<?php
session_start();
if(!isset($_SESSION['username'])){
    die('Unauthorized');
}

require_once 'includes/database.php';
require_once 'Classes/Timetable.php';
$timetable = new Timetable();

// Get parameters
$type = isset($_GET['type']) ? $_GET['type'] : 'class'; // 'class' or 'teacher'
$format = isset($_GET['format']) ? $_GET['format'] : 'excel'; // 'excel' or 'pdf'
$classId = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
$sectionId = isset($_GET['section_id']) ? (int)$_GET['section_id'] : 0;
$teacherId = isset($_GET['teacher_id']) ? (int)$_GET['teacher_id'] : 0;
$academicYear = isset($_GET['academic_year']) ? $_GET['academic_year'] : '';
$term = isset($_GET['term']) ? $_GET['term'] : '';

if($type === 'class' && (!$classId || !$sectionId)) {
    die('Invalid parameters');
}

if($type === 'teacher' && !$teacherId) {
    die('Invalid teacher parameter');
}

// Get data based on type
if($type === 'class') {
    // Get class info
    $sql = "SELECT c.name as class_name, s.name as section_name
            FROM classes c, sections s
            WHERE c.id = :class_id AND s.id = :section_id";
    $timetable->query($sql);
    $timetable->bind(':class_id', $classId);
    $timetable->bind(':section_id', $sectionId);
    $info = $timetable->fetchSingle();

    $title = $info->class_name . ' - ' . $info->section_name;
    $entries = $timetable->getClassTimetable($classId, $sectionId, $academicYear, $term);
} else {
    // Get teacher info
    $sql = "SELECT name, email FROM teachers WHERE id = :teacher_id";
    $timetable->query($sql);
    $timetable->bind(':teacher_id', $teacherId);
    $info = $timetable->fetchSingle();

    $title = 'Teacher: ' . $info->name;
    $entries = $timetable->getTeacherTimetable($teacherId, $academicYear, $term);
}

// Get active days
$days = $timetable->getActiveDays();

// Get all periods
$periods = $timetable->getAllPeriods();

// Get school info
$sql = "SELECT school_name FROM general_settings LIMIT 1";
$timetable->query($sql);
$schoolInfo = $timetable->fetchSingle();
$schoolName = $schoolInfo->school_name ?? 'School';

if($format === 'excel') {
    exportToExcel($schoolName, $title, $days, $periods, $entries, $type, $academicYear, $term);
} else {
    exportToPDF($schoolName, $title, $days, $periods, $entries, $type, $academicYear, $term);
}

function exportToExcel($schoolName, $title, $days, $periods, $entries, $type, $academicYear, $term) {
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=timetable_" . date('Y-m-d_His') . ".xls");
    header("Pragma: no-cache");
    header("Expires: 0");

    echo '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
    echo '<head>';
    echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
    echo '<style>';
    echo 'table { border-collapse: collapse; width: 100%; }';
    echo 'th, td { border: 1px solid #000; padding: 8px; text-align: left; }';
    echo 'th { background-color: #4472C4; color: white; font-weight: bold; text-align: center; }';
    echo '.header { background-color: #f2f2f2; font-weight: bold; padding: 10px; margin-bottom: 20px; }';
    echo '.period-cell { background-color: #E7E6E6; font-weight: bold; text-align: center; }';
    echo '.break-cell { background-color: #FFF2CC; font-style: italic; text-align: center; }';
    echo '.empty-cell { text-align: center; color: #999; }';
    echo '</style>';
    echo '</head>';
    echo '<body>';

    // Header
    echo '<div class="header">';
    echo '<h1>' . htmlspecialchars($schoolName) . '</h1>';
    echo '<h2>Timetable: ' . htmlspecialchars($title) . '</h2>';
    if($academicYear) echo '<p>Academic Year: ' . htmlspecialchars($academicYear) . '</p>';
    if($term) echo '<p>Term: ' . htmlspecialchars($term) . '</p>';
    echo '<p>Generated on: ' . date('F d, Y h:i A') . '</p>';
    echo '</div>';

    // Timetable table
    echo '<table>';
    echo '<thead><tr>';
    echo '<th>Period / Day</th>';
    foreach($days as $day) {
        echo '<th>' . htmlspecialchars($day->day_name) . '</th>';
    }
    echo '</tr></thead>';
    echo '<tbody>';

    foreach($periods as $period) {
        if($period->is_break == 1) {
            echo '<tr>';
            echo '<td class="break-cell" colspan="' . (count($days) + 1) . '">';
            echo htmlspecialchars($period->period_name) . ' (' . date('h:i A', strtotime($period->start_time)) . ' - ' . date('h:i A', strtotime($period->end_time)) . ')';
            echo '</td>';
            echo '</tr>';
        } else {
            echo '<tr>';
            echo '<td class="period-cell">';
            echo '<strong>' . htmlspecialchars($period->period_name) . '</strong><br>';
            echo date('h:i A', strtotime($period->start_time)) . ' - ' . date('h:i A', strtotime($period->end_time));
            echo '</td>';

            foreach($days as $day) {
                $entry = null;
                if($entries) {
                    foreach($entries as $e) {
                        if($e->day_id == $day->id && $e->period_id == $period->id) {
                            $entry = $e;
                            break;
                        }
                    }
                }

                echo '<td>';
                if($entry) {
                    if($type === 'class') {
                        echo '<strong>' . htmlspecialchars($entry->subject_name) . '</strong><br>';
                        echo htmlspecialchars($entry->teacher_name);
                        if($entry->room_number) echo '<br>Room: ' . htmlspecialchars($entry->room_number);
                    } else {
                        echo '<strong>' . htmlspecialchars($entry->class_name) . ' - ' . htmlspecialchars($entry->section_name) . '</strong><br>';
                        echo htmlspecialchars($entry->subject_name);
                        if($entry->room_number) echo '<br>Room: ' . htmlspecialchars($entry->room_number);
                    }
                } else {
                    echo '<span class="empty-cell">-</span>';
                }
                echo '</td>';
            }

            echo '</tr>';
        }
    }

    echo '</tbody>';
    echo '</table>';

    echo '<p style="margin-top: 30px; font-size: 11px; color: #666;">Generated by ' . htmlspecialchars($schoolName) . ' Timetable System</p>';

    echo '</body>';
    echo '</html>';
}

function exportToPDF($schoolName, $title, $days, $periods, $entries, $type, $academicYear, $term) {
    // For PDF, we'll create a print-friendly HTML page that opens in a new window
    // and user can print or save as PDF
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Timetable - <?php echo htmlspecialchars($title); ?></title>
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: Arial, sans-serif; padding: 20px; }
            .header { text-align: center; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 3px solid #333; }
            .header h1 { font-size: 24px; margin-bottom: 10px; }
            .header h2 { font-size: 18px; color: #666; margin-bottom: 10px; }
            .info { font-size: 12px; color: #555; }
            table { width: 100%; border-collapse: collapse; margin-top: 20px; }
            th, td { border: 1px solid #333; padding: 8px; text-align: center; font-size: 11px; }
            th { background: #4472C4; color: white; font-weight: bold; }
            .period-cell { background: #E7E6E6; font-weight: bold; }
            .break-cell { background: #FFF2CC; font-style: italic; }
            .entry { text-align: left; padding: 5px; }
            .entry strong { display: block; margin-bottom: 3px; color: #2c5282; }
            .entry small { font-size: 10px; color: #666; }
            .footer { margin-top: 30px; text-align: center; font-size: 10px; color: #666; }
            @media print {
                body { padding: 10px; }
                .no-print { display: none !important; }
                @page { margin: 15mm; }
            }
            .print-btn {
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 10px 20px;
                background: #007bff;
                color: white;
                border: none;
                border-radius: 5px;
                cursor: pointer;
                z-index: 1000;
            }
        </style>
    </head>
    <body>
    <button onclick="window.print()" class="print-btn no-print">🖨️ Print / Save as PDF</button>

    <div class="header">
        <h1><?php echo htmlspecialchars($schoolName); ?></h1>
        <h2>Timetable: <?php echo htmlspecialchars($title); ?></h2>
        <div class="info">
            <?php if($academicYear): ?>
                <p>Academic Year: <?php echo htmlspecialchars($academicYear); ?></p>
            <?php endif; ?>
            <?php if($term): ?>
                <p>Term: <?php echo htmlspecialchars($term); ?></p>
            <?php endif; ?>
            <p>Generated on: <?php echo date('F d, Y h:i A'); ?></p>
        </div>
    </div>

    <table>
        <thead>
        <tr>
            <th style="width: 100px;">Period / Day</th>
            <?php foreach($days as $day): ?>
                <th><?php echo htmlspecialchars($day->day_name); ?></th>
            <?php endforeach; ?>
        </tr>
        </thead>
        <tbody>
        <?php foreach($periods as $period): ?>
            <?php if($period->is_break == 1): ?>
                <tr>
                    <td class="break-cell" colspan="<?php echo count($days) + 1; ?>">
                        <?php echo htmlspecialchars($period->period_name); ?>
                        (<?php echo date('h:i A', strtotime($period->start_time)); ?> -
                        <?php echo date('h:i A', strtotime($period->end_time)); ?>)
                    </td>
                </tr>
            <?php else: ?>
                <tr>
                    <td class="period-cell">
                        <strong><?php echo htmlspecialchars($period->period_name); ?></strong><br>
                        <small><?php echo date('h:i A', strtotime($period->start_time)); ?> -
                            <?php echo date('h:i A', strtotime($period->end_time)); ?></small>
                    </td>
                    <?php foreach($days as $day): ?>
                        <td>
                            <?php
                            $entry = null;
                            if($entries) {
                                foreach($entries as $e) {
                                    if($e->day_id == $day->id && $e->period_id == $period->id) {
                                        $entry = $e;
                                        break;
                                    }
                                }
                            }

                            if($entry):
                                ?>
                                <div class="entry">
                                    <?php if($type === 'class'): ?>
                                        <strong><?php echo htmlspecialchars($entry->subject_name); ?></strong>
                                        <small><?php echo htmlspecialchars($entry->teacher_name); ?></small>
                                        <?php if($entry->room_number): ?>
                                            <br><small>Room: <?php echo htmlspecialchars($entry->room_number); ?></small>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <strong><?php echo htmlspecialchars($entry->class_name . ' - ' . $entry->section_name); ?></strong>
                                        <small><?php echo htmlspecialchars($entry->subject_name); ?></small>
                                        <?php if($entry->room_number): ?>
                                            <br><small>Room: <?php echo htmlspecialchars($entry->room_number); ?></small>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <span style="color: #999;">-</span>
                            <?php endif; ?>
                        </td>
                    <?php endforeach; ?>
                </tr>
            <?php endif; ?>
        <?php endforeach; ?>
        </tbody>
    </table>

    <div class="footer">
        <p>Generated by <?php echo htmlspecialchars($schoolName); ?> Timetable System</p>
    </div>

    <script>
        // Auto-print option (commented out)
        // window.onload = function() { window.print(); }
    </script>
    </body>
    </html>
    <?php
}
?>