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

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;
if (!$exam_id) { die('Invalid exam'); }

// Fetch exam
$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 = ?");

// Date-wise subjects from routine
$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 = ? AND es.exam_date IS NOT NULL
                           ORDER BY es.exam_date, s.name");
$sub_stmt->execute([$exam_id]);
$date_subjects_rows = $sub_stmt->fetchAll();
// Group by date with pairs
$date_subjects = [];
foreach ($date_subjects_rows as $r) {
    $date_subjects[$r['exam_date']][] = [$r['subject_bn'], $r['subject_en']];
}
$stmt->execute([$exam_id]);
$exam = $stmt->fetch();
if (!$exam) { die('Exam not found'); }

// Fetch grouped duties
$stmt = $pdo->prepare("SELECT d.id, d.room_id, d.teacher_id, d.duty_role, d.duty_date, d.start_time, d.end_time, d.order_index, d.remarks,
                              r.room_name, r.capacity, r.max_teachers,
                              t.first_name, t.last_name, t.employee_id, t.designation, t.photo
                       FROM exam_room_duties d
                       JOIN exam_rooms r ON d.room_id = r.id
                       JOIN teachers t ON d.teacher_id = t.id
                       WHERE d.exam_id = :exam_id AND (:date IS NULL OR d.duty_date = :date2)
                       ORDER BY r.room_name, d.room_id, d.order_index, d.id");
$dateFilter = isset($_GET['date']) && $_GET['date'] !== '' ? $_GET['date'] : null;
$stmt->bindValue(':exam_id', $exam_id, PDO::PARAM_INT);
$stmt->bindValue(':date', $dateFilter, $dateFilter ? PDO::PARAM_STR : PDO::PARAM_NULL);
$stmt->bindValue(':date2', $dateFilter, $dateFilter ? PDO::PARAM_STR : PDO::PARAM_NULL);
$stmt->execute();
$rows = $stmt->fetchAll();

$grouped = [];
foreach ($rows as $r) { $grouped[$r['room_name']][] = $r; }
$roleMap = ['invigilator' => 'মূল', 'assistant' => 'সহকারী', 'reserve' => 'রিজার্ভ'];
?>
<!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.1.3/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; }
    .heading h4 { font-weight: 600; }
    .signature-cell { height: 40px; }
    .name-wide { min-width: 160px; }
    .teacher-name { font-weight: 700 !important; font-size: 1.25rem !important; }
    .sign-wide { min-width: 140px; }
    /* Column widths (screen) */
    .duty-table th:nth-child(2), .duty-table td:nth-child(2) { width: 32%; white-space: nowrap; }
    .duty-table th:nth-child(4), .duty-table td:nth-child(4) { width: 28%; white-space: nowrap; }
    .duty-table th:nth-child(6), .duty-table td:nth-child(6) { width: 18%; }
    @page { size: A4; margin: <?php echo isset($_GET['margin']) ? (int)$_GET['margin'] : 8; ?>mm; }
    @media print {
      .no-print { display: none !important; }
      body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
      .container { max-width: 100% !important; width: 100% !important; margin: 0 !important; padding: 0 6mm !important; }
      .card { box-shadow: none !important; }
      .table-responsive { overflow: visible !important; }
      .teacher-name { font-size: 1.45rem !important; font-weight: 700 !important; }
      /* Print widths */
      .duty-table th:nth-child(2), .duty-table td:nth-child(2) { width: 34% !important; white-space: nowrap !important; }
      .duty-table th:nth-child(4), .duty-table td:nth-child(4) { width: 30% !important; white-space: nowrap !important; }
      .duty-table th:nth-child(6), .duty-table td:nth-child(6) { width: 14% !important; }
    }
  </style>
</head>
<body class="bg-white">
  <div class="container my-4">
    <div class="mb-3 text-center">
      <div class="heading">
        <?php if ($logo_image): ?>
        <div class="text-center mb-3">
            <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" class="img-fluid" style="max-height: <?php echo $logo_size; ?>px; opacity: <?php echo $logo_opacity; ?>; max-width: 200px; object-fit: contain;">
        </div>
        <?php endif; ?>
        <h4 class="mb-1"><?php echo htmlspecialchars($site_name); ?></h4>
        <div class="text-muted"><?php echo htmlspecialchars($site_address); ?></div>
        <h4 class="mb-1 mt-2">রুম ভিত্তিক ডিউটি</h4>
        <div class="text-muted">পরীক্ষা: <?php echo htmlspecialchars($exam['name']); ?></div>
        <div class="text-muted">শ্রেণী: <?php echo htmlspecialchars(($exam['class_name'] ?? '') . ($exam['section'] ? ' - '.$exam['section'] : '')); ?></div>
      </div>
      <form method="get" class="no-print d-flex justify-content-center align-items-end gap-2 my-2">
        <input type="hidden" name="exam_id" value="<?php echo (int)$exam_id; ?>">
        <div>
          <label class="form-label mb-1">তারিখ নির্বাচন</label>
          <select name="date" class="form-select" required>
            <option value="">নির্বাচন করুন</option>
            <?php foreach (array_keys($date_subjects) as $d): ?>
              <option value="<?php echo htmlspecialchars($d); ?>" <?php echo (isset($_GET['date']) && $_GET['date']===$d) ? 'selected' : ''; ?>><?php echo htmlspecialchars($d); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div>
          <label class="form-label mb-1">মার্জিন (মিমি)</label>
          <input type="number" name="margin" class="form-control" value="<?php echo isset($_GET['margin']) ? (int)$_GET['margin'] : 8; ?>" min="0" max="25">
        </div>
        <div>
          <button class="btn btn-primary">লোড করুন</button>
        </div>
      </form>
      <?php if (!empty($_GET['date']) && isset($date_subjects[$_GET['date']])): ?>
        <div class="text-muted small">
          <div>
            <?php $pairs = array_map(function($p){ return $p[0] . ' (' . $p[1] . ')'; }, $date_subjects[$_GET['date']]); ?>
            <strong><?php echo htmlspecialchars($_GET['date']); ?>:</strong> <?php echo htmlspecialchars(implode(', ', $pairs)); ?>
          </div>
        </div>
      <?php elseif (!empty($date_subjects)): ?>
        <div class="text-muted small">একটি তারিখ নির্বাচন করুন প্রিন্টের জন্য।</div>
      <?php endif; ?>
      <div class="no-print mt-2">
        <a href="room_duty.php?exam_id=<?php echo (int)$exam_id; ?>" class="btn btn-secondary">পিছনে</a>
        <a href="manual_room_allocation.php?exam_id=<?php echo (int)$exam_id; ?>&date=<?php echo urlencode($_GET['date'] ?? ''); ?>" class="btn btn-success">ম্যানুয়াল রুম বন্টন</a>
        <button onclick="window.print()" class="btn btn-primary" <?php echo empty($_GET['date']) ? 'disabled' : ''; ?>>প্রিন্ট</button>
      </div>    </div>

    <?php if (empty($grouped)): ?>
        <div class="alert alert-info">কোনো ডিউটি নেই</div>
    <?php else: ?>
        <?php foreach ($grouped as $room => $list): ?>
            <div class="card mb-3">
              <div class="card-header"><strong>রুম: <?php echo htmlspecialchars($room); ?></strong></div>
              <div class="card-body p-0">
                <div class="table-responsive">
                  <table class="table table-bordered mb-0 align-middle duty-table">
                    <thead class="table-light">
                      <tr>
                        <th>ক্রঃ</th>
                        <th class="name-wide">শিক্ষক</th>
                        <th>আইডি</th>
                        <th>পদবি</th>
                        <th>উপস্থিতির সময়</th>
                        <th class="sign-wide">শিক্ষকের স্বাক্ষর</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php $i=1; foreach ($list as $d): ?>
                        <tr>
                          <td><?php echo $i++; ?></td>
                          <td>
                            <?php
                              $photo = !empty($d['photo']) ? $d['photo'] : '';
                              $imgSrc = $photo ? (strpos($photo, 'http')===0 ? $photo : '../'.$photo) : '../uploads/teachers/T001.png';
                            ?>
                            <img src="<?php echo htmlspecialchars($imgSrc); ?>" alt="photo" style="width:26px;height:26px;border-radius:50%;object-fit:cover;border:1px solid #ccc;" class="me-1">
                            <span class="teacher-name"><?php echo htmlspecialchars(trim($d['first_name'].' '.$d['last_name'])); ?></span>
                          </td>
                          <td><?php echo htmlspecialchars($d['employee_id']); ?></td>
                          <td><?php echo htmlspecialchars($d['designation'] ?? ''); ?></td>
                          <td style="height:40px">&nbsp;</td>
                          <td class="signature-cell">&nbsp;</td>
                        </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
  </div>
</body>
</html>