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

$user_role = $_SESSION['role'] ?? 'guest';

// Only admin or manager can manage rooms
function canManageRooms() {
    global $user_role;
    return in_array($user_role, ['admin','manager']);
}

// ==================== Handle Delete Room ====================
if(isset($_GET['delete']) && canManageRooms()){
    $room_id = intval($_GET['delete']);
    $conn->query("DELETE FROM rooms WHERE id=$room_id");
    echo "<script>window.location='room_availability.php';</script>";
    exit;
} elseif(isset($_GET['delete'])){
    echo "<div class='alert alert-danger'>You do not have permission to delete rooms.</div>";
}

// ==================== Filters ====================
$status_filter = $_GET['status'] ?? '';
$type_filter = $_GET['room_type'] ?? '';

$where = [];
if($status_filter) $where[] = "status = '".$conn->real_escape_string($status_filter)."'";
if($type_filter) $where[] = "room_type = '".$conn->real_escape_string($type_filter)."'";
$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";

// ==================== Fetch Rooms ====================
$rooms = $conn->query("SELECT * FROM rooms $where_sql ORDER BY room_number");

// ==================== Fetch Room Types ====================
$room_types = $conn->query("SELECT DISTINCT room_type FROM rooms ORDER BY room_type");

// ==================== Room Stats ====================
$stats_query = $conn->query("SELECT 
    COUNT(*) AS total,
    SUM(status='Available') AS available,
    SUM(status='Occupied') AS occupied,
    SUM(status='Reserved') AS reserved,
    SUM(status='Maintenance') AS maintenance,
    SUM(status='Dirty') AS dirty,
    SUM(status='Out of Order') AS out_of_order
    FROM rooms");
$stats = $stats_query->fetch_assoc();


// ==================== Room Type Stats ====================
$type_stats = $conn->query("
    SELECT room_type, COUNT(*) AS total 
    FROM rooms 
    GROUP BY room_type 
    ORDER BY room_type
");

?>

<style>
.room-box{
    border-radius:10px;
    padding:15px;
    text-align:center;
    color:#fff;
    font-weight:bold;
    cursor:pointer;
    transition: transform 0.2s;
}
.room-box:hover{
    transform: scale(1.05);
}
.available{background:#28a745;}
.occupied{background:#dc3545;}
.reserved{background:#ffc107;color:#000;}
.maintenance{background:#6c757d;}
.dirty{background:#6f42c1;}
.out-of-order{background:#343a40;}
.room-actions { margin-top:5px; }
.stat-box{
    border-radius:10px;
    padding:15px;
    text-align:center;
    color:#fff;
    font-weight:bold;
}
.type-box{
    border-radius:10px;
    padding:12px;
    text-align:center;
    font-weight:bold;
    background:#0d6efd;
    color:#fff;
    transition: transform 0.2s;
}
.type-box:hover{
    transform: scale(1.05);
}

.stat-total{background:#6c757d;}
.stat-available{background:#28a745;}
.stat-occupied{background:#dc3545;}
.stat-reserved{background:#ffc107;color:#000;}
.stat-maintenance{background:#6c757d;}
.stat-dirty{background:#6f42c1;}
.stat-out{background:#343a40;}
</style>

<div class="container mt-4">
    <?php $username = $_SESSION['username'] ?? 'Guest'; ?>
    
    <!-- ================= WELCOME MESSAGE ================= -->
    <div class="welcome-msg mb-3">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4>Room Availability</h4>
        <?php if(canManageRooms()): ?>
            <a href="add_room.php" class="btn btn-success"><i class="fa fa-plus"></i> Add Room</a>
        <?php endif; ?>
    </div>

    <!-- ==================== Room Stats ==================== -->
    <div class="row g-3 mb-3">
        <div class="col-md-2"><div class="stat-box stat-total">Total<br><?= $stats['total'] ?></div></div>
        <div class="col-md-2"><div class="stat-box stat-available">Available<br><?= $stats['available'] ?></div></div>
        <div class="col-md-2"><div class="stat-box stat-occupied">Occupied<br><?= $stats['occupied'] ?></div></div>
        <div class="col-md-2"><div class="stat-box stat-reserved">Reserved<br><?= $stats['reserved'] ?></div></div>
        <div class="col-md-2"><div class="stat-box stat-maintenance">Maintenance<br><?= $stats['maintenance'] ?></div></div>
        <div class="col-md-2"><div class="stat-box stat-dirty">Dirty<br><?= $stats['dirty'] ?></div></div>
        <div class="col-md-2 mt-2"><div class="stat-box stat-out">Out of Order<br><?= $stats['out_of_order'] ?></div></div>
    </div>
<!-- ==================== Room Type Stats ==================== -->
<div class="row g-3 mb-4">
    <div class="col-12">
        <h6 class="text-muted"><i class="fa fa-layer-group"></i> Rooms by Type</h6>
    </div>

    <?php while($ts = $type_stats->fetch_assoc()): ?>
        <div class="col-md-2">
            <div class="type-box">
                <?= htmlspecialchars($ts['room_type']) ?><br>
                <span style="font-size:18px"><?= $ts['total'] ?></span>
            </div>
        </div>
    <?php endwhile; ?>
</div>

    <hr>

    <!-- ==================== Filters ==================== -->
    <form method="GET" class="row g-3 mb-3">
        <div class="col-md-3">
            <select name="status" class="form-control">
                <option value="">-- All Status --</option>
                <option value="Available" <?= $status_filter=='Available'?'selected':'' ?>>Available</option>
                <option value="Occupied" <?= $status_filter=='Occupied'?'selected':'' ?>>Occupied</option>
                <option value="Reserved" <?= $status_filter=='Reserved'?'selected':'' ?>>Reserved</option>
                <option value="Maintenance" <?= $status_filter=='Maintenance'?'selected':'' ?>>Maintenance</option>
                <option value="Dirty" <?= $status_filter=='Dirty'?'selected':'' ?>>Dirty</option>
                <option value="Out of Order" <?= $status_filter=='Out of Order'?'selected':'' ?>>Out of Order</option>
            </select>
        </div>
        <div class="col-md-3">
            <select name="room_type" class="form-control">
                <option value="">-- All Types --</option>
                <?php while($type = $room_types->fetch_assoc()): ?>
                    <option value="<?= $type['room_type'] ?>" <?= $type_filter==$type['room_type']?'selected':'' ?>><?= $type['room_type'] ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary w-100">Filter</button>
        </div>
    </form>

    <!-- ==================== Room Grid ==================== -->
    <div class="row g-3">
        <?php while($r=$rooms->fetch_assoc()):
            $class='available';
            switch($r['status']){
                case 'Occupied': $class='occupied'; break;
                case 'Reserved': $class='reserved'; break;
                case 'Maintenance': $class='maintenance'; break;
                case 'Dirty': $class='dirty'; break;
                case 'Out of Order': $class='out-of-order'; break;
            }
        ?>
        <div class="col-md-2">
            <div class="room-box <?= $class ?>" 
                 data-bs-toggle="tooltip" 
                 title="Room: <?= $r['room_number'] ?>&#10;Type: <?= $r['room_type'] ?>&#10;Capacity: <?= $r['capacity'] ?>&#10;Price: MK <?= number_format($r['price'],2) ?>&#10;Status: <?= $r['status'] ?>">
                Room <?= $r['room_number'] ?><br>
                <small><?= $r['status'] ?></small>

                <?php if(canManageRooms()): ?>
                    <div class="room-actions">
                        <a href="edit_room.php?id=<?= $r['id'] ?>" class="btn btn-warning btn-sm mb-1 w-100"><i class="fa fa-edit"></i> Edit</a>
                        <a href="?delete=<?= $r['id'] ?>" onclick="return confirm('Are you sure you want to remove this room?')" class="btn btn-danger btn-sm w-100"><i class="fa fa-trash"></i> Remove</a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endwhile; ?>
    </div>
</div>

<script>
// Enable Bootstrap tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script>

<?php include 'includes/footer.php'; ?>
