<?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, platform, account_name, auth_type, expires_at, provider_id, enabled, created_at, updated_at FROM accounts 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);
  $platform = smm_str($b["platform"] ?? "");
  $account_name = smm_str($b["account_name"] ?? "");
  $auth_type = smm_str($b["auth_type"] ?? "manual");
  $access_token = smm_str($b["access_token"] ?? "");
  $refresh_token = smm_str($b["refresh_token"] ?? "");
  $expires_at = smm_str($b["expires_at"] ?? "");
  $provider_id = intval($b["provider_id"] ?? 0);
  $enabled = intval($b["enabled"] ?? 1);
  $token_json = json_encode($b["token_json"] ?? new stdClass(), JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

  if ($platform==="" || $access_token==="") smm_json_response(["ok"=>false,"error"=>"platform and access_token are required"], 400);

  $now = smm_now_iso();
  if ($id>0) {
    $st = $pdo->prepare("UPDATE accounts SET platform=:p, account_name=:n, auth_type=:a, access_token=:t, refresh_token=:r, expires_at=:e, token_json=:j, provider_id=:pid, enabled=:en, updated_at=:u WHERE id=:id");
    $st->execute([":p"=>$platform,":n"=>$account_name,":a"=>$auth_type,":t"=>$access_token,":r"=>$refresh_token,":e"=>$expires_at,":j"=>$token_json,":pid"=>$provider_id,":en"=>$enabled,":u"=>$now,":id"=>$id]);
    smm_json_response(["ok"=>true,"id"=>$id]);
  } else {
    $st = $pdo->prepare("INSERT INTO accounts (platform,account_name,auth_type,access_token,refresh_token,expires_at,token_json,provider_id,enabled,created_at,updated_at)
      VALUES (:p,:n,:a,:t,:r,:e,:j,:pid,:en,:c,:u)");
    $st->execute([":p"=>$platform,":n"=>$account_name,":a"=>$auth_type,":t"=>$access_token,":r"=>$refresh_token,":e"=>$expires_at,":j"=>$token_json,":pid"=>$provider_id,":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 accounts WHERE id=:id");
  $st->execute([":id"=>$id]);
  smm_json_response(["ok"=>true]);
}

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