<?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());
}

// Font customization parameters
$font_size = isset($_GET['font_size']) ? (int)$_GET['font_size'] : 14;
$text_color = isset($_GET['text_color']) ? $_GET['text_color'] : '#000000';
$font_weight = isset($_GET['font_weight']) ? $_GET['font_weight'] : 'normal';

// Separate customization for institution name
$header_font_size = isset($_GET['header_font_size']) ? (int)$_GET['header_font_size'] : 24;
$header_text_color = isset($_GET['header_text_color']) ? $_GET['header_text_color'] : '#000000';
$header_font_weight = isset($_GET['header_font_weight']) ? $_GET['header_font_weight'] : 'bold';

// Selected text customization parameters
$selected_text_font_size = isset($_GET['selected_text_font_size']) ? (int)$_GET['selected_text_font_size'] : $font_size;
$selected_text_color = isset($_GET['selected_text_color']) ? $_GET['selected_text_color'] : $text_color;
$selected_text_font_weight = isset($_GET['selected_text_font_weight']) ? $_GET['selected_text_font_weight'] : $font_weight;

// Get allocations from database
$allocations = [];
if ($exam_id && $dateFilter) {
    // First, try to get customization settings from database ONLY if URL parameters are not provided
    // This allows URL parameters to take precedence over database values
    $useDatabaseSettings = !isset($_GET['font_size']) && !isset($_GET['text_color']) && !isset($_GET['font_weight']) && 
                          !isset($_GET['header_font_size']) && !isset($_GET['header_text_color']) && !isset($_GET['header_font_weight']) &&
                          !isset($_GET['selected_text_font_size']) && !isset($_GET['selected_text_color']) && !isset($_GET['selected_text_font_weight']);
    
    if ($useDatabaseSettings) {
        $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 = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Use database values if available
        if ($customization) {
            $font_size = isset($customization['font_size']) ? (int)$customization['font_size'] : $font_size;
            $text_color = isset($customization['text_color']) ? $customization['text_color'] : $text_color;
            $font_weight = isset($customization['font_weight']) ? $customization['font_weight'] : $font_weight;
            $header_font_size = isset($customization['header_font_size']) ? (int)$customization['header_font_size'] : $header_font_size;
            $header_text_color = isset($customization['header_text_color']) ? $customization['header_text_color'] : $header_text_color;
            $header_font_weight = isset($customization['header_font_weight']) ? $customization['header_font_weight'] : $header_font_weight;
            $selected_text_font_size = isset($customization['selected_text_font_size']) ? (int)$customization['selected_text_font_size'] : $selected_text_font_size;
            $selected_text_color = isset($customization['selected_text_color']) ? $customization['selected_text_color'] : $selected_text_color;
            $selected_text_font_weight = isset($customization['selected_text_font_weight']) ? $customization['selected_text_font_weight'] : $selected_text_font_weight;
        }
    }
    
    // Get all allocations
    $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]);
    $allocations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Handle retention cleanup (for duration-based retention)
    // Get retention settings for this exam
    $retentionStmt = $pdo->prepare("SELECT retention_type, retention_duration_days FROM retention_settings WHERE exam_id = ?");
    $retentionStmt->execute([$exam_id]);
    $retentionSettings = $retentionStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($retentionSettings && $retentionSettings['retention_type'] === 'duration' && $retentionSettings['retention_duration_days'] > 0) {
        // Delete records older than the specified duration
        $cutoffDate = date('Y-m-d', strtotime("-{$retentionSettings['retention_duration_days']} days"));
        $deleteStmt = $pdo->prepare("DELETE FROM manual_room_allocations WHERE exam_id = ? AND exam_date < ?");
        $deleteStmt->execute([$exam_id, $cutoffDate]);
    }
}

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

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'];
        
        // Prepare retention text for display
        if ($retention_type === 'count') {
            if ($retention_limit == 0) {
                $retention_text = 'সবগুলো সীট প্লান রাখা হবে';
            } else {
                $retention_text = "শুধু সর্বশেষ {$retention_limit}টি সীট প্লান রাখা হবে";
            }
        } else {
            if ($retention_duration_days == 0) {
                $retention_text = 'সবগুলো সীট প্লান রাখা হবে';
            } else {
                $retention_text = "{$retention_duration_days} দিন পর্যন্ত সীট প্লান রাখা হবে";
            }
        }
    }
}

// Get all dates for this exam that have seat plans
$seat_plan_dates = [];
if ($exam_id) {
    $stmt = $pdo->prepare("SELECT DISTINCT exam_date FROM manual_room_allocations WHERE exam_id = ? ORDER BY exam_date");
    $stmt->execute([$exam_id]);
    $seat_plan_dates = $stmt->fetchAll(PDO::FETCH_COLUMN);
}

function formatDateToBangla($dateString) {
    // Convert YYYY-MM-DD to DD/MM/YYYY format
    $date = new DateTime($dateString);
    return $date->format('d/m/Y');
}

function formatDateToBanglaLong($dateString) {
    // Convert YYYY-MM-DD to a more readable format in Bangla
    $months = [
        '01' => 'জানুয়ারি',
        '02' => 'ফেব্রুয়ারি',
        '03' => 'মার্চ',
        '04' => 'এপ্রিল',
        '05' => 'মে',
        '06' => 'জুন',
        '07' => 'জুলাই',
        '08' => 'আগস্ট',
        '09' => 'সেপ্টেম্বর',
        '10' => 'অক্টোবর',
        '11' => 'নভেম্বর',
        '12' => 'ডিসেম্বর'
    ];
    
    $date = new DateTime($dateString);
    $day = $date->format('d');
    $month = $months[$date->format('m')];
    $year = $date->format('Y');
    
    // Convert numbers to Bangla numerals
    $banglaNumbers = ['0' => '০', '1' => '১', '2' => '২', '3' => '৩', '4' => '৪', '5' => '৫', '6' => '৬', '7' => '৭', '8' => '৮', '9' => '৯'];
    $dayBangla = strtr($day, $banglaNumbers);
    $yearBangla = strtr($year, $banglaNumbers);
    
    return "$dayBangla $month, $yearBangla";
}
?>
<!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://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; 
      font-size: <?= $font_size ?>px;
      color: <?= $text_color ?>;
      font-weight: <?= $font_weight ?>;
    }
    .heading h4 { 
      font-weight: <?= $header_font_weight ?>;
      font-size: <?= $header_font_size ?>px !important;
      color: <?= $header_text_color ?> !important;
    }
    .institution-address {
      font-size: <?= $font_size ?>px !important;
      color: <?= $text_color ?> !important;
      font-weight: <?= $font_weight ?>;
    }
    .print-table th,
    .print-table td {
      text-align: center;
      vertical-align: middle;
      font-size: <?= $font_size ?>px !important;
      color: <?= $text_color ?>;
      font-weight: <?= $font_weight ?>;
      padding: 5px !important; /* Reduce padding for larger fonts */
      border: 1px solid #000 !important; /* Ensure borders are always visible */
    }
    .print-table th {
      font-weight: bold;
      border: 1px solid #000 !important; /* Ensure header borders are always visible */
    }
    /* Ensure font size is applied to all text elements except header */
    h1, h2, h3, h5, h6, p, div:not(.heading), span, td, th, label {
      font-size: <?= $font_size ?>px !important;
      color: <?= $text_color ?> !important;
    }
    h5 {
      font-size: <?= min($font_size + 2, 20) ?>px !important;
      color: <?= $text_color ?> !important;
    }
    /* Styles for selected text formatting */
    .selected-text {
      font-size: <?= $selected_text_font_size ?>px !important;
      color: <?= $selected_text_color ?> !important;
      font-weight: <?= $selected_text_font_weight ?> !important;
    }
    /* Adjust table layout for very large fonts */
    @media screen {
      .table-responsive {
        overflow-x: auto;
      }
    }
    @page { 
      size: A4; 
      margin: <?php echo isset($_GET['margin']) ? (int)$_GET['margin'] : 15; ?>mm; 
    }
    @media print {
      .no-print { 
        display: none !important; 
      }
      body { 
        -webkit-print-color-adjust: exact; 
        print-color-adjust: exact; 
        font-size: <?= $font_size ?>px !important;
        color: <?= $text_color ?> !important;
      }
      .container { 
        max-width: 100% !important; 
        width: 100% !important; 
        margin: 0 !important; 
        padding: 0 !important; 
      }
      .card { 
        box-shadow: none !important; 
        border: none !important;
      }
      /* Ensure font size is applied in print mode except for header */
      h1, h2, h3, h5, h6, p, div:not(.heading), span, td, th, label {
        font-size: <?= $font_size ?>px !important;
        color: <?= $text_color ?> !important;
      }
      .heading h4 { 
        font-weight: <?= $header_font_weight ?>;
        font-size: <?= $header_font_size ?>px !important;
        color: <?= $header_text_color ?> !important;
      }
      .institution-address {
        font-size: <?= $font_size ?>px !important;
        color: <?= $text_color ?> !important;
        font-weight: <?= $font_weight ?>;
      }
      h5 {
        font-size: <?= min($font_size + 2, 20) ?>px !important;
        color: <?= $text_color ?> !important;
      }
      .print-table th,
      .print-table td {
        font-size: <?= $font_size ?>px !important;
        color: <?= $text_color ?> !important;
        padding: 2px !important; /* Reduce padding for larger fonts in print */
        border: 1px solid #000 !important; /* Ensure borders are always visible in print */
      }
      /* Selected text styles in print */
      .selected-text {
        font-size: <?= $selected_text_font_size ?>px !important;
        color: <?= $selected_text_color ?> !important;
        font-weight: <?= $selected_text_font_weight ?> !important;
      }
      /* Adjust page margins for very large fonts */
      @page {
        margin: <?php echo max(5, isset($_GET['margin']) ? (int)$_GET['margin'] : 15) - max(0, ($font_size - 14) * 0.2); ?>mm;
      }
    }
  </style>
</head>
<body>
<div class="container my-4">
  <!-- 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>
    <?php if ($current_exam): ?>
    <div class="mb-1"><strong>পরীক্ষার নাম:</strong> <?= htmlspecialchars($current_exam['name']) ?></div>
    <?php endif; ?>
    <div class="mb-1"><strong>তারিখ:</strong> <?= formatDateToBanglaLong($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; ?>
    <!-- Seat Plan Dates Information -->
    <?php if (!empty($seat_plan_dates)): ?>
    <div class="mt-2">
        <strong>এই সীট প্লান প্রযোজ্য তারিখসমূহ:</strong> 
        <?php 
            $formatted_dates = array_map(function($date) {
                return formatDateToBanglaLong($date);
            }, $seat_plan_dates);
            echo implode(', ', $formatted_dates);
        ?>
    </div>
    <?php endif; ?>
  </div>
  
  <!-- Customization Form (Only visible in browser) -->
  <form method="get" class="no-print bg-light p-3 rounded mb-4">
    <input type="hidden" name="exam_id" value="<?= $exam_id ?>">
    <input type="hidden" name="date" value="<?= htmlspecialchars($dateFilter) ?>">
    
    <div class="row g-3">
      <div class="col-md-3">
        <label class="form-label">ফন্ট সাইজ</label>
        <select name="font_size" class="form-select">
          <option value="10" <?= $font_size==10?'selected':'' ?>>১০ পিক্সেল</option>
          <option value="12" <?= $font_size==12?'selected':'' ?>>১২ পিক্সেল</option>
          <option value="14" <?= $font_size==14?'selected':'' ?>>১৪ পিক্সেল</option>
          <option value="16" <?= $font_size==16?'selected':'' ?>>১৬ পিক্সেল</option>
          <option value="18" <?= $font_size==18?'selected':'' ?>>১৮ পিক্সেল</option>
          <option value="20" <?= $font_size==20?'selected':'' ?>>২০ পিক্সেল</option>
          <option value="22" <?= $font_size==22?'selected':'' ?>>২২ পিক্সেল</option>
          <option value="24" <?= $font_size==24?'selected':'' ?>>২৪ পিক্সেল</option>
          <option value="26" <?= $font_size==26?'selected':'' ?>>২৬ পিক্সেল</option>
          <option value="28" <?= $font_size==28?'selected':'' ?>>২৮ পিক্সেল</option>
          <option value="30" <?= $font_size==30?'selected':'' ?>>৩০ পিক্সেল</option>
          <option value="32" <?= $font_size==32?'selected':'' ?>>৩২ পিক্সেল</option>
          <option value="34" <?= $font_size==34?'selected':'' ?>>৩৪ পিক্সেল</option>
          <option value="36" <?= $font_size==36?'selected':'' ?>>৩৬ পিক্সেল</option>
          <option value="38" <?= $font_size==38?'selected':'' ?>>৩৮ পিক্সেল</option>
          <option value="40" <?= $font_size==40?'selected':'' ?>>৪০ পিক্সেল</option>
        </select>
        <!-- Font size slider -->
        <div class="mt-2">
          <label class="form-label">ফন্ট সাইজ বার:</label>
          <input type="range" class="form-range" min="10" max="40" step="1" value="<?= $font_size ?>" oninput="updateFontSize(this.value)" onchange="this.form.submit()">
          <div class="text-center" id="fontSizeValue"><?= $font_size ?>px</div>
        </div>
      </div>
      <div class="col-md-3">
        <label class="form-label">টেক্সট কালার</label>
        <input type="color" name="text_color" class="form-control form-control-color" value="<?= $text_color ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">ফন্ট ওজন</label>
        <select name="font_weight" class="form-select">
          <option value="normal" <?= $font_weight=='normal'?'selected':'' ?>>সাধারণ</option>
          <option value="bold" <?= $font_weight=='bold'?'selected':'' ?>>বোল্ড</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">মার্জিন (মিমি)</label>
        <input type="number" name="margin" class="form-control" value="<?php echo isset($_GET['margin']) ? (int)$_GET['margin'] : 15; ?>" min="5" max="30">
      </div>
      <!-- Header customization controls -->
      <div class="col-md-4">
        <label class="form-label">প্রতিষ্ঠানের নাম - ফন্ট সাইজ</label>
        <select name="header_font_size" class="form-select">
          <option value="16" <?= $header_font_size==16?'selected':'' ?>>১৬ পিক্সেল</option>
          <option value="18" <?= $header_font_size==18?'selected':'' ?>>১৮ পিক্সেল</option>
          <option value="20" <?= $header_font_size==20?'selected':'' ?>>২০ পিক্সেল</option>
          <option value="22" <?= $header_font_size==22?'selected':'' ?>>২২ পিক্সেল</option>
          <option value="24" <?= $header_font_size==24?'selected':'' ?>>২৪ পিক্সেল</option>
          <option value="26" <?= $header_font_size==26?'selected':'' ?>>২৬ পিক্সেল</option>
          <option value="28" <?= $header_font_size==28?'selected':'' ?>>২৮ পিক্সেল</option>
          <option value="30" <?= $header_font_size==30?'selected':'' ?>>৩০ পিক্সেল</option>
          <option value="32" <?= $header_font_size==32?'selected':'' ?>>৩২ পিক্সেল</option>
          <option value="34" <?= $header_font_size==34?'selected':'' ?>>৩৪ পিক্সেল</option>
          <option value="36" <?= $header_font_size==36?'selected':'' ?>>৩৬ পিক্সেল</option>
          <option value="38" <?= $header_font_size==38?'selected':'' ?>>৩৮ পিক্সেল</option>
          <option value="40" <?= $header_font_size==40?'selected':'' ?>>৪০ পিক্সেল</option>
          <option value="42" <?= $header_font_size==42?'selected':'' ?>>৪২ পিক্সেল</option>
          <option value="44" <?= $header_font_size==44?'selected':'' ?>>৪৪ পিক্সেল</option>
          <option value="46" <?= $header_font_size==46?'selected':'' ?>>৪৬ পিক্সেল</option>
          <option value="48" <?= $header_font_size==48?'selected':'' ?>>৪৮ পিক্সেল</option>
          <option value="50" <?= $header_font_size==50?'selected':'' ?>>৫০ পিক্সেল</option>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">প্রতিষ্ঠানের নাম - টেক্সট কালার</label>
        <input type="color" name="header_text_color" class="form-control form-control-color" value="<?= $header_text_color ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">প্রতিষ্ঠানের নাম - ফন্ট ওজন</label>
        <select name="header_font_weight" class="form-select">
          <option value="normal" <?= $header_font_weight=='normal'?'selected':'' ?>>সাধারণ</option>
          <option value="bold" <?= $header_font_weight=='bold'?'selected':'' ?>>বোল্ড</option>
        </select>
      </div>
      <!-- Selected text customization controls -->
      <div class="col-md-4">
        <label class="form-label">নির্বাচিত টেক্সট - ফন্ট সাইজ</label>
        <select name="selected_text_font_size" class="form-select">
          <?php for ($i = 10; $i <= 40; $i++): ?>
            <option value="<?= $i ?>" <?= $selected_text_font_size==$i?'selected':'' ?>><?= $i ?> পিক্সেল</option>
          <?php endfor; ?>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">নির্বাচিত টেক্সট - টেক্সট কালার</label>
        <input type="color" name="selected_text_color" class="form-control form-control-color" value="<?= $selected_text_color ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">নির্বাচিত টেক্সট - ফন্ট ওজন</label>
        <select name="selected_text_font_weight" class="form-select">
          <option value="normal" <?= $selected_text_font_weight=='normal'?'selected':'' ?>>সাধারণ</option>
          <option value="bold" <?= $selected_text_font_weight=='bold'?'selected':'' ?>>বোল্ড</option>
        </select>
      </div>
      <div class="col-12">
        <button type="submit" class="btn btn-primary"><i class="fas fa-sync"></i> আপডেট করুন</button>
        <button type="button" class="btn btn-success" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
        <button type="button" class="btn btn-info" onclick="toggleTextSelection()"><i class="fas fa-mouse-pointer"></i> টেক্সট নির্বাচন মোড</button>
        <a href="manual_room_allocation.php?exam_id=<?= $exam_id ?>&date=<?= urlencode($dateFilter) ?>" class="btn btn-secondary"><i class="fas fa-edit"></i> এডিট করুন</a>
      </div>
    </div>
  </form>
  
  <!-- Room Allocation Table -->
  <div class="card">
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-bordered align-middle mb-0 print-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: 15%">মোট সংখ্যা</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($allocations as $index => $allocation): ?>
            <tr>
              <td><?= $index + 1 ?></td>
              <td><?= htmlspecialchars($allocation['room']) ?></td>
              <td><?= htmlspecialchars($allocation['from_roll']) ?></td>
              <td><?= htmlspecialchars($allocation['to_roll']) ?></td>
              <td><?= htmlspecialchars($allocation['department']) ?></td>
              <td><?= htmlspecialchars($allocation['total']) ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  
  <!-- Signature Section -->
  <div class="mt-5">
    <div class="row">
      <div class="col-4 text-center">
        <div style="height: 100px;"></div>
        <div>________________________</div>
        <div>পরীক্ষা নিয়ন্ত্রক</div>
      </div>
      <div class="col-4 text-center">
        <div style="height: 100px;"></div>
        <div>________________________</div>
        <div>অধ্যক্ষ</div>
      </div>
      <div class="col-4 text-center">
        <div style="height: 100px;"></div>
        <div>________________________</div>
        <div>প্রধান শিক্ষক</div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Function to update font size in real-time
function updateFontSize(size) {
  // Update the displayed value
  document.getElementById('fontSizeValue').textContent = size + 'px';
  
  // Update all elements with the new font size (except header)
  const elements = document.querySelectorAll('body, h1, h2, h3, h5, h6, p, div:not(.heading h4), span, td, th, label, .print-table th, .print-table td, .institution-address');
  elements.forEach(element => {
    element.style.fontSize = size + 'px';
  });
  
  // Update the select dropdown to match the slider value
  const select = document.querySelector('select[name="font_size"]');
  if (select) {
    select.value = size;
  }
}

// Function to submit the form programmatically
function submitForm() {
  document.querySelector('form').submit();
}

// Text selection functionality for MS Word-like experience
let textSelectionMode = false;
let selectedElements = [];

function toggleTextSelection() {
    textSelectionMode = !textSelectionMode;
    const button = event.target;
    
    if (textSelectionMode) {
        button.classList.remove('btn-info');
        button.classList.add('btn-warning');
        button.innerHTML = '<i class="fas fa-mouse-pointer"></i> নির্বাচন মোড সক্রিয়';
        document.body.classList.add('selection-mode');
        showNotification('টেক্সট নির্বাচন মোড সক্রিয় হয়েছে। টেক্সট ক্লিক করে নির্বাচন করুন।');
    } else {
        button.classList.remove('btn-warning');
        button.classList.add('btn-info');
        button.innerHTML = '<i class="fas fa-mouse-pointer"></i> টেক্সট নির্বাচন মোড';
        document.body.classList.remove('selection-mode');
        clearSelection();
        showNotification('টেক্সট নির্বাচন মোড নিষ্ক্রিয় হয়েছে।');
    }
}

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);
}

function clearSelection() {
    selectedElements.forEach(el => {
        el.classList.remove('selected-for-formatting');
    });
    selectedElements = [];
}

function applySelectedTextFormatting() {
    // Get selected formatting values
    const fontSize = document.querySelector('select[name="selected_text_font_size"]').value;
    const textColor = document.querySelector('input[name="selected_text_color"]').value;
    const fontWeight = document.querySelector('select[name="selected_text_font_weight"]').value;
    
    // Apply formatting to all selected elements
    selectedElements.forEach(el => {
        el.style.fontSize = fontSize + 'px';
        el.style.color = textColor;
        el.style.fontWeight = fontWeight;
        el.classList.add('selected-text');
    });
    
    showNotification('নির্বাচিত টেক্সটে ফরম্যাটিং প্রয়োগ করা হয়েছে।');
    
    // Exit selection mode after applying formatting
    toggleTextSelection();
}

// 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();
        }
    }
});

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();
}

// 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>
</body>
</html>