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

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

// Get domain to match property
$currentDomain = $_SERVER['HTTP_HOST'];

$stmt = $pdo->prepare("SELECT hoa_account_id, hoa_account_name, HOA_statement, city, daysOfStay, parkingStayOptions, PIN_enabled, rec_deleted, stay_mode
                       FROM hoa_account 
                       WHERE URL = ? 
                       LIMIT 1");
$stmt->execute([$currentDomain]);
$hoa = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$hoa) {
    http_response_code(404);
    echo json_encode([
        "status"  => "not_found",
        "message" => "This property is not registered in the system."
    ]);
    exit;
}

// Handle suspended/maintenance/deleted
switch (strtolower($hoa['rec_deleted'])) {
    case 'y':
        echo json_encode([
            "status"  => "deleted",
            "message" => "This property has been removed and is no longer active."
        ]);
        exit;
    case 's':
        echo json_encode([
            "status"  => "suspended",
            "message" => "This property account is temporarily suspended. Please check back later."
        ]);
        exit;
    case 'm':
        echo json_encode([
            "status"  => "maintenance",
            "message" => "This property is currently under maintenance. Please try again soon."
        ]);
        exit;
    case 'n':
    default:
        // Active — continue
        break;
}

// Normalize stay options
$maxDays = (int)$hoa['daysOfStay'];
$stayOptions = [];

// If explicit options exist, parse them
if (!empty($hoa['parkingStayOptions'])) {
    $parsed = array_filter(array_map('intval', explode(',', $hoa['parkingStayOptions'])));
    // Validate parsed options
    if ($parsed && max($parsed) <= $maxDays) {
        $stayOptions = $parsed;
    }
}

// If no valid custom options, fallback to full range
if (empty($stayOptions)) {
    $stayOptions = range(1, $maxDays);
}

// Determine stay mode (default to 'rolling' for backward compatibility)
$stayMode = isset($hoa['stay_mode']) && in_array(strtolower($hoa['stay_mode']), ['rolling', 'monthly'])
    ? strtolower($hoa['stay_mode'])
    : 'rolling';

// Build response
$response = [
    "status"        => "active",
    "property_name" => $hoa['hoa_account_name'],
    "statement"     => $hoa['HOA_statement'],
    "city"          => $hoa['city'],
    "stay_options"  => $stayOptions,
    "require_pin"   => strtolower($hoa['PIN_enabled']) === 'y',
    "stay_mode"     => $stayMode, // 👈 NEW FIELD ADDED HERE
    "server_time"   => (new DateTime("now", new DateTimeZone("America/New_York")))->format("Y-m-d H:i:s")
];

echo json_encode($response);