<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/csrf.php";

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
    http_response_code(405);
    echo json_encode(["success" => false, "error" => "method_not_allowed"]);
    exit;
}

$raw = file_get_contents("php://input");
$data = json_decode((string)$raw, true);
if (!is_array($data)) {
    $data = $_POST;
}
if (!is_array($data)) {
    $data = [];
}

if (!requireCsrfFromPayload($data, "csrf")) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "csrf_failed"]);
    exit;
}

$accepted = (int)($data["accepted"] ?? 0) === 1;
if (!$accepted) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "terms_not_accepted"]);
    exit;
}

$userId = (int)($_SESSION["user"]["id"] ?? 0);
if ($userId <= 0) {
    http_response_code(401);
    echo json_encode(["success" => false, "error" => "unauthorized"]);
    exit;
}

$termsVersion = trim((string)($data["terms_version"] ?? "v1"));
if ($termsVersion === "") {
    $termsVersion = "v1";
}

try {
    $stmt = $pdo->prepare("
        UPDATE users
        SET terms_accepted_at = NOW(),
            terms_version = ?
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$termsVersion, $userId]);

    echo json_encode(["success" => true]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(["success" => false, "error" => "save_failed"]);
}
