<?php
include 'includes/auth.php';
include 'db.php';

// ================= FILTERS =================
$room_number = $_GET['room_number'] ?? '';
$room_type        = $_GET['room_type'] ?? '';
$status      = $_GET['status'] ?? '';
$search      = $_GET['search'] ?? '';

// ================= BUILD WHERE =================
$where = [];

if($room_number){
    $where[] = "r.room_number = '".$conn->real_escape_string($room_number)."'";
}
if($room_type){
    $where[] = "r.room_type = '".$conn->real_escape_string($room_type)."'";
}
if($status){
    $where[] = "r.status = '".$conn->real_escape_string($status)."'";
}
if($search){
    $s = $conn->real_escape_string($search);
    $where[] = "(r.room_number LIKE '%$s%' OR r.capacity LIKE '%$s%')";
}

$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";

// ================= FETCH ROOMS =================
$query = "SELECT r.room_number, r.room_type, r.status, r.price, r.capacity
          FROM rooms r
          $where_sql
          ORDER BY r.room_number ASC";
$result = $conn->query($query);

// ================= EXPORT TO EXCEL =================
header("Content-room_type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=rooms_report_" . date('Ymd_His') . ".xls");
header("Pragma: no-cache");
header("Expires: 0");

echo "<table border='1'>";
echo "<tr style='background-color:#f2f2f2;'>
        <th>Room Number</th>
        <th>room_type</th>
        <th>Status</th>
        <th>Price (MK)</th>
        <th>capacity</th>
      </tr>";

if($result && $result->num_rows){
    while($row = $result->fetch_assoc()){
        echo "<tr>
                <td>".htmlspecialchars($row['room_number'])."</td>
                <td>".htmlspecialchars($row['room_room_type'])."</td>
                <td>".htmlspecialchars($row['status'])."</td>
                <td>".number_format($row['price'],2)."</td>
                <td>".htmlspecialchars($row['capacity'])."</td>
              </tr>";
    }
} else {
    echo "<tr><td colspan='5' style='text-align:center;'>No rooms found</td></tr>";
}

echo "</table>";
exit;
?>