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

$dbFile = __DIR__ . '/.db.db';

if (!file_exists($dbFile)) {
    echo json_encode([
        "ScKit-cd5dfe3dce9c84e49996ae95918e0636" => false
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$code = '';

// Acepta POST o GET para pruebas
if (isset($_POST['code'])) {
    $code = trim($_POST['code']);
} elseif (isset($_GET['code'])) {
    $code = trim($_GET['code']);
}

if ($code === '') {
    echo json_encode([
        "ScKit-cd5dfe3dce9c84e49996ae95918e0636" => false
    ], JSON_UNESCAPED_UNICODE);
    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([
            "ScKit-cd5dfe3dce9c84e49996ae95918e0636" => false
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $expiresAt = trim((string)$row['expires_at']);

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

    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $expiresAt)) {
        $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([
            "ScKit-cd5dfe3dce9c84e49996ae95918e0636" => false
        ], 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([
            "ScKit-cd5dfe3dce9c84e49996ae95918e0636" => false
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    echo json_encode([
        "ScKit-cd5dfe3dce9c84e49996ae95918e0636" => true,
        "ScKit-e77ee60e4cab85ef6a925038bcfe740c" => "VIP PREMIUM",
        "ScKit-72eb8c78cc4605979601217f9820e0c2" => $expiresAt,
        "ScKit-d666eff642c699f88fb1dd6c19c755b1" => $hoursLeft,
        "ScKit-661d9298b34c56abfd223c627f1c41856f0d5336" => "ATIVO",
        "ScKit-bc9b22a57e0811744e8b4247964d72d3" => "LOGIN OK",

        // Extras de debug opcionales (no afectan)
        "ok" => true,
        "expires_at" => $expiresAt,
        "days_left" => $daysLeft,
        "hours_left" => $hoursLeft,
        "seconds_left" => $secondsLeft
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    echo json_encode([
        "ScKit-cd5dfe3dce9c84e49996ae95918e0636" => false
    ], JSON_UNESCAPED_UNICODE);
}
?>