<?php
/**
 * Hostel Allocations Management
 * Manage student room allocations with CRUD operations
 */

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['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, status) 
                    VALUES (?, ?, ?, ?, ?, ?, 'active')
                ");
                $stmt->execute([
                    intval($_POST['student_id']),
                    intval($_POST['room_id']),
                    $_POST['allocation_date'],
                    $_POST['valid_until'] ?: null,
                    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 = '✅ ছাত্রকে হোস্টেলে সফলভাবে বরাদ্দ করা হয়েছে!';
            }
        }
        
        if (isset($_POST['deallocate_student'])) {
            $allocation_id = intval($_POST['allocation_id']);
            
            // Get room_id before updating
            $stmt = $pdo->prepare("SELECT room_id FROM hostel_allocations WHERE id = ?");
            $stmt->execute([$allocation_id]);
            $allocation = $stmt->fetch();
            
            if ($allocation) {
                // Update allocation status
                $stmt = $pdo->prepare("
                    UPDATE hostel_allocations 
                    SET status = 'inactive', deallocation_date = CURDATE()
                    WHERE id = ?
                ");
                $stmt->execute([$allocation_id]);
                
                // Update room occupancy
                $pdo->prepare("
                    UPDATE hostel_rooms 
                    SET current_occupancy = GREATEST(current_occupancy - 1, 0),
                        status = CASE WHEN current_occupancy - 1 < capacity THEN 'available' ELSE status END
                    WHERE id = ?
                ")->execute([$allocation['room_id']]);
                
                $success_message = '✅ বরাদ্দ সফলভাবে বাতিল করা হয়েছে!';
            }
        }
        
        if (isset($_POST['edit_allocation'])) {
            $stmt = $pdo->prepare("
                UPDATE hostel_allocations 
                SET room_id = ?, allocation_date = ?, valid_until = ?, 
                    monthly_rent = ?, security_deposit = ?
                WHERE id = ?
            ");
            $stmt->execute([
                intval($_POST['room_id']),
                $_POST['allocation_date'],
                $_POST['valid_until'] ?: null,
                floatval($_POST['monthly_rent']),
                floatval($_POST['security_deposit']),
                intval($_POST['allocation_id'])
            ]);
            $success_message = '✅ বরাদ্দ সফলভাবে আপডেট করা হয়েছে!';
        }
    } catch(Exception $e) {
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Get active allocations with student and room details
$active_allocations = $pdo->query("
    SELECT a.*, s.student_id as student_code, s.first_name, s.last_name, s.phone, s.class_id,
           r.room_number, r.floor_number, b.building_name, r.monthly_rent as room_rent
    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'
    ORDER BY b.building_name, r.room_number, s.first_name
")->fetchAll();

// Get inactive allocations (history)
$inactive_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='inactive'
    ORDER BY a.deallocation_date DESC
    LIMIT 50
")->fetchAll();

// Get available rooms
$available_rooms = $pdo->query("
    SELECT r.id, r.room_number, r.capacity, r.current_occupancy, 
           r.monthly_rent, b.building_name, r.floor_number
    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();

// Get active students without hostel allocation
$students_without_allocation = $pdo->query("
    SELECT s.id, s.student_id, s.first_name, s.last_name, c.name as class_name
    FROM students s
    LEFT JOIN hostel_allocations ha ON s.id = ha.student_id AND ha.status = 'active'
    LEFT JOIN classes c ON s.class_id = c.id
    WHERE s.status = 'active' AND ha.id IS NULL
    ORDER BY s.first_name
")->fetchAll();

// Statistics
$total_active = count($active_allocations);
$total_inactive = count($inactive_allocations);
?>
<!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-success btn-sm" data-bs-toggle="modal" data-bs-target="#allocateModal">
                            <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-6">
                        <div class="card bg-primary text-white">
                            <div class="card-body text-center">
                                <h6>সক্রিয় বরাদ্দ</h6>
                                <h3><?= $total_active ?></h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card bg-secondary text-white">
                            <div class="card-body text-center">
                                <h6>ইতিহাস (শেষ ৫০)</h6>
                                <h3><?= $total_inactive ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Active Allocations -->
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white">
                        <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 foreach ($active_allocations as $index => $allocation): ?>
                                    <tr>
                                        <td><?= $index + 1 ?></td>
                                        <td><?= htmlspecialchars($allocation['first_name'] . ' ' . $allocation['last_name']) ?></td>
                                        <td><?= htmlspecialchars($allocation['student_code']) ?></td>
                                        <td><?= htmlspecialchars($allocation['building_name']) ?></td>
                                        <td><?= htmlspecialchars($allocation['room_number']) ?></td>
                                        <td><?= $allocation['floor_number'] ?></td>
                                        <td><?= date('d M Y', strtotime($allocation['allocation_date'])) ?></td>
                                        <td><?= $allocation['valid_until'] ? date('d M Y', strtotime($allocation['valid_until'])) : '-' ?></td>
                                        <td>৳<?= number_format($allocation['monthly_rent'], 2) ?></td>
                                        <td>৳<?= number_format($allocation['security_deposit'], 2) ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#editAllocationModal<?= $allocation['id'] ?>">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('আপনি কি নিশ্চিতভাবে এই বরাদ্দটি বাতিল করতে চান?');">
                                                <?= csrf_field() ?>
                                                <input type="hidden" name="allocation_id" value="<?= $allocation['id'] ?>">
                                                <button type="submit" name="deallocate_student" class="btn btn-sm btn-warning" title="বরাদ্দ বাতিল করুন">
                                                    <i class="fas fa-door-open"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- Allocation History -->
                <div class="card">
                    <div class="card-header bg-secondary text-white">
                        <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>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($inactive_allocations as $index => $allocation): ?>
                                    <tr>
                                        <td><?= $index + 1 ?></td>
                                        <td><?= htmlspecialchars($allocation['first_name'] . ' ' . $allocation['last_name']) ?></td>
                                        <td><?= htmlspecialchars($allocation['student_code']) ?></td>
                                        <td><?= htmlspecialchars($allocation['building_name']) ?></td>
                                        <td><?= htmlspecialchars($allocation['room_number']) ?></td>
                                        <td><?= date('d M Y', strtotime($allocation['allocation_date'])) ?></td>
                                        <td><?= $allocation['deallocation_date'] ? date('d M Y', strtotime($allocation['deallocation_date'])) : '-' ?></td>
                                        <td>৳<?= number_format($allocation['monthly_rent'], 2) ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Allocate Student Modal -->
    <div class="modal fade" id="allocateModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <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="row">
                            <div class="col-md-6">
                                <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 foreach ($students_without_allocation as $s): ?>
                                        <option value="<?= $s['id'] ?>">
                                            <?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name'] . ' (' . $s['student_id'] . ')') ?>
                                            <?= $s['class_name'] ? ' - ' . $s['class_name'] : '' ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">রুম নির্বাচন <span class="text-danger">*</span></label>
                                    <select name="room_id" class="form-select" id="roomSelect" required>
                                        <option value="">-- রুম নির্বাচন --</option>
                                        <?php foreach ($available_rooms 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>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <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>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">মেয়াদ শেষ</label>
                                    <input type="date" name="valid_until" class="form-control">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">মাসিক ভাড়া (৳) <span class="text-danger">*</span></label>
                                    <input type="number" name="monthly_rent" class="form-control" id="monthlyRent" value="2000" min="0" step="0.01" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <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>
                    </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>
    
    <!-- Edit Allocation Modals -->
    <?php foreach ($active_allocations as $allocation): ?>
    <div class="modal fade" id="editAllocationModal<?= $allocation['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="allocation_id" value="<?= $allocation['id'] ?>">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">ছাত্র</label>
                            <input type="text" class="form-control" value="<?= htmlspecialchars($allocation['first_name'] . ' ' . $allocation['last_name']) ?>" disabled>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">রুম নির্বাচন <span class="text-danger">*</span></label>
                            <select name="room_id" class="form-select" required>
                                <?php 
                                $all_rooms = $pdo->query("
                                    SELECT r.id, r.room_number, r.capacity, r.current_occupancy, 
                                           b.building_name, r.status
                                    FROM hostel_rooms r 
                                    JOIN hostel_buildings b ON r.building_id = b.id 
                                    WHERE r.status IN ('available', 'occupied')
                                    ORDER BY b.building_name, r.room_number
                                ")->fetchAll();
                                foreach ($all_rooms as $r): 
                                ?>
                                <option value="<?= $r['id'] ?>" <?= $allocation['room_id'] == $r['id'] ? 'selected' : '' ?>>
                                    <?= 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="<?= $allocation['allocation_date'] ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">মেয়াদ শেষ</label>
                            <input type="date" name="valid_until" class="form-control" value="<?= $allocation['valid_until'] ?>">
                        </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="<?= $allocation['monthly_rent'] ?>" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">সিকিউরিটি ডিপোজিট (৳)</label>
                            <input type="number" name="security_deposit" class="form-control" value="<?= $allocation['security_deposit'] ?>" 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="edit_allocation" 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('roomSelect').addEventListener('change', function() {
            const selected = this.options[this.selectedIndex];
            if (selected.dataset.rent) {
                document.getElementById('monthlyRent').value = selected.dataset.rent;
            }
        });
    </script>
</body>
</html>
