<?php
// Filename: booking/admin/manage_rooms.php
include '../../config.php';

// --- 1. SECURITY & ADMIN CHECK ---
if (!isset($_SESSION['user_id'])) { header("Location: ../../login.php"); exit; }
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
if (empty(array_intersect($user_roles, ['admin', 'admin_booking']))) {
    die("Access Denied.");
}

// Handle Status Toggle
if(isset($_POST['toggle_id'])) {
    $new_status = ($_POST['current_status'] == 'active') ? 'inactive' : 'active';
    $stmt = $pdo->prepare("UPDATE rooms SET status = ? WHERE id = ?");
    $stmt->execute([$new_status, $_POST['toggle_id']]);
    header("Location: manage_rooms.php?msg=toggled"); exit;
}

// Handle Add Room
if(isset($_POST['add_room'])) {
    // Added try-catch to handle potential DB errors gracefully
    try {
        $stmt = $pdo->prepare("INSERT INTO rooms (name, capacity, location, type, status) VALUES (?, ?, ?, ?, 'active')");
        $stmt->execute([$_POST['name'], $_POST['capacity'], $_POST['location'], $_POST['type']]);
        header("Location: manage_rooms.php?msg=added"); exit;
    } catch (PDOException $e) {
        $error = "Error adding room: " . $e->getMessage();
    }
}

// Fetch Rooms with assigned facilities count
$rooms = $pdo->query("SELECT r.*, (SELECT COUNT(*) FROM room_facilities rf WHERE rf.room_id = r.id) as fac_count 
                      FROM rooms r ORDER BY location, name ASC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Rooms</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; }
        body { background: #f8f9fd; font-family: 'Plus Jakarta Sans', sans-serif; padding-bottom: 80px; }
        .app-header { background: var(--primary-grad); padding: 20px 20px 30px 20px; color: white; border-radius: 0 0 30px 30px; }
        .room-card { background: white; border-radius: 18px; border: none; box-shadow: 0 4px 15px rgba(0,0,0,0.05); overflow: hidden; }
        .nav-pill-custom { background: rgba(255,255,255,0.2); border-radius: 50px; padding: 4px; display: inline-flex; }
        .nav-pill-custom .btn { border-radius: 50px; color: white; border: none; font-size: 0.8rem; font-weight: 600; padding: 5px 15px; }
        .nav-pill-custom .btn.active { background: white; color: #1e293b; }
    </style>
</head>
<body>

<div class="app-header mb-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <a href="manage.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
        <h5 class="mb-0 fw-bold">Resources</h5>
        <div style="width:24px"></div>
    </div>
    <div class="text-center">
        <div class="nav-pill-custom">
            <a href="manage_rooms.php" class="btn active">Rooms</a>
            <a href="manage_facilities.php" class="btn">Facilities</a>
        </div>
    </div>
</div>

<div class="container">
    <?php if(isset($_GET['msg'])): ?>
        <div class="alert alert-success border-0 shadow-sm rounded-3 small py-2 text-center mb-3">Operation successful!</div>
    <?php endif; ?>
    <?php if(isset($error)): ?>
        <div class="alert alert-danger border-0 shadow-sm rounded-3 small py-2 text-center mb-3"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="d-flex justify-content-between align-items-center mb-3 px-2">
        <h6 class="fw-bold text-muted mb-0">Rooms (<?= count($rooms) ?>)</h6>
        <button class="btn btn-primary rounded-pill btn-sm px-3 fw-bold" data-bs-toggle="modal" data-bs-target="#addRoomModal">+ New Room</button>
    </div>

    <div class="row g-3">
        <?php foreach($rooms as $r): ?>
        <div class="col-md-6 col-lg-4">
            <div class="room-card p-3">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <small class="text-muted text-uppercase fw-bold" style="font-size:0.6rem; letter-spacing: 0.5px;"><?= htmlspecialchars($r['location']) ?></small>
                        <h6 class="fw-bold mb-1 text-dark"><?= htmlspecialchars($r['name']) ?></h6>
                        
                        <div class="small text-muted">
                            <i class="bi bi-people me-1"></i> <?= $r['capacity'] ?> Pax • <?= htmlspecialchars($r['type'] ?? 'General') ?>
                        </div>
                        
                    </div>
                    <form method="POST" class="m-0">
                        <input type="hidden" name="toggle_id" value="<?= $r['id'] ?>">
                        <input type="hidden" name="current_status" value="<?= $r['status'] ?>">
                        <button type="submit" class="btn <?= $r['status']=='active'?'btn-light text-success':'btn-outline-danger' ?> btn-sm rounded-pill fw-bold" style="font-size:0.7rem">
                            <?= $r['status']=='active'?'Active':'Inactive' ?>
                        </button>
                    </form>
                </div>
                
                <div class="mt-3 pt-2 border-top d-flex justify-content-between align-items-center">
                    <a href="assign_facilities.php?room_id=<?= $r['id'] ?>" class="text-primary text-decoration-none small fw-bold">
                        <i class="bi bi-tools me-1"></i> Manage Facilities
                    </a>
                    <?php if($r['fac_count'] > 0): ?>
                        <span class="badge bg-primary bg-opacity-10 text-primary rounded-pill fw-bold" style="font-size: 0.6rem;"><?= $r['fac_count'] ?> assigned</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="modal fade" id="addRoomModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4 border-0 shadow">
            <div class="modal-header border-0 pb-0">
                <h5 class="fw-bold">Add New Room</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST">
                    <div class="mb-3"><label class="small fw-bold">Room Name</label><input type="text" name="name" class="form-control" required></div>
                    <div class="row mb-3">
                        <div class="col-6"><label class="small fw-bold">Capacity</label><input type="number" name="capacity" class="form-control" required></div>
                        <div class="col-6"><label class="small fw-bold">Type</label>
                            <select name="type" class="form-select">
                                <option>Classroom</option>
                                <option>Lab</option>
                                <option>Meeting Room</option>
                                <option>Hall</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-4"><label class="small fw-bold">Location (e.g. Block A, Level 1)</label><input type="text" name="location" class="form-control" placeholder="Block A, Level 1" required></div>
                    <button type="submit" name="add_room" class="btn btn-primary w-100 rounded-pill py-2 fw-bold">Save Room</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include '../../menu.php'; ?>  
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>