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

$dbFile = __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;
    }

    $expiresAt = trim((string)$row['expires_at']);
    
    // Zona horaria de Ecuador (solo para comparación, no modifica tu BD)
    $zonaEcuador = new DateTimeZone('America/Guayaquil');
    $now = new DateTime('now', $zonaEcuador);
    $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', $zonaEcuador);
    } else {
        try {
            $exp = new DateTime($expiresAt, $zonaEcuador);
        } 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"]);
}
?>