<?php
header('Content-Type: application/json; charset=utf-8');

// Ajuste o caminho do seu banco (mesma pasta do check_code.php)
$dbFile = __DIR__ . '/.db.db'; // se estiver em /api/.db.db
// Se estiver em outro lugar, ajuste: __DIR__ . '/../.db.db'

if (!file_exists($dbFile)) {
    echo json_encode(["ok" => false, "reason" => "db_not_found"]);
    exit;
}

$code = isset($_POST['code']) ? trim($_POST['code']) : '';
if ($code === '') {
    echo json_encode(["ok" => false, "reason" => "missing_code"]);
    exit;
}

try {
    $pdo = new PDO('sqlite:' . $dbFile);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("SELECT code, expires_at FROM codes WHERE code = :code LIMIT 1");
    $stmt->execute([':code' => $code]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        echo json_encode(["ok" => false, "reason" => "not_found"]);
        exit;
    }

    // Compatível com:
    // - "YYYY-MM-DD" (expira no fim do dia)
    // - "YYYY-MM-DD HH:MM:SS" (expira no horário exato)
    $expiresAt = trim((string)$row['expires_at']);

    $now = new DateTime('now');
    $exp = null;

    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $expiresAt)) {
        // Mantém comportamento antigo (válido até o fim da data)
        $exp = DateTime::createFromFormat('Y-m-d H:i:s', $expiresAt . ' 23:59:59');
    } else {
        try {
            $exp = new DateTime($expiresAt);
        } catch (Throwable $e) {
            $exp = null;
        }
    }

    if (!$exp) {
        echo json_encode(["ok" => false, "reason" => "invalid_exp_date"], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $secondsLeft = $exp->getTimestamp() - $now->getTimestamp();
    $daysLeft    = (int)floor($secondsLeft / 86400);
    $hoursLeft   = (int)floor($secondsLeft / 3600);

    if ($secondsLeft < 0) {
        echo json_encode([
            "ok" => false,
            "reason" => "expired",
            "expires_at" => $expiresAt,
            "days_left" => $daysLeft,
            "hours_left" => $hoursLeft,
            "seconds_left" => $secondsLeft,
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    echo json_encode([
        "ok" => true,
        "expires_at" => $expiresAt,
        "days_left" => $daysLeft,
        "hours_left" => $hoursLeft,
        "seconds_left" => $secondsLeft,
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    echo json_encode(["ok" => false, "reason" => "server_error"]);
}
