<?php
/**
 * Hostel Rooms Management
 * Manage hostel rooms by building with add/edit functionality
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/SecurityHelper.php';

// Check authentication - redirect to login if not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit;
}

// Check admin role - support both new and legacy session variables
$user_role = $_SESSION['user_role'] ?? $_SESSION['role'] ?? '';
if (!isset($_SESSION['user_id']) || ($user_role !== 'admin')) {
    http_response_code(403);
    die('❌ অ্যাক্সেস denied। আপনার এই পেজ দেখার অনুমতি নেই।<br><br>
    <a href="../../login.php" class="btn btn-primary">লগইন পেজে যান</a>');
}

$success_message = '';
$error_message = '';

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    SecurityHelper::validatePost();
    
    try {
        if (isset($_POST['add_room'])) {
            $stmt = $pdo->prepare("
                INSERT INTO hostel_rooms (building_id, room_number, floor_number, room_type, 
                    capacity, amenities, monthly_rent, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, 'available')
            ");
            
            $room_type = $_POST['room_type'];
            $capacity = match($room_type) {
                'single' => 1,
                'double' => 2,
                'triple' => 3,
                'dormitory' => intval($_POST['capacity']),
                default => 2
            };
            
            $stmt->execute([
                intval($_POST['building_id']),
                sanitize($_POST['room_number']),
                intval($_POST['floor_number']),
                $room_type,
                $capacity,
                sanitize($_POST['amenities']),
                floatval($_POST['monthly_rent'])
            ]);
            $success_message = '✅ রুম সফলভাবে যোগ করা হয়েছে!';
        }
        
        if (isset($_POST['edit_room'])) {
            $stmt = $pdo->prepare("
                UPDATE hostel_rooms 
                SET building_id = ?, room_number = ?, floor_number = ?, room_type = ?, 
                    capacity = ?, amenities = ?, monthly_rent = ?, status = ?
                WHERE id = ?
            ");
            
            $room_type = $_POST['room_type'];
            $capacity = match($room_type) {
                'single' => 1,
                'double' => 2,
                'triple' => 3,
                'dormitory' => intval($_POST['capacity']),
                default => 2
            };
            
            $stmt->execute([
                intval($_POST['building_id']),
                sanitize($_POST['room_number']),
                intval($_POST['floor_number']),
                $room_type,
                $capacity,
                sanitize($_POST['amenities']),
                floatval($_POST['monthly_rent']),
                sanitize($_POST['status']),
                intval($_POST['room_id'])
            ]);
            $success_message = '✅ রুম সফলভাবে আপডেট করা হয়েছে!';
        }
        
        if (isset($_POST['delete_room'])) {
            // Check if room has active allocations
            $check = $pdo->prepare("SELECT COUNT(*) FROM hostel_allocations WHERE room_id = ? AND status = 'active'");
            $check->execute([intval($_POST['room_id'])]);
            if ($check->fetchColumn() > 0) {
                $error_message = '❌ এই রুমে সক্রিয় বরাদ্দ রয়েছে। প্রথমে বরাদ্দ বাতিল করুন।';
            } else {
                $stmt = $pdo->prepare("DELETE FROM hostel_rooms WHERE id = ?");
                $stmt->execute([intval($_POST['room_id'])]);
                $success_message = '✅ রুম সফলভাবে মুছে ফেলা হয়েছে!';
            }
        }
    } catch(Exception $e) {
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Get all buildings
$buildings = $pdo->query("SELECT * FROM hostel_buildings WHERE status='active' ORDER BY building_name")->fetchAll();

// Get rooms with building info
$rooms = $pdo->query("
    SELECT r.*, b.building_name 
    FROM hostel_rooms r 
    JOIN hostel_buildings b ON r.building_id = b.id 
    ORDER BY b.building_name, r.floor_number, r.room_number
")->fetchAll();

// Get selected building for filtering
$selected_building = isset($_GET['building_id']) ? intval($_GET['building_id']) : 0;

// Room statistics
$total_rooms = count($rooms);
$available_rooms = count(array_filter($rooms, fn($r) => $r['status'] == 'available'));
$occupied_rooms = count(array_filter($rooms, fn($r) => $r['status'] == 'occupied'));
$maintenance_rooms = count(array_filter($rooms, fn($r) => $r['status'] == 'maintenance'));
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>হোস্টেল রুম ব্যবস্থাপনা - <?= APP_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="../../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">🚪 হোস্টেল রুম ব্যবস্থাপনা</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="../../index.php" class="btn btn-outline-primary btn-sm me-2">
                            <i class="fas fa-home"></i> হোম পেজ
                        </a>
                        <a href="index.php" class="btn btn-outline-secondary btn-sm me-2">
                            <i class="fas fa-arrow-left"></i> হোস্টেল হোম
                        </a>
                        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addRoomModal">
                            <i class="fas fa-plus"></i> নতুন রুম
                        </button>
                    </div>
                </div>
                
                <?php if ($success_message): ?>
                    <div class="alert alert-success"><?= $success_message ?></div>
                <?php endif; ?>
                <?php if ($error_message): ?>
                    <div class="alert alert-danger"><?= $error_message ?></div>
                <?php endif; ?>
                
                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body text-center">
                                <h6>মোট রুম</h6>
                                <h3><?= $total_rooms ?></h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body text-center">
                                <h6>ফাঁকা রুম</h6>
                                <h3><?= $available_rooms ?></h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-dark">
                            <div class="card-body text-center">
                                <h6>ভর্তি রুম</h6>
                                <h3><?= $occupied_rooms ?></h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-secondary text-white">
                            <div class="card-body text-center">
                                <h6>মেইনটেনেন্স</h6>
                                <h3><?= $maintenance_rooms ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Building Filter -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">ভবন অনুযায়ী ফিল্টার</label>
                                <select name="building_id" class="form-select" onchange="this.form.submit()">
                                    <option value="0">সকল ভবন</option>
                                    <?php foreach ($buildings as $building): ?>
                                    <option value="<?= $building['id'] ?>" <?= $selected_building == $building['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($building['building_name']) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Rooms Table -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">🏢 রুম তালিকা</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>ভবন</th>
                                        <th>রুম নং</th>
                                        <th>তলা</th>
                                        <th>ধরন</th>
                                        <th>আসন</th>
                                        <th>বর্তমান</th>
                                        <th>ভাড়া (৳)</th>
                                        <th>অবস্থা</th>
                                        <th>সুবিধা</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $row_num = 1;
                                    foreach ($rooms as $room): 
                                        if ($selected_building && $room['building_id'] != $selected_building) continue;
                                    ?>
                                    <tr>
                                        <td><?= $row_num++ ?></td>
                                        <td><?= htmlspecialchars($room['building_name']) ?></td>
                                        <td><?= htmlspecialchars($room['room_number']) ?></td>
                                        <td><?= $room['floor_number'] ?></td>
                                        <td>
                                            <?php
                                            $type_labels = [
                                                'single' => 'সিঙ্গেল',
                                                'double' => 'ডাবল',
                                                'triple' => 'ট্রিপল',
                                                'dormitory' => 'ডরমিটরি'
                                            ];
                                            echo $type_labels[$room['room_type']] ?? $room['room_type'];
                                            ?>
                                        </td>
                                        <td><?= $room['capacity'] ?></td>
                                        <td><?= $room['current_occupancy'] ?></td>
                                        <td><?= number_format($room['monthly_rent'], 2) ?></td>
                                        <td>
                                            <span class="badge bg-<?= 
                                                $room['status'] == 'available' ? 'success' : 
                                                ($room['status'] == 'occupied' ? 'warning' : 'secondary') 
                                            ?>">
                                                <?= 
                                                    $room['status'] == 'available' ? 'ফাঁকা' : 
                                                    ($room['status'] == 'occupied' ? 'ভর্তি' : 'মেইনটেনেন্স') 
                                                ?>
                                            </span>
                                        </td>
                                        <td><?= htmlspecialchars($room['amenities']) ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#editRoomModal<?= $room['id'] ?>">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('আপনি কি নিশ্চিতভাবে এই রুমটি মুছে ফেলতে চান?');">
                                                <?= csrf_field() ?>
                                                <input type="hidden" name="room_id" value="<?= $room['id'] ?>">
                                                <button type="submit" name="delete_room" class="btn btn-sm btn-danger">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Add Room Modal -->
    <div class="modal fade" id="addRoomModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">নতুন রুম যোগ করুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <?= csrf_field() ?>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">ভবন <span class="text-danger">*</span></label>
                            <select name="building_id" class="form-select" required>
                                <option value="">-- ভবন নির্বাচন --</option>
                                <?php foreach ($buildings as $b): ?>
                                <option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['building_name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">রুম নম্বর <span class="text-danger">*</span></label>
                            <input type="text" name="room_number" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">তলা নম্বর</label>
                            <input type="number" name="floor_number" class="form-control" value="1" min="1">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">রুমের ধরন <span class="text-danger">*</span></label>
                            <select name="room_type" class="form-select" id="roomType" required>
                                <option value="single">সিঙ্গেল (১ জন)</option>
                                <option value="double" selected>ডাবল (২ জন)</option>
                                <option value="triple">ট্রিপল (৩ জন)</option>
                                <option value="dormitory">ডরমিটরি (৪+)</option>
                            </select>
                        </div>
                        <div class="mb-3" id="capacityDiv" style="display:none;">
                            <label class="form-label">আসন সংখ্যা (ডরমিটরির জন্য)</label>
                            <input type="number" name="capacity" class="form-control" value="4" min="4">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">সুবিধাসমূহ</label>
                            <textarea name="amenities" class="form-control" rows="2" placeholder="যেমন: এসি, ওয়াশরুম, টেবিল..."></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">মাসিক ভাড়া (৳) <span class="text-danger">*</span></label>
                            <input type="number" name="monthly_rent" class="form-control" value="2000" min="0" step="0.01" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                        <button type="submit" name="add_room" class="btn btn-primary">সংরক্ষণ</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Edit Room Modals -->
    <?php foreach ($rooms as $room): ?>
    <div class="modal fade" id="editRoomModal<?= $room['id'] ?>" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">রুম সম্পাদনা</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <?= csrf_field() ?>
                    <input type="hidden" name="room_id" value="<?= $room['id'] ?>">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">ভবন <span class="text-danger">*</span></label>
                            <select name="building_id" class="form-select" required>
                                <?php foreach ($buildings as $b): ?>
                                <option value="<?= $b['id'] ?>" <?= $room['building_id'] == $b['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($b['building_name']) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">রুম নম্বর <span class="text-danger">*</span></label>
                            <input type="text" name="room_number" class="form-control" value="<?= htmlspecialchars($room['room_number']) ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">তলা নম্বর</label>
                            <input type="number" name="floor_number" class="form-control" value="<?= $room['floor_number'] ?>" min="1">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">রুমের ধরন <span class="text-danger">*</span></label>
                            <select name="room_type" class="form-select" required>
                                <option value="single" <?= $room['room_type'] == 'single' ? 'selected' : '' ?>>সিঙ্গেল (১ জন)</option>
                                <option value="double" <?= $room['room_type'] == 'double' ? 'selected' : '' ?>>ডাবল (২ জন)</option>
                                <option value="triple" <?= $room['room_type'] == 'triple' ? 'selected' : '' ?>>ট্রিপল (৩ জন)</option>
                                <option value="dormitory" <?= $room['room_type'] == 'dormitory' ? 'selected' : '' ?>>ডরমিটরি (৪+)</option>
                            </select>
                        </div>
                        <div class="mb-3" <?= $room['room_type'] != 'dormitory' ? 'style="display:none;"' : '' ?>>
                            <label class="form-label">আসন সংখ্যা</label>
                            <input type="number" name="capacity" class="form-control" value="<?= $room['capacity'] ?>" min="1">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">সুবিধাসমূহ</label>
                            <textarea name="amenities" class="form-control" rows="2"><?= htmlspecialchars($room['amenities']) ?></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">মাসিক ভাড়া (৳) <span class="text-danger">*</span></label>
                            <input type="number" name="monthly_rent" class="form-control" value="<?= $room['monthly_rent'] ?>" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">অবস্থা <span class="text-danger">*</span></label>
                            <select name="status" class="form-select" required>
                                <option value="available" <?= $room['status'] == 'available' ? 'selected' : '' ?>>ফাঁকা</option>
                                <option value="occupied" <?= $room['status'] == 'occupied' ? 'selected' : '' ?>>ভর্তি</option>
                                <option value="maintenance" <?= $room['status'] == 'maintenance' ? 'selected' : '' ?>>মেইনটেনেন্স</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                        <button type="submit" name="edit_room" class="btn btn-primary">আপডেট</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('roomType').addEventListener('change', function() {
            document.getElementById('capacityDiv').style.display = this.value === 'dormitory' ? 'block' : 'none';
        });
    </script>
</body>
</html>
