<?php
// lib/validation.php

/**
 * Validates guest registration against property rules.
 *
 * @param array $hoa       Property row (from hoa_account).
 * @param array $visitor   Visitor details (plate, visit_length_days, etc).
 * @param bool  $preview   If true, returns remaining days/options but does NOT block.
 * 
 * @return array
 */
function validateRegistration($hoa, $visitor, $preview = false) {
    global $pdo;

    $plate  = $visitor['plate'] ?? '';
    $length = (int)($visitor['visit_length_days'] ?? 0);

    if (!$plate) {
        return ["status" => false, "message" => "Missing license plate."];
    }

    // ---------------------------
    // 🚫 Step 1: Check banned list (plate-only, no state)
    // ---------------------------
    if (isBanned($plate, $hoa['hoa_account_id'])) {
        return [
            "status" => false,
            "message" => "This vehicle is banned and cannot be registered at this property."
        ];
    }

    // ---------------------------
    // Step 2: Pull property rules
    // ---------------------------
    $ruleStmt = $pdo->prepare("
        SELECT daysOfStay, daysOfReset, stay_mode 
        FROM hoa_account 
        WHERE hoa_account_id = ? LIMIT 1
    ");
    $ruleStmt->execute([$hoa['hoa_account_id']]);
    $rules = $ruleStmt->fetch(PDO::FETCH_ASSOC);

    if (!$rules) {
        return ["status" => false, "message" => "Property rules not found."];
    }

    $allowedDays = (int)$rules['daysOfStay'];   // max allowed days
    $periodDays  = (int)$rules['daysOfReset'];  // length of rolling window
    $stayMode    = isset($rules['stay_mode']) && in_array(strtolower($rules['stay_mode']), ['rolling', 'monthly'])
        ? strtolower($rules['stay_mode'])
        : 'rolling';

    // ---------------------------
    // Step 3: Calculate used days (depending on stay_mode)
    // ---------------------------
    if ($stayMode === 'monthly') {
        // ✅ MONTHLY MODE: Count overlapping days within the current calendar month only
        $checkStmt = $pdo->prepare("
            SELECT SUM(
                CEIL(
                    TIMESTAMPDIFF(
                        HOUR,
                        GREATEST(arrival_date, DATE_FORMAT(CURDATE(), '%Y-%m-01')),
                        LEAST(departure_date, LAST_DAY(CURDATE()) + INTERVAL 1 DAY)
                    ) / 24
                )
            ) AS used_days
            FROM parking_lots
            WHERE tag_number = ?
              AND hoa_account_id = ?
              AND rec_deleted = 'n'
              AND (
                    departure_date >= DATE_FORMAT(CURDATE(), '%Y-%m-01')
                AND arrival_date <  (LAST_DAY(CURDATE()) + INTERVAL 1 DAY)
              )
        ");
        $checkStmt->execute([$plate, $hoa['hoa_account_id']]);
    } else {
        // ROLLING MODE: Count days used within the rolling window (last N days)
        $checkStmt = $pdo->prepare("
            SELECT SUM(
                CEIL(
                    TIMESTAMPDIFF(
                        HOUR,
                        GREATEST(arrival_date, DATE_SUB(NOW(), INTERVAL ? DAY)),
                        LEAST(departure_date, NOW())
                    ) / 24
                )
            ) AS used_days
            FROM parking_lots
            WHERE tag_number = ?
              AND hoa_account_id = ?
              AND rec_deleted = 'n'
              AND departure_date >= DATE_SUB(NOW(), INTERVAL ? DAY)
        ");
        $checkStmt->execute([$periodDays, $plate, $hoa['hoa_account_id'], $periodDays]);
    }

    $row = $checkStmt->fetch(PDO::FETCH_ASSOC);
    $usedDays = (int)($row['used_days'] ?? 0);
    $remainingDays = max(0, $allowedDays - $usedDays);

    // ---------------------------
    // Step 4: Preview mode
    // ---------------------------
    if ($preview) {
        $options = [];
        for ($i = 1; $i <= $remainingDays; $i++) {
            $options[] = $i;
        }
        return [
            "status" => true,
            "remaining_days" => $remainingDays,
            "available_options" => $options,
            "stay_mode" => $stayMode
        ];
    }

    // ---------------------------
    // Step 5: Enforce limits
    // ---------------------------
    if ($length > $remainingDays) {
        return [
            "status" => false,
            "message" => "You requested {$length} days but only {$remainingDays} days are available this " .
                         ($stayMode === 'monthly' ? 'month.' : 'period.')
        ];
    }

    return [
        "status" => true,
        "remaining_days" => $remainingDays,
        "stay_mode" => $stayMode
    ];
}

/**
 * 🚫 Check if plate is banned at this property.
 */
function isBanned($plate, $hoa_account_id) {
    global $pdo;
    $stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM parking_lots 
        WHERE tag_number = ? 
          AND hoa_account_id = ? 
          AND banned = 'y' 
          AND rec_deleted = 'n'
    ");
    $stmt->execute([$plate, $hoa_account_id]);
    return $stmt->fetchColumn() > 0;
}