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

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

// ---------------------------
// Get request data
// ---------------------------
$data = json_decode(file_get_contents("php://input"), true);

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

$visitor = [
    "plate" => $normalizedPlate,
    "state" => strtoupper($data['state'] ?? ''), // still stored, but not enforced
    "email" => $data['email'] ?? null,
    "phone" => preg_replace('/\D/', '', $data['phone'] ?? ''),
    "address" => trim($data['address'] ?? ''),
    "visit_length_days" => (int)($data['visit_length_days'] ?? 1),
    "unit_number" => trim($data['unit_number'] ?? ''),
    "resident_pin" => trim($data['resident_pin'] ?? '')
];

// ---------------------------
// Property lookup
// ---------------------------
$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;
}

// ---------------------------
// PIN ENFORCEMENT
// ---------------------------
if ($hoa['PIN_enabled'] === 'y') {
    if (!$visitor['unit_number'] || !$visitor['resident_pin']) {
        echo json_encode(["error" => "Resident Unit and PIN are required."]);
        exit;
    }

    $pinCheck = $pdo->prepare("SELECT * FROM PINS_tbl 
                               WHERE hoa_fk_id = ? 
                                 AND unit = ? 
                                 AND resident_pin = ? 
                                 AND active = 'y' LIMIT 1");
    $pinCheck->execute([$hoa['hoa_account_id'], $visitor['unit_number'], $visitor['resident_pin']]);
    $pinRow = $pinCheck->fetch(PDO::FETCH_ASSOC);

    if (!$pinRow) {
        echo json_encode(["error" => "Invalid unit/PIN combination. Please confirm with the resident."]);
        exit;
    }
}

// ---------------------------
// BANNED TAG ENFORCEMENT (plate only, no state)
// ---------------------------
$banCheck = $pdo->prepare("SELECT COUNT(*) FROM parking_lots 
                           WHERE tag_number = ? 
                             AND hoa_account_id = ? 
                             AND banned = 'y' 
                             AND rec_deleted = 'n'");
$banCheck->execute([$visitor['plate'], $hoa['hoa_account_id']]);
if ($banCheck->fetchColumn() > 0) {
    echo json_encode(["error" => "This vehicle is banned from guest registration at this property."]);
    exit;
}

// ---------------------------
// Run property-driven validation (days, active tickets, etc.)
// ---------------------------
$validation = validateRegistration($hoa, $visitor);
if (!$validation['status']) {
    http_response_code(400);
    echo json_encode(["error" => $validation['message']]);
    exit;
}

// ---------------------------
// Create Registration
// ---------------------------
date_default_timezone_set('America/New_York');
$arrival   = date("Y-m-d H:i:s");
$departure = date("Y-m-d H:i:s", strtotime("+{$visitor['visit_length_days']} days"));

// Generate secure token
$ticket_token = bin2hex(random_bytes(16));

$stmt = $pdo->prepare("INSERT INTO parking_lots 
    (hoa_account_id, tag_number, stateProvidence, residence_address, unit_number, resident_pin, 
     arrival_date, departure_date, email, phone, rec_deleted, ticket_token) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'n', ?)");

$stmt->execute([
    $hoa['hoa_account_id'],
    $visitor['plate'],
    $visitor['state'], // still stored for records
    $visitor['address'],
    $visitor['unit_number'],
    $visitor['resident_pin'],
    $arrival,
    $departure,
    $visitor['email'],
    $visitor['phone'],
    $ticket_token
]);

$ticket_id = $pdo->lastInsertId();

// ---------------------------
// Build ticket object
// ---------------------------
$ticket = [
    "id" => $ticket_id,
    "token" => $ticket_token,
    "plate" => $visitor['plate'],
    "state" => $visitor['state'],
    "address" => $visitor['address'],
    "email" => $visitor['email'],
    "phone" => $visitor['phone'],
    "arrival" => $arrival,
    "expiration_time" => $departure
];

// ---------------------------
// Build ticket link dynamically
// ---------------------------
$baseUrl   = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
$baseUrl  .= "://{$_SERVER['HTTP_HOST']}";

// Strip off /api/... from SCRIPT_NAME so we always point to /ui/
$projectRoot = preg_replace('#/api.*$#', '', $_SERVER['SCRIPT_NAME']);
$uiUrl = rtrim($projectRoot, '/\\') . '/ui/index.html';

$ticketUrl = $baseUrl . $uiUrl . "?ticket={$ticket_id}&token={$ticket_token}";

// ---------------------------
// SMS confirmation
// ---------------------------
$message = "🚗 {$hoa['hoa_account_name']} Parking Confirmed\n{$ticketUrl}\n\n**DO NOT REPLY**";
sendSMS($visitor['phone'], $message);

// ---------------------------
// Wallet passes (placeholders for now)
// ---------------------------
$applePass  = generateApplePass($ticket);
$googlePass = generateGooglePass($ticket);

// ---------------------------
// Response
// ---------------------------
echo json_encode([
    "ticket" => $ticket,
    "wallet" => [
        "apple" => $applePass,
        "google" => $googlePass
    ]
]);