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

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

// Load sessions (academic sessions from exams table)
$sessions = $pdo->query("SELECT DISTINCT session FROM exams WHERE session IS NOT NULL AND session <> '' ORDER BY session DESC")->fetchAll(PDO::FETCH_COLUMN);

// Inputs
$selected_session = isset($_GET['session']) ? trim($_GET['session']) : '';
$selected_exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : 0;

// Exams for session
$exams = [];
if ($selected_session !== '') {
    $stmt = $pdo->prepare("SELECT id, name, class_id, session, group_name, created_at FROM exams WHERE session = ? ORDER BY created_at DESC");
    $stmt->execute([$selected_session]);
    $exams = $stmt->fetchAll();
}

// Fetch exam details
$exam = null;
if ($selected_exam_id) {
    $stmt = $pdo->prepare("SELECT e.*, c.name AS class_name, c.section AS class_section FROM exams e LEFT JOIN classes c ON e.class_id = c.id WHERE e.id = ?");
    $stmt->execute([$selected_exam_id]);
    $exam = $stmt->fetch();
}

// Fetch teacher-wise duties for the exam
$dutiesByTeacher = [];
if ($selected_exam_id) {
    $stmt = $pdo->prepare("\n        SELECT d.id, d.exam_id, d.room_id, d.teacher_id, d.duty_role, d.duty_date, d.start_time, d.end_time, d.remarks,\n               r.room_name, r.building, r.floor,\n               t.first_name, t.last_name, t.designation, t.employee_id, t.photo\n        FROM exam_room_duties d\n        LEFT JOIN exam_rooms r ON d.room_id = r.id\n        JOIN teachers t ON d.teacher_id = t.id\n        WHERE d.exam_id = ?\n        ORDER BY t.first_name, t.last_name, d.duty_date, d.start_time, d.id\n    ");
    $stmt->execute([$selected_exam_id]);
    $rows = $stmt->fetchAll();
    foreach ($rows as $r) {
        $tid = (int)$r['teacher_id'];
        if (!isset($dutiesByTeacher[$tid])) $dutiesByTeacher[$tid] = [
            'teacher_id' => $tid,
            'teacher_name' => trim(($r['first_name'] ?? '') . ' ' . ($r['last_name'] ?? '')),
            'designation' => $r['designation'] ?? '',
            'employee_id' => $r['employee_id'] ?? '',
            'photo' => $r['photo'] ?? '',
            'duties' => []
        ];
        $dutiesByTeacher[$tid]['duties'][] = $r;
    }
}

// Load school settings for header
$school_name = 'আমাদের স্কুল';
$school_address = '';
try {
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
    $rows = $stmt->fetchAll();
    $map = [];
    foreach ($rows as $row) { $map[$row['setting_key']] = $row['setting_value']; }
    if (!empty($map['school_name'])) $school_name = $map['school_name'];
    if (!empty($map['school_address'])) $school_address = $map['school_address'];
} catch (Exception $e) {
    // ignore if settings not present
}

// Try to auto-detect a logo file (optional)
$school_logo = '';
$logoCandidates = glob(__DIR__ . '/../uploads/temp/seat_cards/logo_*.*');
if ($logoCandidates) {
    usort($logoCandidates, function($a,$b){ return filemtime($b) <=> filemtime($a); });
    $latest = $logoCandidates[0];
    // Convert to web path relative to this file
    $school_logo = '../uploads/temp/seat_cards/' . basename($latest);
}

?>
<!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://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/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; }
    :root { --letter-gap: 10mm; } /* Customize this to change gap between two letters */
    @page { size: A4; margin: 12mm; }
    @media print {
      .no-print { display: none !important; }
      .card { box-shadow: none !important; border: none !important; margin-bottom: 0 !important; }
      .page-break { page-break-after: always; }
      .print-letter { page-break-inside: avoid; break-inside: avoid; page-break-after: always; }
      .print-letter:last-of-type { page-break-after: auto; }
      .container, .container-fluid { padding: 0 !important; }
    }
    .teacher-header { border-bottom: 1px dashed #ccc; margin-bottom: 8px; padding-bottom: 6px; }
    .teacher-photo { width: 48px; height: 48px; object-fit: cover; border:1px solid #ddd; border-radius: 50%; }
    .school-logo { width: 70px; height: 70px; object-fit: contain; }
    .letter-title { font-size: 1.1rem; font-weight: 600; }
    .teacher-name { font-size: 1.25rem; font-weight: 700; }
    .signature-line { margin-top: 32px; margin-bottom: 4px; }
    /* Ensure date cells can wrap into multiple lines within the same row */
    .duty-letter-table th { white-space: nowrap; }
    .duty-letter-table td { white-space: normal; overflow-wrap: anywhere; word-break: break-word; line-height: 1.5; }
  </style>
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
    <div class="container-fluid">
      <a class="navbar-brand" href="../index.php">
        <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
      </a>
      <div class="navbar-nav ms-auto">
        <a class="nav-link" href="room_duty.php"><i class="fas fa-door-open"></i> রুম ডিউটি</a>
        <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
      </div>
    </div>
  </nav>

  <div class="container-fluid mt-4">
    <div class="row mb-3 no-print">
      <div class="col-12">
        <div class="card">
          <div class="card-header"><strong><i class="fas fa-print"></i> শিক্ষক-ভিত্তিক ডিউটি লেটার</strong></div>
          <div class="card-body">
            <form method="get" class="row g-2 align-items-end">
              <div class="col-md-3">
                <label class="form-label">সেশন</label>
                <select name="session" class="form-select" onchange="this.form.submit()" required>
                  <option value="">নির্বাচন করুন</option>
                  <?php foreach ($sessions as $s): ?>
                    <option value="<?php echo htmlspecialchars($s); ?>" <?php echo ($selected_session === $s) ? 'selected' : ''; ?>><?php echo htmlspecialchars($s); ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="col-md-5">
                <label class="form-label">পরীক্ষা</label>
                <select name="exam_id" class="form-select" <?php echo $selected_session === '' ? 'disabled' : ''; ?> required>
                  <option value="">নির্বাচন করুন</option>
                  <?php foreach ($exams as $ex): ?>
                    <option value="<?php echo (int)$ex['id']; ?>" <?php echo ($selected_exam_id == (int)$ex['id']) ? 'selected' : ''; ?>>
                      <?php echo htmlspecialchars($ex['name']); ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="col-md-2">
                <button class="btn btn-primary w-100"><i class="fas fa-search"></i> দেখুন</button>
              </div>
              <div class="col-md-2 text-end">
                <?php if ($selected_exam_id): ?>
                  <button type="button" class="btn btn-outline-secondary w-100" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট</button>
                <?php endif; ?>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <?php if ($selected_exam_id && $exam): ?>
      <div class="row mb-3 no-print">
        <div class="col-12">
          <div class="alert alert-info">
            <strong>পরীক্ষা:</strong> <?php echo htmlspecialchars($exam['name']); ?>
            <?php if (!empty($exam['class_name'])): ?>
              <span class="ms-2"><strong>ক্লাস:</strong> <?php echo htmlspecialchars($exam['class_name']); ?><?php echo $exam['class_section'] ? ' - '.htmlspecialchars($exam['class_section']) : ''; ?></span>
            <?php endif; ?>
            <?php if (!empty($exam['session'])): ?>
              <span class="ms-2"><strong>সেশন:</strong> <?php echo htmlspecialchars($exam['session']); ?></span>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <?php if (empty($dutiesByTeacher)): ?>
        <div class="alert alert-warning">এই পরীক্ষায় কোনো ডিউটি অ্যাসাইন করা হয়নি।</div>
      <?php else: ?>
        <?php foreach ($dutiesByTeacher as $t): ?>
          <div class="card mb-4 print-letter">
            <div class="card-body">
              <!-- Letter Header: Logo + School Info -->
              <div class="mb-3 text-center">
                <div class="d-flex justify-content-center align-items-center mb-2">
                  <?php if (!empty($school_logo)): ?>
                    <img src="<?php echo htmlspecialchars($school_logo); ?>" alt="Logo" class="school-logo me-2">
                  <?php endif; ?>
                  <div>
                    <div class="h5 mb-1"><?php echo htmlspecialchars($school_name); ?></div>
                    <?php if (!empty($school_address)): ?><div class="text-muted small"><?php echo nl2br(htmlspecialchars($school_address)); ?></div><?php endif; ?>
                  </div>
                </div>
                <div class="small text-muted">
                  <?php if (!empty($exam['name'])): ?>পরীক্ষা: <?php echo htmlspecialchars($exam['name']); ?><?php endif; ?>
                  <?php if (!empty($exam['session'])): ?> | সেশন: <?php echo htmlspecialchars($exam['session']); ?><?php endif; ?>
                </div>
              </div>

              <!-- Letter Body -->
              <div class="mb-3">
                <div class="letter-title">কক্ষপরিদর্শকের দায়িত্ব প্রসঙ্গে</div>
                <p class="mb-1 teacher-name">
                  <?php echo htmlspecialchars($t['teacher_name']); ?><?php if (!empty($t['designation'])): ?>, <?php echo htmlspecialchars($t['designation']); ?><?php endif; ?>
                </p>
                <p class="mb-0">
                  এই মর্মে অবগত করা যাচ্ছে যে উপরে উল্লিখিত শিক্ষক মহোদয়/মহোদয়া-কে নিম্ন তালিকায় উল্লেখিত তারিখগুলোতে পরীক্ষার হলে কক্ষপরিদর্শকের দায়িত্ব প্রদান করা হলো। পরীক্ষা শুরুর ৩০ (ত্রিশ) মিনিট পূর্বে পরীক্ষা কন্ট্রোল রুমে উপস্থিত থাকার জন্য অনুরোধ করা হলো।
                </p>
              </div>

              <!-- Teacher header removed as per letter format -->

              <div class="table-responsive">
                <?php
                  // Aggregate dates into morning/afternoon lists (unique, comma-separated)
                  $morningDates = [];
                  $afternoonDates = [];
                  $toMin = function($time) {
                    if (!$time) return null;
                    $parts = explode(':', $time);
                    $h = (int)($parts[0] ?? 0);
                    $m = (int)($parts[1] ?? 0);
                    return $h*60 + $m;
                  };
                  $morningStart = 9*60;  // 09:00
                  $morningEnd   = 14*60; // 14:00 (covers up to 2pm)

                  foreach ($t['duties'] as $d) {
                    $st = $d['start_time'] ?? null;
                    $et = $d['end_time'] ?? null;
                    $sm = $toMin($st);
                    $em = $toMin($et);
                    $isMorning = false;
                    if ($sm !== null && $em !== null) {
                      $isMorning = ($sm >= $morningStart && $em <= $morningEnd);
                    } elseif ($sm !== null) {
                      $isMorning = ($sm >= $morningStart && $sm <= $morningEnd);
                    } elseif ($em !== null) {
                      $isMorning = ($em <= $morningEnd);
                    }
                    $dateStr = trim((string)$d['duty_date']);
                    if ($dateStr !== '') {
                      if ($isMorning) $morningDates[] = $dateStr; else $afternoonDates[] = $dateStr;
                    }
                  }

                  // Make unique and sort for stable output
                  $morningDates = array_values(array_unique($morningDates));
                  $afternoonDates = array_values(array_unique($afternoonDates));
                  sort($morningDates);
                  sort($afternoonDates);

                  $morningText = htmlspecialchars(implode(', ', $morningDates));
                  $afternoonText = htmlspecialchars(implode(', ', $afternoonDates));
                ?>
                <table class="table table-sm table-bordered align-middle mb-0 duty-letter-table">
                  <thead class="table-light text-center">
                    <tr>
                      <th style="width: 50%;">তারিখ (সকাল)</th>
                      <th style="width: 50%;">তারিখ (বিকাল)</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td class="text-center"><?php echo $morningText; ?></td>
                      <td class="text-center"><?php echo $afternoonText; ?></td>
                    </tr>
                  </tbody>
                </table>
              </div>

              <!-- Signature section -->
              <div class="mt-4">
                <div class="row text-center">
                  <div class="col-4">
                    <div class="signature-line">______________________</div>
                    <div class="small">আহ্বায়ক, পরীক্ষা কমিটি</div>
                  </div>
                  <div class="col-4">
                    <div class="signature-line">______________________</div>
                    <div class="small">সদস্য, পরীক্ষা কমিটি</div>
                  </div>
                  <div class="col-4">
                    <div class="signature-line">______________________</div>
                    <div class="small">সদস্য, পরীক্ষা কমিটি</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    <?php endif; ?>
  </div>

  <script>
    // Auto submit exam select when session already chosen and exam changes
    // (Form submit button still available)
  </script>
</body>
</html>