<?php
// Filename: public_relief.php
require 'config.php';

// NOTE: No requireLogin() here. This is a public page.

// 1. GET DATE
$date = $_GET['date'] ?? date('Y-m-d');
$day_num = date('N', strtotime($date));

// 2. FETCH SETTINGS
$s_name = getSetting('school_name', 'SMK Muadzam Shah');
$start_time_str = getSetting('start_time', '07:30');
$slot_dur = intval(getSetting('slot_duration', 30));
$start_ts = strtotime($start_time_str);

// 3. FETCH SUBJECT CODES (For Compact Display)
$sub_map = $pdo->query("SELECT subject_name, subject_code FROM subjects")->fetchAll(PDO::FETCH_KEY_PAIR);

// 4. FETCH DATA
$sql = "
    SELECT 
        u_orig.full_name as absent_name,
        ta.reason,
        t.start_time,
        t.subject,
        c.class_name,
        u_rel.full_name as reliever_name
    FROM relief_assignments ra
    JOIN timetable t ON ra.timetable_id = t.id
    JOIN classes c ON t.class_id = c.id
    JOIN users u_orig ON t.teacher_id = u_orig.id
    LEFT JOIN users u_rel ON ra.reliever_id = u_rel.id
    LEFT JOIN teacher_absences ta ON t.teacher_id = ta.user_id AND ta.absence_date = ra.assignment_date
    WHERE ra.assignment_date = ?
    ORDER BY u_orig.full_name ASC, t.start_time ASC
";

$stmt = $pdo->prepare($sql);
$stmt->execute([$date]);
$rows = $stmt->fetchAll();

// 5. GROUP DATA BY ABSENT TEACHER
$grouped = [];
foreach ($rows as $r) {
    $grouped[$r['absent_name']][] = $r;
}

$absent_teachers_list = array_keys($grouped);

// Helper: Calculate Period Number
function getPeriodNumber($time, $start_ts, $dur) {
    $current_ts = strtotime($time);
    $diff_mins = ($current_ts - $start_ts) / 60;
    return floor($diff_mins / $dur) + 1;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Substitution - <?= date('d.m.Y', strtotime($date)) ?></title>
    <style>
        body { 
            font-family: 'Arial', sans-serif; 
            background: #e0e0e0; 
            margin: 0; padding: 20px;
            color: #000;
        }
        .sheet {
            background: white;
            max-width: 210mm; /* A4 Width */
            margin: 0 auto;
            padding: 15mm;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            min-height: 297mm; /* A4 Height */
            box-sizing: border-box;
        }
        
        /* HEADER */
        .header { text-align: center; margin-bottom: 20px; }
        .title { font-size: 24px; font-weight: bold; margin-bottom: 5px; text-transform: uppercase; letter-spacing: 1px; }
        .subtitle { font-size: 14px; margin-bottom: 15px; border-bottom: 2px solid #000; display: inline-block; padding-bottom: 5px; }
        .summary-text { font-size: 12px; font-style: italic; margin-bottom: 5px; color: #444; }
        .summary-list { 
            font-size: 11px; font-weight: bold; text-transform: uppercase; margin-bottom: 25px; 
            line-height: 1.5; word-wrap: break-word;
        }

        /* TABLE */
        table { 
            width: 100%; 
            border-collapse: collapse; 
            font-size: 11px; 
            table-layout: fixed; /* Forces cells to respect widths and wrap text */
        }
        
        th { 
            background-color: #f0f0f0; 
            border-top: 2px solid #000; 
            border-bottom: 2px solid #000; 
            padding: 8px 4px; 
            text-align: left;
            white-space: nowrap; 
        }
        
        td { 
            padding: 6px 4px; 
            border-bottom: 1px solid #ddd; 
            vertical-align: top; 
            word-wrap: break-word; /* Crucial for long names */
            overflow-wrap: break-word;
        }
        
        /* Specific Column Styles (Total 100%) */
        .col-absent { width: 22%; font-weight: bold; text-transform: uppercase; background-color: #f9f9f9; border-right: 1px solid #eee; font-size: 10px; }
        .col-period { width: 5%; text-align: center; font-weight: bold; }
        .col-reason { width: 10%; text-align: center; text-transform: uppercase; font-size: 9px; color: #555; }
        .col-subject { width: 8%; text-align: center; text-transform: uppercase; font-weight: bold; }
        .col-class { width: 10%; font-weight: bold; text-align: center; font-size: 11px; }
        .col-sub { width: 25%; font-weight: bold; text-transform: uppercase; font-size: 10px; }
        .col-note { width: 10%; font-style: italic; color: #777; font-size: 9px; text-align: right; }

        /* PRINT BUTTON */
        .no-print { text-align: center; margin-bottom: 20px; }
        .btn { 
            padding: 10px 20px; background: #333; color: white; text-decoration: none; 
            border-radius: 5px; font-weight: bold; cursor: pointer; border: none;
            display: inline-block; margin: 0 5px;
        }
        .btn:hover { background: #000; }
        .btn-blue { background: #0d6efd; } .btn-blue:hover { background: #0b5ed7; }
        
        .footer {
            margin-top: 40px; border-top: 1px solid #000; padding-top: 5px;
            font-size: 9px; display: flex; justify-content: space-between; color: #555;
        }

        /* PRINT MEDIA QUERY */
        @media print {
            body { background: white; padding: 0; margin: 0; }
            .sheet { box-shadow: none; margin: 0; width: 100%; max-width: 100%; padding: 10mm; border: none; }
            .no-print { display: none; }
            @page { margin: 0; size: A4 portrait; }
        }
    </style>
</head>
<body>

    <div class="no-print">
        <form method="GET" style="display:inline-block; margin-right:10px;">
            <input type="date" name="date" value="<?= $date ?>" style="padding:9px; border:1px solid #ccc; border-radius:4px;">
            <button class="btn btn-blue">Change Date</button>
        </form>
        <button onclick="window.print()" class="btn">🖨️ Print / PDF</button>
    </div>

    <div class="sheet">
        
        <div class="header">
            <div class="title">Substitution</div>
            <div class="subtitle"><?= date('l, d.m.Y', strtotime($date)) ?></div>
            
            <?php if(empty($grouped)): ?>
                <div style="margin-top: 50px; color: #666; font-style: italic;">
                    No relief assignments recorded for today.
                </div>
            <?php else: ?>
                <div class="summary-text">Teachers absent today:</div>
                <div class="summary-list">
                    <?= implode(', ', array_map('strtoupper', $absent_teachers_list)) ?>
                </div>
            <?php endif; ?>
        </div>

        <?php if(!empty($grouped)): ?>
        <table>
            <thead>
                <tr>
                    <th class="col-absent">Absent</th>
                    <th class="col-period">Per</th>
                    <th class="col-reason">Reason</th>
                    <th class="col-subject">Subj</th>
                    <th class="col-class">Class</th>
                    <th class="col-sub">Substitute</th>
                    <th class="col-note">Note</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($grouped as $teacher_name => $classes): ?>
                    <?php 
                    $row_count = count($classes);
                    foreach($classes as $index => $row): 
                        $period = getPeriodNumber($row['start_time'], $start_ts, $slot_dur);
                        // Use Short Code if available, else full name
                        $subj_display = $sub_map[$row['subject']] ?? $row['subject'];
                    ?>
                    <tr>
                        <?php if($index === 0): ?>
                            <td class="col-absent" rowspan="<?= $row_count ?>">
                                <?= strtoupper($teacher_name) ?>
                            </td>
                        <?php endif; ?>

                        <td class="col-period"><?= $period ?></td>
                        <td class="col-reason"><?= strtoupper($row['reason'] ?? '-') ?></td>
                        <td class="col-subject"><?= strtoupper($subj_display) ?></td>
                        <td class="col-class"><?= strtoupper($row['class_name']) ?></td>
                        <td class="col-sub">
                            <?php if($row['reliever_name']): ?>
                                <?= strtoupper($row['reliever_name']) ?>
                            <?php else: ?>
                                <span style="color:#dc3545; font-size:10px;">(PENDING)</span>
                            <?php endif; ?>
                        </td>
                        <td class="col-note">RELIEF</td>
                    </tr>
                    <?php endforeach; ?>
                    <tr><td colspan="7" style="height: 10px; border: none;"></td></tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>

        <div class="footer">
            <div>System Generated</div>
            <div><?= htmlspecialchars($s_name) ?></div>
            <div>Printed: <?= date('d.m.Y H:i') ?></div>
        </div>

    </div>

</body>
</html>