<?php
declare(strict_types=1);
require_once __DIR__ . "/../app/db.php";
require_once __DIR__ . "/../app/auth.php";

$pdo = smm_db();
$action = $_GET["action"] ?? "list";

if ($action === "list") {
  $rows = $pdo->query("SELECT id,name,platform,auth_url,token_url,scopes,enabled,created_at,updated_at FROM oauth_providers ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
  smm_json_response(["ok"=>true,"rows"=>$rows]);
}

if ($action === "save") {
  $b = smm_read_json_body();
  $id = intval($b["id"] ?? 0);
  $name = smm_str($b["name"] ?? "");
  $platform = smm_str($b["platform"] ?? "");
  $client_id = smm_str($b["client_id"] ?? "");
  $client_secret = smm_str($b["client_secret"] ?? "");
  $auth_url = smm_str($b["auth_url"] ?? "");
  $token_url = smm_str($b["token_url"] ?? "");
  $scopes = smm_str($b["scopes"] ?? "");
  $enabled = intval($b["enabled"] ?? 1);
  $extra_json = json_encode($b["extra_json"] ?? new stdClass(), JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  if ($name===""||$platform===""||$client_id===""||$client_secret===""||$auth_url===""||$token_url===""||$scopes==="") {
    smm_json_response(["ok"=>false,"error"=>"name, platform, client_id, client_secret, auth_url, token_url, scopes required"], 400);
  }
  $now = smm_now_iso();
  if ($id>0) {
    $st=$pdo->prepare("UPDATE oauth_providers SET name=:n,platform=:p,client_id=:cid,client_secret=:cs,auth_url=:au,token_url=:tu,scopes=:s,extra_json=:x,enabled=:en,updated_at=:u WHERE id=:id");
    $st->execute([":n"=>$name,":p"=>$platform,":cid"=>$client_id,":cs"=>$client_secret,":au"=>$auth_url,":tu"=>$token_url,":s"=>$scopes,":x"=>$extra_json,":en"=>$enabled,":u"=>$now,":id"=>$id]);
    smm_json_response(["ok"=>true,"id"=>$id]);
  } else {
    $st=$pdo->prepare("INSERT INTO oauth_providers (name,platform,client_id,client_secret,auth_url,token_url,scopes,extra_json,enabled,created_at,updated_at)
      VALUES (:n,:p,:cid,:cs,:au,:tu,:s,:x,:en,:c,:u)");
    $st->execute([":n"=>$name,":p"=>$platform,":cid"=>$client_id,":cs"=>$client_secret,":au"=>$auth_url,":tu"=>$token_url,":s"=>$scopes,":x"=>$extra_json,":en"=>$enabled,":c"=>$now,":u"=>$now]);
    smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId())]);
  }
}

if ($action === "delete") {
  $b=smm_read_json_body();
  $id=intval($b["id"]??0);
  if($id<=0) smm_json_response(["ok"=>false,"error"=>"id required"],400);
  $st=$pdo->prepare("DELETE FROM oauth_providers WHERE id=:id");
  $st->execute([":id"=>$id]);
  smm_json_response(["ok"=>true]);
}

smm_json_response(["ok"=>false,"error"=>"Unknown action"], 400);
