<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Occupancy Forecast PDF';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('money_fmt')) {
    function money_fmt($amount): string
    {
        return number_format((float)$amount, 2);
    }
}

if (!function_exists('pct_fmt')) {
    function pct_fmt($value): string
    {
        return number_format((float)$value, 1) . '%';
    }
}

$today = date('Y-m-d');
$dateFrom = trim((string)($_GET['date_from'] ?? $today));
$dateTo = trim((string)($_GET['date_to'] ?? date('Y-m-d', strtotime($today . ' +13 days'))));
$propertyId = (int)($_GET['property_id'] ?? 0);

$errors = [];
$properties = [];
$totalRooms = 0;
$days = [];
$dailyData = [];
$propertyLabel = 'All Properties';

if (strtotime($dateFrom) === false || strtotime($dateTo) === false) {
    $errors[] = 'Invalid date range.';
}
if (!$errors && $dateFrom > $dateTo) {
    $errors[] = 'Date from cannot be after date to.';
}
if (!$errors) {
    $d1 = new DateTime($dateFrom);
    $d2 = new DateTime($dateTo);
    $diffDays = (int)$d1->diff($d2)->days;
    if ($diffDays > 92) {
        $errors[] = 'Please choose a range of 93 days or less.';
    }
}

try {
    $stmt = $pdo->query("
        SELECT id, name, code
        FROM properties
        WHERE is_active = 1
        ORDER BY name ASC
    ");
    $properties = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $properties = [];
}

if ($propertyId > 0) {
    try {
        $stmt = $pdo->prepare("
            SELECT name, code
            FROM properties
            WHERE id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $propertyId]);
        $prop = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($prop) {
            $propertyLabel = trim((string)($prop['name'] ?? ''));
            if (!empty($prop['code'])) {
                $propertyLabel .= ' (' . $prop['code'] . ')';
            }
        }
    } catch (Throwable $e) {
    }
}

/* total room stock */
if (!$errors) {
    try {
        $sql = "SELECT COUNT(*) FROM rooms WHERE 1=1";
        $params = [];

        if ($propertyId > 0) {
            $sql .= " AND property_id = :property_id";
            $params[':property_id'] = $propertyId;
        }

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $totalRooms = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

/* date series */
if (!$errors) {
    $start = new DateTime($dateFrom);
    $end = new DateTime($dateTo);
    $endInclusive = clone $end;
    $endInclusive->modify('+1 day');

    $period = new DatePeriod($start, new DateInterval('P1D'), $endInclusive);
    foreach ($period as $dt) {
        $days[] = $dt->format('Y-m-d');
    }
}

/* daily forecast */
if (!$errors && $days) {
    try {
        $propertyOrderFilter = $propertyId > 0 ? " AND o.property_id = :property_id " : "";
        $propertyRoomFilter  = $propertyId > 0 ? " AND r.property_id = :property_id " : "";

        foreach ($days as $day) {
            $dailyData[$day] = [
                'occupied_rooms' => 0,
                'vacant_rooms'   => 0,
                'arrivals'       => 0,
                'departures'     => 0,
                'occupancy_pct'  => 0,
            ];

            $sql = "
                SELECT COUNT(DISTINCT rmg.room_id)
                FROM order_rooming rmg
                INNER JOIN orders o ON o.id = rmg.order_id
                INNER JOIN rooms r ON r.id = rmg.room_id
                WHERE DATE(o.check_in) <= :day
                  AND DATE(o.check_out) >= :day
                  AND rmg.room_id IS NOT NULL
                  $propertyRoomFilter
            ";
            $params = [':day' => $day];
            if ($propertyId > 0) {
                $params[':property_id'] = $propertyId;
            }
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $occupiedRooms = (int)$stmt->fetchColumn();

            $sql = "
                SELECT COUNT(*)
                FROM orders o
                WHERE DATE(o.check_in) = :day
                $propertyOrderFilter
            ";
            $params = [':day' => $day];
            if ($propertyId > 0) {
                $params[':property_id'] = $propertyId;
            }
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $arrivals = (int)$stmt->fetchColumn();

            $sql = "
                SELECT COUNT(*)
                FROM orders o
                WHERE DATE(o.check_out) = :day
                $propertyOrderFilter
            ";
            $params = [':day' => $day];
            if ($propertyId > 0) {
                $params[':property_id'] = $propertyId;
            }
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $departures = (int)$stmt->fetchColumn();

            $vacantRooms = max(0, $totalRooms - $occupiedRooms);
            $occupancyPct = $totalRooms > 0 ? ($occupiedRooms / $totalRooms) * 100 : 0;

            $dailyData[$day] = [
                'occupied_rooms' => $occupiedRooms,
                'vacant_rooms'   => $vacantRooms,
                'arrivals'       => $arrivals,
                'departures'     => $departures,
                'occupancy_pct'  => $occupancyPct,
            ];
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

/* summary */
$avgOcc = 0;
$maxOcc = 0;
$minOcc = 0;
$totalArrivals = 0;
$totalDepartures = 0;

if ($dailyData) {
    $occValues = array_map(function ($r) {
        return (float)$r['occupancy_pct'];
    }, $dailyData);

    $avgOcc = array_sum($occValues) / max(1, count($occValues));
    $maxOcc = max($occValues);
    $minOcc = min($occValues);

    foreach ($dailyData as $r) {
        $totalArrivals += (int)$r['arrivals'];
        $totalDepartures += (int)$r['departures'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Occupancy Forecast PDF</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        :root{
            --bg:#f5f7fb;
            --card:#ffffff;
            --ink:#1f2937;
            --muted:#6b7280;
            --line:#e5e7eb;
            --primary:#1d4ed8;
            --success:#15803d;
            --warning:#b45309;
            --danger:#b91c1c;
            --dark:#111827;
        }
        *{box-sizing:border-box}
        body{
            margin:0;
            font-family:Arial, Helvetica, sans-serif;
            color:var(--ink);
            background:var(--bg);
        }
        .wrap{
            max-width:1200px;
            margin:0 auto;
            padding:24px;
        }
        .toolbar{
            display:flex;
            justify-content:space-between;
            align-items:center;
            gap:16px;
            margin-bottom:20px;
        }
        .btn{
            border:1px solid var(--line);
            background:#fff;
            padding:10px 14px;
            border-radius:10px;
            text-decoration:none;
            color:var(--ink);
            font-size:14px;
            cursor:pointer;
        }
        .btn.primary{
            background:var(--primary);
            border-color:var(--primary);
            color:#fff;
        }
        .report{
            background:var(--card);
            border:1px solid var(--line);
            border-radius:18px;
            overflow:hidden;
        }
        .report-header{
            padding:24px;
            border-bottom:1px solid var(--line);
            background:linear-gradient(135deg,#eef4ff,#ffffff);
        }
        .report-title{
            font-size:28px;
            font-weight:800;
            margin:0 0 6px 0;
        }
        .report-sub{
            color:var(--muted);
            font-size:14px;
        }
        .grid{
            display:grid;
            grid-template-columns:repeat(6,1fr);
            gap:14px;
            padding:20px 24px;
        }
        .metric{
            border:1px solid var(--line);
            border-radius:14px;
            padding:14px 16px;
            background:#fff;
        }
        .metric .label{
            color:var(--muted);
            font-size:12px;
            margin-bottom:6px;
        }
        .metric .value{
            font-size:22px;
            font-weight:800;
        }
        .section{
            padding:0 24px 24px 24px;
        }
        .section-title{
            font-size:18px;
            font-weight:800;
            margin:18px 0 12px;
        }
        table{
            width:100%;
            border-collapse:collapse;
            background:#fff;
            border:1px solid var(--line);
        }
        th,td{
            border-bottom:1px solid var(--line);
            padding:10px 12px;
            font-size:13px;
            vertical-align:top;
            text-align:left;
        }
        th{
            background:#f9fafb;
            font-weight:700;
        }
        .text-right{text-align:right}
        .empty{
            padding:18px;
            border:1px dashed var(--line);
            border-radius:12px;
            background:#fff;
            color:var(--muted);
        }
        .badge{
            display:inline-block;
            padding:4px 8px;
            border-radius:999px;
            font-size:11px;
            font-weight:700;
            color:#fff;
        }
        .b-success{background:var(--success)}
        .b-primary{background:var(--primary)}
        .b-warning{background:var(--warning)}
        .b-danger{background:var(--danger)}
        .footer-note{
            padding:0 24px 24px 24px;
            color:var(--muted);
            font-size:12px;
        }
        @media (max-width:1100px){
            .grid{grid-template-columns:repeat(3,1fr);}
        }
        @media print{
            body{background:#fff}
            .wrap{max-width:none;padding:0}
            .toolbar{display:none!important}
            .report{border:none;border-radius:0}
            .section{break-inside:avoid}
            table{page-break-inside:auto}
            tr{page-break-inside:avoid;page-break-after:auto}
        }
    </style>
</head>
<body>
<div class="wrap">
    <div class="toolbar">
        <div>
            <a href="/rooms/modules/payments/occupancy_forecast.php?date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?><?php echo $propertyId > 0 ? '&property_id=' . $propertyId : ''; ?>" class="btn">Back to Occupancy Forecast</a>
        </div>
        <div>
            <button onclick="window.print()" class="btn primary">Print / Save PDF</button>
        </div>
    </div>

    <div class="report">
        <div class="report-header">
            <h1 class="report-title">Occupancy Forecast Report</h1>
            <div class="report-sub">
                Date Range: <strong><?php echo h($dateFrom); ?></strong> to <strong><?php echo h($dateTo); ?></strong>
                &nbsp; | &nbsp;
                Property: <strong><?php echo h($propertyLabel); ?></strong>
                &nbsp; | &nbsp;
                Generated: <strong><?php echo h(date('Y-m-d H:i:s')); ?></strong>
            </div>
        </div>

        <?php if ($errors): ?>
            <div class="section">
                <div class="section-title">Errors</div>
                <div class="empty">
                    <?php foreach ($errors as $err): ?>
                        <div><?php echo h($err); ?></div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php else: ?>

        <div class="grid">
            <div class="metric">
                <div class="label">Room Stock</div>
                <div class="value"><?php echo number_format($totalRooms); ?></div>
            </div>
            <div class="metric">
                <div class="label">Average Occupancy</div>
                <div class="value"><?php echo pct_fmt($avgOcc); ?></div>
            </div>
            <div class="metric">
                <div class="label">Peak Occupancy</div>
                <div class="value"><?php echo pct_fmt($maxOcc); ?></div>
            </div>
            <div class="metric">
                <div class="label">Low Occupancy</div>
                <div class="value"><?php echo pct_fmt($minOcc); ?></div>
            </div>
            <div class="metric">
                <div class="label">Total Arrivals</div>
                <div class="value"><?php echo number_format($totalArrivals); ?></div>
            </div>
            <div class="metric">
                <div class="label">Total Departures</div>
                <div class="value"><?php echo number_format($totalDepartures); ?></div>
            </div>
        </div>

        <div class="section">
            <div class="section-title">Daily Occupancy Forecast</div>
            <?php if (!$dailyData): ?>
                <div class="empty">No forecast data available.</div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Day</th>
                            <th class="text-right">Rooms</th>
                            <th class="text-right">Occupied</th>
                            <th class="text-right">Vacant</th>
                            <th class="text-right">Arrivals</th>
                            <th class="text-right">Departures</th>
                            <th class="text-right">Occupancy %</th>
                            <th>Level</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($dailyData as $day => $row): ?>
                            <?php
                            $occPct = (float)$row['occupancy_pct'];
                            $levelClass = 'b-success';
                            $levelText = 'Low';
                            if ($occPct >= 85) {
                                $levelClass = 'b-danger';
                                $levelText = 'Very High';
                            } elseif ($occPct >= 65) {
                                $levelClass = 'b-warning';
                                $levelText = 'High';
                            } elseif ($occPct >= 40) {
                                $levelClass = 'b-primary';
                                $levelText = 'Moderate';
                            }
                            ?>
                            <tr>
                                <td><strong><?php echo h($day); ?></strong></td>
                                <td><?php echo h(date('D', strtotime($day))); ?></td>
                                <td class="text-right"><?php echo number_format($totalRooms); ?></td>
                                <td class="text-right"><?php echo number_format($row['occupied_rooms']); ?></td>
                                <td class="text-right"><?php echo number_format($row['vacant_rooms']); ?></td>
                                <td class="text-right"><?php echo number_format($row['arrivals']); ?></td>
                                <td class="text-right"><?php echo number_format($row['departures']); ?></td>
                                <td class="text-right"><?php echo pct_fmt($occPct); ?></td>
                                <td><span class="badge <?php echo h($levelClass); ?>"><?php echo h($levelText); ?></span></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <th colspan="5" class="text-right">Range Totals</th>
                            <th class="text-right"><?php echo number_format($totalArrivals); ?></th>
                            <th class="text-right"><?php echo number_format($totalDepartures); ?></th>
                            <th class="text-right"><?php echo pct_fmt($avgOcc); ?></th>
                            <th></th>
                        </tr>
                    </tfoot>
                </table>
            <?php endif; ?>
        </div>

        <div class="footer-note">
            This report is designed for print/PDF export. Use your browser’s print dialog and select “Save as PDF”.
        </div>

        <?php endif; ?>
    </div>
</div>
</body>
</html>