<?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 {
    $db = new SQLite3($dbFile);
    $stmt = $db->prepare("SELECT code, expires_at, status, client_name, owner FROM codes WHERE code = :code LIMIT 1");
    $stmt->bindValue(':code', $code, SQLITE3_TEXT);
    $result = $stmt->execute();
    $row = $result ? $result->fetchArray(SQLITE3_ASSOC) : false;

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

    if (($row['status'] ?? 'active') === 'blocked') {
        echo json_encode([
            "ok" => false,
            "reason" => "blocked",
            "expires_at" => $row['expires_at'] ?? null
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $expiresAt = trim((string)$row['expires_at']);
    $now = new DateTime('now');
    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $expiresAt)) {
        $exp = DateTime::createFromFormat('Y-m-d H:i:s', $expiresAt . ' 23:59:59');
    } else {
        $exp = new DateTime($expiresAt);
    }

    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,
            "client_name" => $row['client_name'] ?? null,
            "owner" => $row['owner'] ?? null,
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

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