<?php
/**
 * Hostel Management Module
 */

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 = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    SecurityHelper::validatePost();
    
    try {
        if (isset($_POST['add_building'])) {
            $stmt = $pdo->prepare("
                INSERT INTO hostel_buildings (building_name, building_code, address, total_floors, 
                    warden_name, warden_phone, warden_email) 
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                sanitize($_POST['building_name']),
                sanitize($_POST['building_code']),
                sanitize($_POST['address']),
                intval($_POST['total_floors']),
                sanitize($_POST['warden_name']),
                sanitize($_POST['warden_phone']),
                sanitize($_POST['warden_email'])
            ]);
            $success_message = '✅ হোস্টেল ভবন সফলভাবে যোগ করা হয়েছে!';
        }
        
        if (isset($_POST['add_room'])) {
            $stmt = $pdo->prepare("
                INSERT INTO hostel_rooms (building_id, room_number, floor_number, room_type, 
                    capacity, amenities, monthly_rent) 
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            
            $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['allocate_student'])) {
            // Check if student already has active allocation
            $check = $pdo->prepare("SELECT id FROM hostel_allocations WHERE student_id=? AND status='active'");
            $check->execute([intval($_POST['student_id'])]);
            if ($check->fetch()) {
                $error_message = '❌ এই ছাত্রের ইতিমধ্যে একটি অ্যাক্টিভ হোস্টেল বরাদ্দ আছে!';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO hostel_allocations (student_id, room_id, allocation_date, valid_until, 
                        monthly_rent, security_deposit) 
                    VALUES (?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    intval($_POST['student_id']),
                    intval($_POST['room_id']),
                    $_POST['allocation_date'],
                    $_POST['valid_until'],
                    floatval($_POST['monthly_rent']),
                    floatval($_POST['security_deposit'])
                ]);
                
                // Update room occupancy
                $pdo->prepare("
                    UPDATE hostel_rooms SET current_occupancy = current_occupancy + 1,
                    status = CASE WHEN current_occupancy + 1 >= capacity THEN 'occupied' ELSE 'available' END
                    WHERE id=?
                ")->execute([intval($_POST['room_id'])]);
                
                $success_message = '✅ ছাত্রকে হোস্টেলে বরাদ্দ করা হয়েছে!';
            }
        }
    } catch(Exception $e) {
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Get statistics
$buildings = $pdo->query("SELECT * FROM hostel_buildings WHERE status='active'")->fetchAll();
$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.room_number")->fetchAll();
$active_allocations = $pdo->query("
    SELECT a.*, s.student_id as student_code, s.first_name, s.last_name, r.room_number, b.building_name 
    FROM hostel_allocations a 
    JOIN students s ON a.student_id = s.id 
    JOIN hostel_rooms r ON a.room_id = r.id 
    JOIN hostel_buildings b ON r.building_id = b.id 
    WHERE a.status='active'
")->fetchAll();

$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'));
$total_capacity = array_sum(array_column($rooms, 'capacity'));
$current_occupancy = array_sum(array_column($rooms, 'current_occupancy'));
?>
<!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>
                    <a href="../../index.php" class="btn btn-outline-primary">
                        <i class="fas fa-home"></i> হোম পেজ
                    </a>
                </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-2">
                        <div class="card bg-primary text-white">
                            <div class="card-body text-center">
                                <h6>মোট ভবন</h6>
                                <h3><?= count($buildings) ?></h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <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-2">
                        <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-2">
                        <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-2">
                        <div class="card bg-secondary text-white">
                            <div class="card-body text-center">
                                <h6>মোট আসন</h6>
                                <h3><?= $total_capacity ?></h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card bg-dark text-white">
                            <div class="card-body text-center">
                                <h6>বর্তমান ছাত্র</h6>
                                <h3><?= $current_occupancy ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <!-- Buildings Section -->
                    <div class="col-md-4">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">🏢 হোস্টেল ভবন</h5>
                                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addBuildingModal">+</button>
                            </div>
                            <div class="card-body">
                                <?php foreach ($buildings as $building): ?>
                                <div class="card mb-2">
                                    <div class="card-body p-3">
                                        <h6 class="mb-1"><?= htmlspecialchars($building['building_name']) ?></h6>
                                        <small class="text-muted">ওয়ার্ডেন: <?= htmlspecialchars($building['warden_name']) ?></small><br>
                                        <small class="text-muted">ফোন: <?= htmlspecialchars($building['warden_phone']) ?></small>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Rooms Section -->
                    <div class="col-md-4">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">🚪 রুমসমূহ</h5>
                                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addRoomModal">+</button>
                            </div>
                            <div class="card-body">
                                <div class="list-group" style="max-height: 400px; overflow-y: auto;">
                                    <?php foreach ($rooms as $room): ?>
                                    <div class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                        <div>
                                            <strong><?= htmlspecialchars($room['building_name']) ?> - রুম <?= htmlspecialchars($room['room_number']) ?></strong>
                                            <br><small class="text-muted">
                                                <?= $room['room_type'] == 'single' ? 'সিঙ্গেল' : ($room['room_type'] == 'double' ? 'ডাবল' : ($room['room_type'] == 'triple' ? 'ট্রিপল' : 'ডরমিটরি')) ?>
                                                | <?= $room['current_occupancy'] ?>/<?= $room['capacity'] ?> ছাত্র
                                            </small>
                                        </div>
                                        <span class="badge bg-<?= $room['status'] == 'available' ? 'success' : ($room['status'] == 'occupied' ? 'warning' : 'secondary') ?>">
                                            <?= $room['status'] == 'available' ? 'ফাঁকা' : ($room['status'] == 'occupied' ? 'ভর্তি' : 'মেইনটেনেন্স') ?>
                                        </span>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Allocations Section -->
                    <div class="col-md-4">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">👥 বরাদ্দ তালিকা</h5>
                                <button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#allocateModal">+ বরাদ্দ</button>
                            </div>
                            <div class="card-body">
                                <div class="list-group" style="max-height: 400px; overflow-y: auto;">
                                    <?php foreach ($active_allocations as $allocation): ?>
                                    <div class="list-group-item">
                                        <h6 class="mb-1"><?= htmlspecialchars($allocation['first_name'] . ' ' . $allocation['last_name']) ?></h6>
                                        <p class="mb-1">
                                            <small>
                                                ID: <?= $allocation['student_code'] ?><br>
                                                <?= htmlspecialchars($allocation['building_name']) ?> - রুম <?= htmlspecialchars($allocation['room_number']) ?><br>
                                                ভাড়া: ৳<?= $allocation['monthly_rent'] ?>/মাস
                                            </small>
                                        </p>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Hostel Fees Link -->
                <div class="mt-3">
                    <a href="hostel_fees.php" class="btn btn-outline-primary">
                        <i class="fas fa-money-bill"></i> হোস্টেল ফি ব্যবস্থাপনা
                    </a>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Add Building Modal -->
    <div class="modal fade" id="addBuildingModal" 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>
                            <input type="text" name="building_name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ভবন কোড <span class="text-danger">*</span></label>
                            <input type="text" name="building_code" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ঠিকানা</label>
                            <textarea name="address" class="form-control" rows="2"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">মোট তলা</label>
                            <input type="number" name="total_floors" class="form-control" value="1" min="1">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ওয়ার্ডেনের নাম</label>
                            <input type="text" name="warden_name" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ওয়ার্ডেনের ফোন</label>
                            <input type="text" name="warden_phone" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ওয়ার্ডেনের ইমেইল</label>
                            <input type="email" name="warden_email" class="form-control">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                        <button type="submit" name="add_building" class="btn btn-primary">সংরক্ষণ</button>
                    </div>
                </form>
            </div>
        </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">মাসিক ভাড়া (৳)</label>
                            <input type="number" name="monthly_rent" class="form-control" value="2000" min="0" step="0.01">
                        </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>
    
    <!-- Allocate Student Modal -->
    <div class="modal fade" id="allocateModal" 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="student_id" class="form-select" required>
                                <option value="">-- ছাত্র নির্বাচন --</option>
                                <?php
                                $students = $pdo->query("SELECT id, student_id, first_name, last_name FROM students WHERE status='active' ORDER BY first_name")->fetchAll();
                                foreach ($students as $s):
                                ?>
                                <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name'] . ' (' . $s['student_id'] . ')') ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">রুম নির্বাচন <span class="text-danger">*</span></label>
                            <select name="room_id" class="form-select" required>
                                <option value="">-- রুম নির্বাচন --</option>
                                <?php
                                $available_rooms_list = $pdo->query("
                                    SELECT r.id, r.room_number, r.capacity, r.current_occupancy, 
                                           r.monthly_rent, b.building_name 
                                    FROM hostel_rooms r 
                                    JOIN hostel_buildings b ON r.building_id = b.id 
                                    WHERE r.status='available' AND r.current_occupancy < r.capacity
                                    ORDER BY b.building_name, r.room_number
                                ")->fetchAll();
                                foreach ($available_rooms_list as $r):
                                ?>
                                <option value="<?= $r['id'] ?>" data-rent="<?= $r['monthly_rent'] ?>">
                                    <?= htmlspecialchars($r['building_name'] . ' - রুম ' . $r['room_number'] . ' (' . $r['current_occupancy'] . '/' . $r['capacity'] . ')') ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">বরাদ্দ তারিখ <span class="text-danger">*</span></label>
                            <input type="date" name="allocation_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">মেয়াদ শেষ</label>
                            <input type="date" name="valid_until" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">মাসিক ভাড়া (৳)</label>
                            <input type="number" name="monthly_rent" class="form-control" id="monthlyRent" value="2000" min="0" step="0.01">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">সিকিউরিটি ডিপোজিট (৳)</label>
                            <input type="number" name="security_deposit" class="form-control" value="3000" min="0" step="0.01">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                        <button type="submit" name="allocate_student" class="btn btn-success">বরাদ্দ করুন</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <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';
        });
        
        document.querySelector('select[name="room_id"]').addEventListener('change', function() {
            const selected = this.options[this.selectedIndex];
            if (selected.dataset.rent) {
                document.getElementById('monthlyRent').value = selected.dataset.rent;
            }
        });
    </script>
</body>
</html>
