<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';

// Access control: admin or teacher only
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

// Get site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'প্রতিষ্ঠানের নাম';
$site_address = $settings['site_address'] ?? 'ঠিকানা, ফোন: ০১৭xxxxxxxx';
$logo_image = $settings['logo_image'] ?? '';
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;
$logo_opacity = isset($settings['logo_opacity']) ? floatval($settings['logo_opacity']) : 0.9;

$exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : 0;
$dateFilter = isset($_GET['date']) ? $_GET['date'] : '';

// Fetch exams for dropdown
$exams = $pdo->query("SELECT id, name, exam_date FROM exams ORDER BY exam_date DESC, id DESC")->fetchAll();

// Selected exam
$current_exam = null;
if ($exam_id) {
    $stmt = $pdo->prepare("SELECT e.id, e.name, e.exam_date, e.start_time, e.end_time, e.class_id, c.name AS class_name, c.section
                         FROM exams e
                         LEFT JOIN classes c ON e.class_id = c.id
                         WHERE e.id = ?");
    $stmt->execute([$exam_id]);
    $current_exam = $stmt->fetch();
}

// Date-wise subjects from routine
$date_subjects = [];
if ($exam_id) {
    $sub_stmt = $pdo->prepare("SELECT es.exam_date, s.name AS subject_bn, COALESCE(NULLIF(s.description,''), s.code) AS subject_en
                               FROM exam_subjects es
                               JOIN subjects s ON es.subject_id = s.id
                               WHERE es.exam_id = ?
                               ORDER BY es.exam_date, s.name");
    $sub_stmt->execute([$exam_id]);
    $date_subjects_rows = $sub_stmt->fetchAll();
    
    // Group by date with pairs
    foreach ($date_subjects_rows as $r) {
        $date_subjects[$r['exam_date']][] = [$r['subject_bn'], $r['subject_en']];
    }
}

// Get allowed dates for exam
$allowed_dates = [];
if ($exam_id) {
    $stmt = $pdo->prepare("SELECT DISTINCT exam_date FROM exam_subjects WHERE exam_id = ? AND exam_date IS NOT NULL ORDER BY exam_date");
    $stmt->execute([$exam_id]);
    $allowed_dates = array_map(function($r){ return $r['exam_date']; }, $stmt->fetchAll());
}

// Handle form submission for saving room allocations
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save_allocations') {
        // Process and save the room allocations
        $allocations = isset($_POST['allocations']) ? $_POST['allocations'] : [];
        
        // Get customization settings
        $font_size = isset($_POST['font_size']) ? (int)$_POST['font_size'] : 14;
        $text_color = isset($_POST['text_color']) ? $_POST['text_color'] : '#000000';
        $font_weight = isset($_POST['font_weight']) ? $_POST['font_weight'] : 'normal';
        
        // Get header customization settings
        $header_font_size = isset($_POST['header_font_size']) ? (int)$_POST['header_font_size'] : 24;
        $header_text_color = isset($_POST['header_text_color']) ? $_POST['header_text_color'] : '#000000';
        $header_font_weight = isset($_POST['header_font_weight']) ? $_POST['header_font_weight'] : 'bold';
        
        // Get selected text customization settings
        $selected_text_font_size = isset($_POST['selected_text_font_size']) ? (int)$_POST['selected_text_font_size'] : $font_size;
        $selected_text_color = isset($_POST['selected_text_color']) ? $_POST['selected_text_color'] : $text_color;
        $selected_text_font_weight = isset($_POST['selected_text_font_weight']) ? $_POST['selected_text_font_weight'] : $font_weight;
        
        // Get retention settings
        $retention_type = isset($_POST['retention_type']) ? $_POST['retention_type'] : 'count';
        $retention_limit = isset($_POST['retention_limit']) ? (int)$_POST['retention_limit'] : 5;
        $retention_duration_days = isset($_POST['retention_duration_days']) ? (int)$_POST['retention_duration_days'] : 30;
        
        // Get selected dates for applying this seat plan template
        $selected_dates = isset($_POST['apply_to_dates']) ? $_POST['apply_to_dates'] : [];
        
        // Save retention setting for this exam
        if ($exam_id) {
            // Check if setting already exists
            $checkStmt = $pdo->prepare("SELECT id FROM retention_settings WHERE exam_id = ?");
            $checkStmt->execute([$exam_id]);
            
            if ($checkStmt->fetch()) {
                // Update existing setting
                $updateStmt = $pdo->prepare("UPDATE retention_settings SET retention_type = ?, retention_limit = ?, retention_duration_days = ?, updated_at = CURRENT_TIMESTAMP WHERE exam_id = ?");
                $updateStmt->execute([$retention_type, $retention_limit, $retention_duration_days, $exam_id]);
            } else {
                // Insert new setting
                $insertStmt = $pdo->prepare("INSERT INTO retention_settings (exam_id, retention_type, retention_limit, retention_duration_days) VALUES (?, ?, ?, ?)");
                $insertStmt->execute([$exam_id, $retention_type, $retention_limit, $retention_duration_days]);
            }
            
            // If specific dates are selected, apply this template to those dates
            if (!empty($selected_dates) && $dateFilter) {
                foreach ($selected_dates as $targetDate) {
                    // Skip if target date is the same as current date (already handled)
                    if ($targetDate === $dateFilter) continue;
                    
                    // Delete existing allocations for this exam and target date
                    $deleteStmt = $pdo->prepare("DELETE FROM manual_room_allocations WHERE exam_id = ? AND exam_date = ?");
                    $deleteStmt->execute([$exam_id, $targetDate]);
                    
                    // Copy allocations from current date to target date
                    $copyStmt = $pdo->prepare("INSERT INTO manual_room_allocations (exam_id, exam_date, room_number, from_roll, to_roll, department, total_count, font_size, text_color, font_weight, header_font_size, header_text_color, header_font_weight, selected_text_font_size, selected_text_color, selected_text_font_weight) 
                                              SELECT exam_id, ?, room_number, from_roll, to_roll, department, total_count, ?, ?, ?, ?, ?, ?, ?, ?, ? 
                                              FROM manual_room_allocations 
                                              WHERE exam_id = ? AND exam_date = ?");
                    $copyStmt->execute([
                        $targetDate,
                        $font_size, $text_color, $font_weight,
                        $header_font_size, $header_text_color, $header_font_weight,
                        $selected_text_font_size, $selected_text_color, $selected_text_font_weight,
                        $exam_id, $dateFilter
                    ]);
                }
            }
        }
        
        // Delete existing allocations for this exam and date
        $deleteStmt = $pdo->prepare("DELETE FROM manual_room_allocations WHERE exam_id = ? AND exam_date = ?");
        $deleteStmt->execute([$exam_id, $dateFilter]);
        
        // Insert new allocations with customization settings
        $insertStmt = $pdo->prepare("INSERT INTO manual_room_allocations (exam_id, exam_date, room_number, from_roll, to_roll, department, total_count, font_size, text_color, font_weight, header_font_size, header_text_color, header_font_weight, selected_text_font_size, selected_text_color, selected_text_font_weight) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        foreach ($allocations as $allocation) {
            if (!empty($allocation['room']) || !empty($allocation['from_roll']) || !empty($allocation['to_roll']) || !empty($allocation['department']) || !empty($allocation['total'])) {
                $insertStmt->execute([
                    $exam_id,
                    $dateFilter,
                    $allocation['room'] ?? '',
                    $allocation['from_roll'] ?? '',
                    $allocation['to_roll'] ?? '',
                    $allocation['department'] ?? '',
                    $allocation['total'] ?? '',
                    $font_size,
                    $text_color,
                    $font_weight,
                    $header_font_size,
                    $header_text_color,
                    $header_font_weight,
                    $selected_text_font_size,
                    $selected_text_color,
                    $selected_text_font_weight
                ]);
            }
        }
        
        // Handle retention based on type
        if ($retention_type === 'count' && $retention_limit > 0) {
            // Get all distinct exam_date entries for this exam, ordered by date descending
            $stmt = $pdo->prepare("SELECT DISTINCT exam_date FROM manual_room_allocations WHERE exam_id = ? ORDER BY exam_date DESC");
            $stmt->execute([$exam_id]);
            $dates = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            // If we have more dates than the retention limit, delete the oldest ones
            if (count($dates) > $retention_limit) {
                // Get the dates to delete (everything after the retention limit)
                $datesToDelete = array_slice($dates, $retention_limit);
                
                // Delete records for those dates
                foreach ($datesToDelete as $dateToDelete) {
                    $deleteStmt = $pdo->prepare("DELETE FROM manual_room_allocations WHERE exam_id = ? AND exam_date = ?");
                    $deleteStmt->execute([$exam_id, $dateToDelete]);
                }
            }
        } else if ($retention_type === 'duration' && $retention_duration_days > 0) {
            // Delete records older than the specified duration
            $cutoffDate = date('Y-m-d', strtotime("-{$retention_duration_days} days"));
            $deleteStmt = $pdo->prepare("DELETE FROM manual_room_allocations WHERE exam_id = ? AND exam_date < ?");
            $deleteStmt->execute([$exam_id, $cutoffDate]);
        }
        
        // Redirect to print view with customization parameters
        $redirect_url = "print_manual_room_allocation.php?exam_id=" . $exam_id . "&date=" . urlencode($dateFilter) . "&font_size=" . $font_size . "&text_color=" . urlencode($text_color) . "&font_weight=" . urlencode($font_weight) . "&header_font_size=" . $header_font_size . "&header_text_color=" . urlencode($header_text_color) . "&header_font_weight=" . urlencode($header_font_weight) . "&selected_text_font_size=" . $selected_text_font_size . "&selected_text_color=" . urlencode($selected_text_color) . "&selected_text_font_weight=" . urlencode($selected_text_font_weight);
        header("Location: $redirect_url");
        exit();
    }
}

// Get saved allocations from database
$saved_allocations = [];
if ($exam_id && $dateFilter) {
    $stmt = $pdo->prepare("SELECT room_number as room, from_roll, to_roll, department, total_count as total FROM manual_room_allocations WHERE exam_id = ? AND exam_date = ? ORDER BY id");
    $stmt->execute([$exam_id, $dateFilter]);
    $saved_allocations = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get customization settings from database for existing allocations
$customization_settings = [];
if ($exam_id && $dateFilter) {
    $stmt = $pdo->prepare("SELECT font_size, text_color, font_weight, header_font_size, header_text_color, header_font_weight, selected_text_font_size, selected_text_color, selected_text_font_weight FROM manual_room_allocations WHERE exam_id = ? AND exam_date = ? ORDER BY id LIMIT 1");
    $stmt->execute([$exam_id, $dateFilter]);
    $customization_settings = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Set default values if no customization found
    if (!$customization_settings) {
        $customization_settings = [
            'font_size' => 14,
            'text_color' => '#000000',
            'font_weight' => 'normal',
            'header_font_size' => 24,
            'header_text_color' => '#000000',
            'header_font_weight' => 'bold',
            'selected_text_font_size' => 14,
            'selected_text_color' => '#000000',
            'selected_text_font_weight' => 'normal'
        ];
    }
}

// Get current retention settings for this exam
$retention_type = 'count';
$retention_limit = 5;
$retention_duration_days = 30;

if ($exam_id) {
    $stmt = $pdo->prepare("SELECT retention_type, retention_limit, retention_duration_days FROM retention_settings WHERE exam_id = ?");
    $stmt->execute([$exam_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($result) {
        $retention_type = $result['retention_type'];
        $retention_limit = (int)$result['retention_limit'];
        $retention_duration_days = (int)$result['retention_duration_days'];
    }
}

// Get available dates for this exam
$available_dates = [];
if ($exam_id) {
    $stmt = $pdo->prepare("SELECT DISTINCT exam_date FROM exam_subjects WHERE exam_id = ? AND exam_date IS NOT NULL ORDER BY exam_date");
    $stmt->execute([$exam_id]);
    $available_dates = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ম্যানুয়াল রুম বন্টন</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <style>
    body { 
      font-family: 'Hind Siliguri', sans-serif; 
      background-color: #f8f9fa;
    }
    .heading h4 { 
      font-weight: bold; 
    }
    .customizable-text {
      /* Default styles that can be customized */
      font-size: 16px;
      color: #000000;
      font-weight: normal;
    }
    .institution-address {
      font-size: 14px;
      color: #666666;
      font-weight: normal;
    }
    .room-allocation-table th, 
    .room-allocation-table td {
      text-align: center;
      vertical-align: middle;
      padding: 5px; /* Reduce padding for larger fonts */
      border: 1px solid #000 !important; /* Ensure borders are always visible */
    }
    /* Adjust table layout for very large fonts */
    .table-responsive {
      overflow-x: auto;
    }
    @media print {
      .no-print { 
        display: none !important; 
      }
      body { 
        background-color: white;
        -webkit-print-color-adjust: exact; 
        print-color-adjust: exact; 
      }
      .card {
        box-shadow: none;
        border: 1px solid #dee2e6;
      }
      .heading h4 {
        color: #000000 !important;
      }
      .institution-address {
        color: #666666 !important;
      }
      .room-allocation-table th, 
      .room-allocation-table td {
        border: 1px solid #000 !important; /* Ensure borders are always visible in print */
      }
    }
    
    /* Styles for text selection highlighting - only outline, no background color */
    .selection-mode *:hover {
        cursor: pointer !important;
    }
    
    .selected-for-formatting {
        outline: 2px dashed #007bff !important;
        outline-offset: 2px;
    }
    
    .selection-notification {
        transition: opacity 0.3s;
    }
  </style>
</head>
<body>
<div class="container-fluid py-4">
  <div class="d-flex align-items-center gap-2 mb-3">
    <h4 class="mb-0"><i class="fas fa-door-open"></i> ম্যানুয়াল রুম বন্টন</h4>
    <div class="ms-auto">
      <a href="../index.php" class="btn btn-sm btn-outline-secondary"><i class="fas fa-home"></i> হোম</a>
    </div>
  </div>

  <!-- Form for selecting exam and date -->
  <div class="card mb-4 no-print">
    <div class="card-header">
      <strong><i class="fas fa-filter"></i> পরীক্ষা ও তারিখ নির্বাচন</strong>
    </div>
    <div class="card-body">
      <form method="get" class="row g-3">
        <div class="col-md-6">
          <label class="form-label">পরীক্ষা নির্বাচন করুন</label>
          <select name="exam_id" class="form-select" required onchange="this.form.submit()">
            <option value="">নির্বাচন করুন</option>
            <?php foreach ($exams as $exam): ?>
              <option value="<?= (int)$exam['id'] ?>" <?= ((int)$exam['id']===$exam_id?'selected':'') ?>><?= htmlspecialchars($exam['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        
        <?php if ($exam_id && !empty($allowed_dates)): ?>
        <div class="col-md-6">
          <label class="form-label">তারিখ নির্বাচন করুন</label>
          <select name="date" class="form-select" required onchange="this.form.submit()">
            <option value="">নির্বাচন করুন</option>
            <?php foreach ($allowed_dates as $date): ?>
              <option value="<?= htmlspecialchars($date) ?>" <?= ($date===$dateFilter?'selected':'') ?>><?= htmlspecialchars($date) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <?php endif; ?>
      </form>
    </div>
  </div>

  <?php if ($exam_id && $dateFilter && $current_exam): ?>
  <!-- Main content for room allocation -->
  <div class="card">
    <div class="card-header d-flex align-items-center">
      <strong><i class="fas fa-list"></i> রুম বন্টন তালিকা</strong>
      <div class="ms-auto no-print">
        <button class="btn btn-sm btn-success" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট</button>
      </div>
    </div>
    <div class="card-body">
      <!-- Institution Header -->
      <div class="text-center mb-4">
        <?php if ($logo_image): ?>
        <div class="mb-2">
          <img src="../<?= htmlspecialchars($logo_image) ?>" alt="Logo" class="img-fluid" style="max-height: <?= $logo_size ?>px; opacity: <?= $logo_opacity ?>; max-width: 200px; object-fit: contain;">
        </div>
        <?php endif; ?>
        <h4 class="mb-1"><?= htmlspecialchars($site_name) ?></h4>
        <div class="institution-address"><?= htmlspecialchars($site_address) ?></div>
      </div>
      
      <!-- Exam Details -->
      <div class="text-center mb-4">
        <h5 class="mb-2">পরীক্ষার রুম বন্টন</h5>
        <div class="mb-1"><strong>পরীক্ষার নাম:</strong> <?= htmlspecialchars($current_exam['name']) ?></div>
        <div class="mb-1"><strong>তারিখ:</strong> <?= htmlspecialchars($dateFilter) ?></div>
        <?php if (isset($date_subjects[$dateFilter])): ?>
        <div>
          <strong>বিষয়সমূহ:</strong> 
          <?php 
            $subjects = array_map(function($pair) { 
              return $pair[0] . ' (' . $pair[1] . ')'; 
            }, $date_subjects[$dateFilter]); 
            echo htmlspecialchars(implode(', ', $subjects));
          ?>
        </div>
        <?php endif; ?>
      </div>
      
      <!-- Add date selection section -->
      <div class="card mb-4 no-print">
        <div class="card-header">
          <strong><i class="fas fa-calendar-alt"></i> সীট প্লান প্রয়োগের তারিখ নির্বাচন</strong>
        </div>
        <div class="card-body">
          <div class="mb-3">
            <label class="form-label">এই সীট প্লান নিচের তারিখগুলোতে প্রয়োগ করুন:</label>
            <div class="row">
                <?php foreach ($available_dates as $date): ?>
                    <?php if ($date != $dateFilter): // Don't show current date ?>
                        <div class="col-md-3 mb-2">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="apply_to_dates[]" value="<?= htmlspecialchars($date) ?>" id="date_<?= str_replace('-', '_', $date) ?>">
                                <label class="form-check-label" for="date_<?= str_replace('-', '_', $date) ?>">
                                    <?= htmlspecialchars($date) ?>
                                </label>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
            <?php if (count($available_dates) <= 1): ?>
                <div class="alert alert-info">এই পরীক্ষার জন্য আরও তারিখ নেই।</div>
            <?php endif; ?>
          </div>
        </div>
      </div>
      
      <!-- Customization Panel (Only in edit mode) -->
      <div class="card mb-4 no-print">
        <div class="card-header">
          <strong><i class="fas fa-sliders-h"></i> টেক্সট কাস্টমাইজেশন এবং রিটেনশন সেটিংস</strong>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <!-- Existing customization controls -->
            <div class="col-md-3">
              <label class="form-label">ফন্ট সাইজ</label>
              <select class="form-select" id="fontSizeSelector" name="font_size">
                <?php for ($i = 10; $i <= 40; $i++): ?>
                    <option value="<?= $i ?>" <?= (isset($customization_settings['font_size']) && $customization_settings['font_size'] == $i) ? 'selected' : '' ?>><?= $i ?> পিক্সেল</option>
                <?php endfor; ?>
              </select>
              <!-- Font size slider -->
              <div class="mt-2">
                <label class="form-label">ফন্ট সাইজ বার:</label>
                <input type="range" class="form-range" id="fontSizeSlider" min="10" max="40" step="1" value="<?= isset($customization_settings['font_size']) ? (int)$customization_settings['font_size'] : 14 ?>" oninput="updateFontSizeFromSlider(this.value)">
                <div class="text-center" id="fontSizeSliderValue"><?= isset($customization_settings['font_size']) ? (int)$customization_settings['font_size'] : 14 ?>px</div>
              </div>
            </div>
            <div class="col-md-3">
              <label class="form-label">টেক্সট কালার</label>
              <input type="color" class="form-control form-control-color" id="textColorSelector" name="text_color" value="<?= isset($customization_settings['text_color']) ? htmlspecialchars($customization_settings['text_color']) : '#000000' ?>">
            </div>
            <div class="col-md-3">
              <label class="form-label">ফন্ট ওজন</label>
              <select class="form-select" id="fontWeightSelector" name="font_weight">
                <option value="normal" <?= (!isset($customization_settings['font_weight']) || $customization_settings['font_weight'] == 'normal') ? 'selected' : '' ?>>সাধারণ</option>
                <option value="bold" <?= (isset($customization_settings['font_weight']) && $customization_settings['font_weight'] == 'bold') ? 'selected' : '' ?>>বোল্ড</option>
              </select>
            </div>
            <!-- Header customization controls -->
            <div class="col-md-3">
              <label class="form-label">প্রতিষ্ঠানের নাম - ফন্ট সাইজ</label>
              <select class="form-select" id="headerFontSizeSelector" name="header_font_size">
                <?php for ($i = 16; $i <= 50; $i++): ?>
                    <option value="<?= $i ?>" <?= (isset($customization_settings['header_font_size']) && $customization_settings['header_font_size'] == $i) ? 'selected' : '' ?>><?= $i ?> পিক্সেল</option>
                <?php endfor; ?>
              </select>
            </div>
            <div class="col-md-3">
              <label class="form-label">প্রতিষ্ঠানের নাম - টেক্সট কালার</label>
              <input type="color" class="form-control form-control-color" id="headerTextColorSelector" name="header_text_color" value="<?= isset($customization_settings['header_text_color']) ? htmlspecialchars($customization_settings['header_text_color']) : '#000000' ?>">
            </div>
            <div class="col-md-3">
              <label class="form-label">প্রতিষ্ঠানের নাম - ফন্ট ওজন</label>
              <select class="form-select" id="headerFontWeightSelector" name="header_font_weight">
                <option value="normal" <?= (!isset($customization_settings['header_font_weight']) || $customization_settings['header_font_weight'] == 'normal') ? 'selected' : '' ?>>সাধারণ</option>
                <option value="bold" <?= (isset($customization_settings['header_font_weight']) && $customization_settings['header_font_weight'] == 'bold') ? 'selected' : '' ?>>বোল্ড</option>
              </select>
            </div>
            <!-- Selected text customization controls -->
            <div class="col-md-3">
              <label class="form-label">নির্বাচিত টেক্সট - ফন্ট সাইজ</label>
              <select class="form-select" id="selectedTextFontSizeSelector" name="selected_text_font_size">
                <?php for ($i = 10; $i <= 40; $i++): ?>
                    <option value="<?= $i ?>" <?= (isset($customization_settings['selected_text_font_size']) && $customization_settings['selected_text_font_size'] == $i) ? 'selected' : '' ?>><?= $i ?> পিক্সেল</option>
                <?php endfor; ?>
              </select>
            </div>
            <div class="col-md-3">
              <label class="form-label">নির্বাচিত টেক্সট - টেক্সট কালার</label>
              <input type="color" class="form-control form-control-color" id="selectedTextColorSelector" name="selected_text_color" value="<?= isset($customization_settings['selected_text_color']) ? htmlspecialchars($customization_settings['selected_text_color']) : '#000000' ?>">
            </div>
            <div class="col-md-3">
              <label class="form-label">নির্বাচিত টেক্সট - ফন্ট ওজন</label>
              <select class="form-select" id="selectedTextFontWeightSelector" name="selected_text_font_weight">
                <option value="normal" <?= (!isset($customization_settings['selected_text_font_weight']) || $customization_settings['selected_text_font_weight'] == 'normal') ? 'selected' : '' ?>>সাধারণ</option>
                <option value="bold" <?= (isset($customization_settings['selected_text_font_weight']) && $customization_settings['selected_text_font_weight'] == 'bold') ? 'selected' : '' ?>>বোল্ড</option>
              </select>
            </div>
            <!-- Retention limit control -->
            <div class="col-md-3">
                <label class="form-label">সীট প্লান রিটেনশন লিমিট</label>
                <select class="form-select" name="retention_type">
                    <option value="count" <?= $retention_type == 'count' ? 'selected' : '' ?>>সংখ্যা অনুযায়ী</option>
                    <option value="duration" <?= $retention_type == 'duration' ? 'selected' : '' ?>>সময় অনুযায়ী</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">সীট প্লান সংখ্যা রিটেনশন লিমিট</label>
                <select class="form-select" name="retention_limit">
                    <option value="0" <?= $retention_limit == 0 ? 'selected' : '' ?>>সবগুলো রাখুন</option>
                    <option value="1" <?= $retention_limit == 1 ? 'selected' : '' ?>>শুধু সর্বশেষ ১টি</option>
                    <option value="3" <?= $retention_limit == 3 ? 'selected' : '' ?>>সর্বশেষ ৩টি</option>
                    <option value="5" <?= $retention_limit == 5 ? 'selected' : '' ?>>সর্বশেষ ৫টি</option>
                    <option value="10" <?= $retention_limit == 10 ? 'selected' : '' ?>>সর্বশেষ ১০টি</option>
                    <option value="15" <?= $retention_limit == 15 ? 'selected' : '' ?>>সর্বশেষ ১৫টি</option>
                    <option value="20" <?= $retention_limit == 20 ? 'selected' : '' ?>>সর্বশেষ ২০টি</option>
                </select>
                <small class="form-text text-muted">নির্বাচিত সংখ্যক সর্বশেষ সীট প্লান রাখা হবে, বাকিগুলো মুছে ফেলা হবে</small>
            </div>
            <div class="col-md-3">
                <label class="form-label">সীট প্লান সময় রিটেনশন লিমিট</label>
                <select class="form-select" name="retention_duration_days">
                    <option value="0" <?= $retention_duration_days == 0 ? 'selected' : '' ?>>সবগুলো রাখুন</option>
                    <option value="7" <?= $retention_duration_days == 7 ? 'selected' : '' ?>>৭ দিন</option>
                    <option value="14" <?= $retention_duration_days == 14 ? 'selected' : '' ?>>১৪ দিন</option>
                    <option value="30" <?= $retention_duration_days == 30 ? 'selected' : '' ?>>৩০ দিন</option>
                    <option value="60" <?= $retention_duration_days == 60 ? 'selected' : '' ?>>৬০ দিন</option>
                    <option value="90" <?= $retention_duration_days == 90 ? 'selected' : '' ?>>৯০ দিন</option>
                </select>
                <small class="form-text text-muted">নির্বাচিত সময়ের মধ্যে সীট প্লান রাখা হবে, বাকিগুলো মুছে ফেলা হবে</small>
            </div>
            
            <div class="col-md-3 d-flex align-items-end">
                <button class="btn btn-primary w-100" onclick="applyCustomizations()">প্রয়োগ করুন</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Hidden fields to store customization values in the form -->
      <input type="hidden" id="hiddenFontSize" name="font_size" value="<?= isset($customization_settings['font_size']) ? (int)$customization_settings['font_size'] : 14 ?>">
      <input type="hidden" id="hiddenTextColor" name="text_color" value="<?= isset($customization_settings['text_color']) ? htmlspecialchars($customization_settings['text_color']) : '#000000' ?>">
      <input type="hidden" id="hiddenFontWeight" name="font_weight" value="<?= isset($customization_settings['font_weight']) ? htmlspecialchars($customization_settings['font_weight']) : 'normal' ?>">
      <input type="hidden" id="hiddenHeaderFontSize" name="header_font_size" value="<?= isset($customization_settings['header_font_size']) ? (int)$customization_settings['header_font_size'] : 24 ?>">
      <input type="hidden" id="hiddenHeaderTextColor" name="header_text_color" value="<?= isset($customization_settings['header_text_color']) ? htmlspecialchars($customization_settings['header_text_color']) : '#000000' ?>">
      <input type="hidden" id="hiddenHeaderFontWeight" name="header_font_weight" value="<?= isset($customization_settings['header_font_weight']) ? htmlspecialchars($customization_settings['header_font_weight']) : 'bold' ?>">
      <input type="hidden" id="hiddenSelectedTextFontSize" name="selected_text_font_size" value="<?= isset($customization_settings['selected_text_font_size']) ? (int)$customization_settings['selected_text_font_size'] : 14 ?>">
      <input type="hidden" id="hiddenSelectedTextColor" name="selected_text_color" value="<?= isset($customization_settings['selected_text_color']) ? htmlspecialchars($customization_settings['selected_text_color']) : '#000000' ?>">
      <input type="hidden" id="hiddenSelectedTextFontWeight" name="selected_text_font_weight" value="<?= isset($customization_settings['selected_text_font_weight']) ? htmlspecialchars($customization_settings['selected_text_font_weight']) : 'normal' ?>">

      <!-- Room Allocation Table -->
      <form method="post" id="allocationForm">
        <input type="hidden" name="action" value="save_allocations">
        <input type="hidden" name="exam_id" value="<?= $exam_id ?>">
        <input type="hidden" name="date" value="<?= htmlspecialchars($dateFilter) ?>">
        
        <div class="table-responsive">
          <table class="table table-bordered align-middle mb-0 room-allocation-table">
            <thead class="table-light">
              <tr>
                <th style="width: 5%">ক্রমিক</th>
                <th style="width: 15%">রুম নং</th>
                <th style="width: 20%">রোল (থেকে)</th>
                <th style="width: 20%">রোল (পর্যন্ত)</th>
                <th style="width: 25%">বিভাগ/শাখা</th>
                <th style="width: 10%">মোট সংখ্যা</th>
                <th style="width: 5%" class="no-print">অ্যাকশন</th>
              </tr>
            </thead>
            <tbody id="allocationTableBody">
              <?php if (!empty($saved_allocations)): ?>
                <?php foreach ($saved_allocations as $index => $allocation): ?>
                <tr>
                  <td><?= $index + 1 ?></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[<?= $index ?>][room]" value="<?= htmlspecialchars($allocation['room']) ?>"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[<?= $index ?>][from_roll]" value="<?= htmlspecialchars($allocation['from_roll']) ?>"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[<?= $index ?>][to_roll]" value="<?= htmlspecialchars($allocation['to_roll']) ?>"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[<?= $index ?>][department]" value="<?= htmlspecialchars($allocation['department']) ?>"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[<?= $index ?>][total]" value="<?= htmlspecialchars($allocation['total']) ?>"></td>
                  <td class="no-print">
                    <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)"><i class="fas fa-trash"></i></button>
                  </td>
                </tr>
                <?php endforeach; ?>
              <?php else: ?>
                <!-- Sample rows for initial entry -->
                <tr>
                  <td>1</td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[0][room]" placeholder="রুম নং"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[0][from_roll]" placeholder="শুরু রোল"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[0][to_roll]" placeholder="শেষ রোল"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[0][department]" placeholder="বিভাগ"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[0][total]" placeholder="মোট"></td>
                  <td class="no-print">
                    <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)"><i class="fas fa-trash"></i></button>
                  </td>
                </tr>
                <tr>
                  <td>2</td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[1][room]" placeholder="রুম নং"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[1][from_roll]" placeholder="শুরু রোল"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[1][to_roll]" placeholder="শেষ রোল"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[1][department]" placeholder="বিভাগ"></td>
                  <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[1][total]" placeholder="মোট"></td>
                  <td class="no-print">
                    <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)"><i class="fas fa-trash"></i></button>
                  </td>
                </tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
        
        <div class="mt-3 no-print">
          <button type="button" class="btn btn-secondary" onclick="addNewRow()"><i class="fas fa-plus"></i> নতুন সারি যোগ</button>
          <button type="button" class="btn btn-info" onclick="toggleTextSelection()"><i class="fas fa-mouse-pointer"></i> টেক্সট নির্বাচন মোড</button>
          <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> সংরক্ষণ করুন</button>
        </div>
      </form>
    </div>
  </div>
  <?php elseif ($exam_id && !$dateFilter): ?>
  <div class="alert alert-info">একটি তারিখ নির্বাচন করুন রুম বন্টন তৈরি করতে।</div>
  <?php elseif (!$exam_id): ?>
  <div class="alert alert-info">একটি পরীক্ষা নির্বাচন করুন শুরু করতে।</div>
  <?php endif; ?>
</div>

<script>
let rowIndex = <?= !empty($saved_allocations) ? count($saved_allocations) : 2 ?>;
let textSelectionMode = false;
let selectedElements = [];

function addNewRow() {
  const tbody = document.getElementById('allocationTableBody');
  const newRow = document.createElement('tr');
  
  newRow.innerHTML = `
    <td>${++rowIndex}</td>
    <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[${rowIndex-1}][room]" placeholder="রুম নং"></td>
    <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[${rowIndex-1}][from_roll]" placeholder="শুরু রোল"></td>
    <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[${rowIndex-1}][to_roll]" placeholder="শেষ রোল"></td>
    <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[${rowIndex-1}][department]" placeholder="বিভাগ"></td>
    <td><input type="text" class="form-control form-control-sm customizable-text" name="allocations[${rowIndex-1}][total]" placeholder="মোট"></td>
    <td class="no-print">
      <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)"><i class="fas fa-trash"></i></button>
    </td>
  `;
  
  tbody.appendChild(newRow);
}

function removeRow(button) {
  const row = button.closest('tr');
  row.remove();
  // We don't decrement rowIndex to avoid conflicts with form indices
}

function updateFontSizeFromSlider(value) {
  document.getElementById('fontSizeSelector').value = value;
  document.getElementById('fontSizeSliderValue').textContent = value + 'px';
  // Also update the hidden field
  document.getElementById('hiddenFontSize').value = value;
  applyCustomizations();
}

function applyCustomizations() {
    const fontSizeSelect = document.getElementById('fontSizeSelector');
    const textColorInput = document.getElementById('textColorSelector');
    const fontWeightSelect = document.getElementById('fontWeightSelector');
    const fontSizeSlider = document.getElementById('fontSizeSlider');
    
    // Header customization elements
    const headerFontSizeSelect = document.getElementById('headerFontSizeSelector');
    const headerTextColorInput = document.getElementById('headerTextColorSelector');
    const headerFontWeightSelect = document.getElementById('headerFontWeightSelector');
    
    // Selected text customization elements
    const selectedTextFontSizeSelect = document.getElementById('selectedTextFontSizeSelector');
    const selectedTextColorInput = document.getElementById('selectedTextColorSelector');
    const selectedTextFontWeightSelect = document.getElementById('selectedTextFontWeightSelector');
    
    const fontSize = fontSizeSelect.value + 'px';
    const textColor = textColorInput.value;
    const fontWeight = fontWeightSelect.value;
    
    const headerFontSize = headerFontSizeSelect.value + 'px';
    const headerTextColor = headerTextColorInput.value;
    const headerFontWeight = headerFontWeightSelect.value;
    
    const selectedTextFontSize = selectedTextFontSizeSelect.value + 'px';
    const selectedTextColor = selectedTextColorInput.value;
    const selectedTextFontWeight = selectedTextFontWeightSelect.value;
    
    // Update hidden fields
    document.getElementById('hiddenFontSize').value = fontSizeSelect.value;
    document.getElementById('hiddenTextColor').value = textColorInput.value;
    document.getElementById('hiddenFontWeight').value = fontWeightSelect.value;
    
    // Update header hidden fields
    document.getElementById('hiddenHeaderFontSize').value = headerFontSizeSelect.value;
    document.getElementById('hiddenHeaderTextColor').value = headerTextColorInput.value;
    document.getElementById('hiddenHeaderFontWeight').value = headerFontWeightSelect.value;
    
    // Update selected text hidden fields
    document.getElementById('hiddenSelectedTextFontSize').value = selectedTextFontSizeSelect.value;
    document.getElementById('hiddenSelectedTextColor').value = selectedTextColorInput.value;
    document.getElementById('hiddenSelectedTextFontWeight').value = selectedTextFontWeightSelect.value;
    
    // Update slider to match select value
    if (fontSizeSlider) {
        fontSizeSlider.value = fontSizeSelect.value;
        document.getElementById('fontSizeSliderValue').textContent = fontSizeSelect.value + 'px';
    }
    
    // Apply to all customizable text elements (excluding header)
    const customizableElements = document.querySelectorAll('.customizable-text');
    customizableElements.forEach(element => {
        element.style.fontSize = fontSize;
        element.style.color = textColor;
        element.style.fontWeight = fontWeight;
    });
    
    // Apply header customization ONLY to institution name
    const headerElement = document.querySelector('.heading h4');
    if (headerElement) {
        headerElement.style.fontSize = headerFontSize;
        headerElement.style.color = headerTextColor;
        headerElement.style.fontWeight = headerFontWeight;
    }
    
    // Apply to institution address (separate styling)
    const addressElements = document.querySelectorAll('.institution-address');
    addressElements.forEach(element => {
        element.style.fontSize = fontSize;
        element.style.color = textColor;
        element.style.fontWeight = fontWeight;
    });
    
    // Also apply to table cells
    const tableCells = document.querySelectorAll('.room-allocation-table td, .room-allocation-table th');
    tableCells.forEach(cell => {
        cell.style.fontSize = fontSize;
        cell.style.color = textColor;
        if (cell.tagName === 'TH') {
            cell.style.fontWeight = fontWeight;
        }
    });
    
    alert('কাস্টমাইজেশন প্রয়োগ করা হয়েছে!');
}

function applySelectedTextFormatting() {
    // Get selected formatting values from the customization controls
    const selectedTextFontSizeSelect = document.getElementById('selectedTextFontSizeSelector');
    const selectedTextColorInput = document.getElementById('selectedTextColorSelector');
    const selectedTextFontWeightSelect = document.getElementById('selectedTextFontWeightSelector');
    
    const fontSize = selectedTextFontSizeSelect ? selectedTextFontSizeSelect.value + 'px' : '18px';
    const textColor = selectedTextColorInput ? selectedTextColorInput.value : '#ff0000';
    const fontWeight = selectedTextFontWeightSelect ? selectedTextFontWeightSelect.value : 'bold';
    
    // Apply formatting to all selected elements
    selectedElements.forEach(el => {
        el.style.fontSize = fontSize;
        el.style.color = textColor;
        el.style.fontWeight = fontWeight;
        el.classList.add('selected-text');
    });
    
    showNotification('নির্বাচিত টেক্সটে ফরম্যাটিং প্রয়োগ করা হয়েছে।');
    
    // Exit selection mode after applying formatting
    toggleTextSelection();
}

function toggleTextSelection() {
    textSelectionMode = !textSelectionMode;
    selectedElements = [];
    document.querySelectorAll('.selected-for-formatting').forEach(el => el.classList.remove('selected-for-formatting'));
    
    // Remove apply button if it exists
    const applyBtn = document.getElementById('apply-selected-formatting');
    if (applyBtn) applyBtn.remove();
    
    if (textSelectionMode) {
        document.body.style.cursor = 'pointer';
        showNotification('টেক্সট নির্বাচন মোড সক্রিয়। ক্লিক করে টেক্সট নির্বাচন করুন।');
    } else {
        document.body.style.cursor = 'default';
        showNotification('টেক্সট নির্বাচন মোড অসক্রিয়।');
    }
}

function showApplyButton() {
    // Remove existing apply button if any
    const existing = document.getElementById('apply-selected-formatting');
    if (existing) existing.remove();
    
    // Create apply button
    const applyBtn = document.createElement('button');
    applyBtn.id = 'apply-selected-formatting';
    applyBtn.className = 'btn btn-success position-fixed bottom-0 end-0 m-3';
    applyBtn.innerHTML = '<i class="fas fa-check"></i> নির্বাচিত টেক্সটে ফরম্যাটিং প্রয়োগ করুন';
    applyBtn.onclick = applySelectedTextFormatting;
    
    document.body.appendChild(applyBtn);
}

function hideApplyButton() {
    const applyBtn = document.getElementById('apply-selected-formatting');
    if (applyBtn) applyBtn.remove();
}

function showNotification(message) {
    // Remove existing notification if any
    const existing = document.querySelector('.selection-notification');
    if (existing) existing.remove();
    
    // Create notification
    const notification = document.createElement('div');
    notification.className = 'selection-notification alert alert-info position-fixed top-0 start-50 translate-middle-x mt-3';
    notification.style.zIndex = '9999';
    notification.innerHTML = message;
    
    document.body.appendChild(notification);
    
    // Auto remove after 3 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 3000);
}

// Add click event listeners for text selection mode
document.addEventListener('click', function(e) {
    if (!textSelectionMode) return;
    
    // Prevent default behavior
    e.preventDefault();
    
    // Check if clicked element is text-containing
    const target = e.target;
    if (target.nodeType === Node.ELEMENT_NODE && 
        (target.textContent.trim() !== '' || 
         target.tagName === 'TD' || 
         target.tagName === 'TH' || 
         target.classList.contains('customizable-text'))) {
        
        // Toggle selection class
        if (target.classList.contains('selected-for-formatting')) {
            target.classList.remove('selected-for-formatting');
            // Remove from selectedElements array
            const index = selectedElements.indexOf(target);
            if (index > -1) {
                selectedElements.splice(index, 1);
            }
        } else {
            target.classList.add('selected-for-formatting');
            selectedElements.push(target);
        }
        
        // Show apply button if any elements are selected
        if (selectedElements.length > 0) {
            showApplyButton();
        } else {
            hideApplyButton();
        }
    }
});

// Add CSS for selection highlighting
const style = document.createElement('style');
style.innerHTML = `
    .selection-mode *:hover {
        cursor: pointer !important;
    }
    
    .selected-for-formatting {
        outline: 2px dashed #007bff !important;
        outline-offset: 2px;
    }
    
    .selection-notification {
        transition: opacity 0.3s;
    }
`;
document.head.appendChild(style);
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>