<?php
require __DIR__ . '/../config/db.php';
require __DIR__ . '/../lib/validation.php';

header('Content-Type: application/json');

// Get request data (plate is optional for preview)
$data = json_decode(file_get_contents("php://input"), true);

// --- Normalize plate: uppercase, remove invalid chars, convert letter O → zero ---
$plate = strtoupper(
    str_replace('O', '0', preg_replace("/[^A-Z0-9]/", "", $data['plate'] ?? ''))
);

// Find property by domain
$currentDomain = $_SERVER['HTTP_HOST'];
$stmt = $pdo->prepare("SELECT * FROM hoa_account WHERE URL = ? AND rec_deleted = 'n' LIMIT 1");
$stmt->execute([$currentDomain]);
$hoa = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$hoa) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid property"]);
    exit;
}

// ------------------------------
// Determine stay mode (new field)
// ------------------------------
$stayMode = isset($hoa['stay_mode']) && in_array(strtolower($hoa['stay_mode']), ['rolling', 'monthly'])
    ? strtolower($hoa['stay_mode'])
    : 'rolling';

// If no plate yet, just show full property allowance
if (!$plate) {
    $allowedDays = (int)$hoa['parkingDays'];
    $options = [];
    for ($i = 1; $i <= $allowedDays; $i++) {
        $options[] = $i;
    }

    echo json_encode([
        "rules" => [
            "remaining_days" => $allowedDays,
            "available_options" => $options,
            "stay_mode" => $stayMode
        ]
    ]);
    exit;
}

// Run validation in preview mode
$result = validateRegistration($hoa, ["plate" => $plate], true);

// If validation fails (like banned, no days left, etc.) → return the error
if (!$result['status']) {
    http_response_code(200); // still 200 so frontend handles gracefully
    echo json_encode([
        "error" => $result['message'],
        "rules" => [
            "remaining_days" => 0,
            "available_options" => [],
            "stay_mode" => $stayMode
        ]
    ]);
    exit;
}

// Success → return the available days
echo json_encode([
    "rules" => [
        "remaining_days" => $result['remaining_days'],
        "available_options" => $result['available_options'],
        "stay_mode" => $stayMode
    ]
]);