<?php
session_start();
error_reporting(0);
if(isset($_SESSION['teacher'])){
    $username = $_SESSION['teacher'];
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php include '../admin/includes/styles.php'; ?>
        <title>My Timetable | <?php echo $school_name; ?></title>

        <?php
        require_once '../admin/Classes/Timetable.php';
        $timetable = new Timetable();

        // Get teacher info
        $sql = "SELECT * FROM teachers WHERE username = :username";
        $conn->query($sql);
        $conn->bind(':username', $username);
        $teacher = $conn->fetchSingle();

        if (!$teacher) {
            header("Location: $teacher_login_link");
            exit();
        }

        $teacher_id = $teacher->id;
        $teacher_name = $teacher->name;
        ?>

        <style>
            .teacher-info-card {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border-radius: 8px;
                padding: 25px;
                margin-bottom: 20px;
                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            }
            .teacher-photo {
                width: 100px;
                height: 100px;
                border-radius: 50%;
                object-fit: cover;
                border: 4px solid white;
                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            }
            .workload-stats {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 15px;
                margin-bottom: 20px;
            }
            .stat-box {
                background: white;
                padding: 25px;
                border-radius: 8px;
                text-align: center;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                transition: all 0.3s;
            }
            .stat-box:hover {
                transform: translateY(-5px);
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            }
            .stat-number {
                font-size: 2.5rem;
                font-weight: bold;
                background: linear-gradient(135deg, #667eea, #764ba2);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                background-clip: text;
            }
            .stat-label {
                font-size: 0.9rem;
                color: #666;
                margin-top: 5px;
            }
            .stat-icon {
                font-size: 2rem;
                color: #667eea;
                margin-bottom: 10px;
            }
            .timetable-card {
                background: white;
                border-radius: 8px;
                padding: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .timetable-table {
                width: 100%;
                border-collapse: separate;
                border-spacing: 0;
            }
            .timetable-table th {
                background: linear-gradient(135deg, #667eea, #764ba2);
                color: white;
                padding: 12px;
                text-align: center;
                font-weight: 600;
                border: 1px solid #764ba2;
                position: sticky;
                top: 0;
                z-index: 10;
            }
            .timetable-table th:first-child {
                border-radius: 8px 0 0 0;
            }
            .timetable-table th:last-child {
                border-radius: 0 8px 0 0;
            }
            .timetable-table td {
                border: 1px solid #dee2e6;
                padding: 10px;
                vertical-align: top;
            }
            .period-cell {
                background: #f8f9fa;
                font-weight: 600;
                text-align: center;
                width: 120px;
            }
            .break-cell {
                background: #fff3cd;
                text-align: center;
                font-style: italic;
                color: #856404;
                font-weight: 600;
            }
            .class-entry {
                background: linear-gradient(135deg, #e7f3ff 0%, #f0f8ff 100%);
                border-left: 4px solid #007bff;
                padding: 12px;
                margin: 5px 0;
                border-radius: 4px;
                transition: all 0.3s;
            }
            .class-entry:hover {
                transform: translateX(5px);
                box-shadow: 0 4px 8px rgba(0,123,255,0.3);
            }
            .class-name {
                font-weight: 600;
                color: #0056b3;
                font-size: 0.95rem;
                margin-bottom: 5px;
            }
            .subject-name {
                font-size: 0.85rem;
                color: #666;
                margin-bottom: 3px;
            }
            .room-info {
                font-size: 0.8rem;
                color: #999;
            }
            .free-period {
                text-align: center;
                color: #999;
                font-style: italic;
                padding: 20px;
                background: #f8f9fa;
                border-radius: 4px;
            }
            .current-day {
                background: #fff3cd !important;
            }
            .filter-section {
                background: white;
                padding: 15px;
                border-radius: 8px;
                margin-bottom: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .schedule-summary {
                background: white;
                padding: 20px;
                border-radius: 8px;
                margin-bottom: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .day-summary {
                display: flex;
                justify-content: space-between;
                padding: 10px;
                border-bottom: 1px solid #dee2e6;
            }
            .day-summary:last-child {
                border-bottom: none;
            }
            @media (max-width: 768px) {
                .timetable-table {
                    font-size: 0.85rem;
                }
                .period-cell {
                    width: 80px;
                }
                .class-entry {
                    padding: 8px;
                }
                .teacher-photo {
                    width: 80px;
                    height: 80px;
                }
            }
            @media print {
                .no-print {
                    display: none;
                }
                .timetable-table {
                    font-size: 10pt;
                }
                .teacher-info-card {
                    background: #667eea !important;
                    -webkit-print-color-adjust: exact;
                    print-color-adjust: exact;
                }
            }
        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php include 'includes/notifications.php'; ?>
        <?php include "includes/sidebar.php"; ?>

        <?php
        //fetch active term
        $sql = "SELECT active_term FROM general_settings";
        $conn->query($sql);
        $active_term = $conn->fetchColumn();
        ?>

        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-6">
                            <h1 class="m-0"><i class="fas fa-calendar-week"></i> My Teaching Timetable</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url();?>">Home</a></li>
                                <li class="breadcrumb-item active">My Timetable</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <section class="content">
                <div class="container-fluid">

                    <!-- Teacher Info Card -->
                    <div class="teacher-info-card">
                        <div class="row align-items-center">
                            <div class="col-md-2 text-center">
                                <img src="<?php echo !empty($teacher->photo) ? '../admin/upload/' . $teacher->photo : '../admin/upload/default.png'; ?>"
                                     alt="Teacher Photo" class="teacher-photo">
                            </div>
                            <div class="col-md-7">
                                <h3 style="margin: 0 0 10px 0;"><?php echo htmlspecialchars($teacher_name); ?></h3>
                                <p style="margin: 0; font-size: 1.1rem;">
                                    <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($teacher->email); ?>
                                </p>
                                <?php if(!empty($teacher->phone)): ?>
                                    <p style="margin: 5px 0 0 0; font-size: 1rem;">
                                        <i class="fas fa-phone"></i> <?php echo htmlspecialchars($teacher->phone); ?>
                                    </p>
                                <?php endif; ?>
                            </div>
                            <div class="col-md-3 text-right no-print">
                                <button class="btn btn-light btn-lg" onclick="window.print()">
                                    <i class="fas fa-print"></i> Print Schedule
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="filter-section no-print">
                        <form id="filter-form">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Academic Year</label>
                                        <select name="academic_year" id="academic_year" class="form-control">
                                            <option value="">Current Year</option>
                                            <?php
                                            $currentYear = date('Y');
                                            for($i = $currentYear - 2; $i <= $currentYear + 2; $i++) {
                                                $selected = ($i == $currentYear) ? 'selected' : '';
                                                echo "<option value='{$i}' {$selected}>{$i}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Term</label>
                                        <select name="term" id="term" class="form-control">
                                            <option value="">Current Term</option>
                                            <option value="1st Term">1st Term</option>
                                            <option value="2nd Term">2nd Term</option>
                                            <option value="3rd Term">3rd Term</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>&nbsp;</label>
                                        <button type="submit" class="btn btn-primary btn-block">
                                            <i class="fas fa-search"></i> Load Timetable
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Workload Statistics -->
                    <div class="workload-stats" id="workload-stats" style="display:none;">
                        <div class="stat-box">
                            <div class="stat-icon"><i class="fas fa-clock"></i></div>
                            <div class="stat-number" id="total-periods">0</div>
                            <div class="stat-label">Teaching Periods/Week</div>
                        </div>
                        <div class="stat-box">
                            <div class="stat-icon"><i class="fas fa-calendar-day"></i></div>
                            <div class="stat-number" id="teaching-days">0</div>
                            <div class="stat-label">Teaching Days</div>
                        </div>
                        <div class="stat-box">
                            <div class="stat-icon"><i class="fas fa-users"></i></div>
                            <div class="stat-number" id="classes-taught">0</div>
                            <div class="stat-label">Classes Taught</div>
                        </div>
                        <div class="stat-box">
                            <div class="stat-icon"><i class="fas fa-hourglass-half"></i></div>
                            <div class="stat-number" id="free-periods">0</div>
                            <div class="stat-label">Free Periods</div>
                        </div>
                    </div>

                    <!-- Daily Schedule Summary -->
                    <div class="schedule-summary" id="schedule-summary" style="display:none;">
                        <h5><i class="fas fa-list"></i> Today's Schedule</h5>
                        <div id="today-schedule">
                            <!-- Today's classes will be listed here -->
                        </div>
                    </div>

                    <!-- Timetable Grid -->
                    <div id="timetable-container" style="display:none;">
                        <div class="timetable-card">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h4>Weekly Teaching Schedule</h4>
                                <span class="badge badge-info" id="entry-count">Loading...</span>
                            </div>
                            <div class="table-responsive">
                                <table class="timetable-table" id="timetable-table">
                                    <thead>
                                    <tr>
                                        <th>Period / Day</th>
                                        <!-- Days will be populated here -->
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <!-- Timetable content will be loaded here -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Loading State -->
                    <div id="loading-state" class="text-center" style="padding: 100px 0; display:none;">
                        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
                            <span class="sr-only">Loading...</span>
                        </div>
                        <h4 class="mt-3 text-muted">Loading your teaching schedule...</h4>
                    </div>

                    <!-- Empty State -->
                    <div id="empty-state" class="text-center" style="padding: 100px 0;">
                        <i class="fas fa-chalkboard-teacher" style="font-size: 5rem; color: #dee2e6;"></i>
                        <h4 class="mt-3 text-muted">Your Teaching Schedule</h4>
                        <p class="text-muted">Select filters and click "Load Timetable" to view your schedule</p>
                    </div>

                </div>
            </section>

        </div>

        <?php include "../admin/includes/footer.php";?>

        <script>
            let currentFilters = {
                teacher_id: <?php echo $teacher_id; ?>,
                academic_year: $('#academic_year').val(),
                term: "<?php echo $active_term; ?>"
            };

            $(document).ready(function() {
                // Auto-load current timetable
                loadTimetable();

                // Filter form submission
                $('#filter-form').on('submit', function(e) {
                    e.preventDefault();
                    currentFilters.academic_year = $('#academic_year').val();
                    currentFilters.term = $('#term').val();
                    loadTimetable();
                });
            });

            function loadTimetable() {
                $('#loading-state').show();
                $('#empty-state').hide();
                $('#timetable-container').hide();
                $('#workload-stats').hide();
                $('#schedule-summary').hide();

                $.ajax({
                    url: 'get-teacher-timetable-data.php',
                    type: 'POST',
                    data: currentFilters,
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            displayWorkload(response.workload);
                            renderTimetable(response.timetable, response.days, response.periods);
                            displayTodaySchedule(response.timetable, response.days, response.periods);
                            $('#loading-state').hide();
                            $('#timetable-container').show();
                            $('#workload-stats').show();
                            $('#schedule-summary').show();
                        } else {
                            $('#loading-state').hide();
                            $('#empty-state').show();
                            alert('Error loading timetable: ' + response.message);
                        }
                    },
                    error: function() {
                        $('#loading-state').hide();
                        $('#empty-state').show();
                        alert('Error connecting to server');
                    }
                });
            }

            function displayWorkload(workload) {
                $('#total-periods').text(workload.total_periods || 0);
                $('#teaching-days').text(workload.teaching_days || 0);
                $('#classes-taught').text(workload.classes_taught || 0);
            }

            function renderTimetable(data, days, periods) {
                // Update entry count
                $('#entry-count').text(data.length + ' classes this week');

                // Get current day
                const currentDay = new Date().getDay(); // 0=Sunday, 1=Monday, etc.

                // Build table header
                let headerHtml = '<tr><th>Period / Day</th>';
                days.forEach(day => {
                    const isToday = (day.day_number == currentDay);
                    headerHtml += `<th class="${isToday ? 'current-day' : ''}">${day.day_name}${isToday ? ' (Today)' : ''}</th>`;
                });
                headerHtml += '</tr>';
                $('#timetable-table thead').html(headerHtml);

                // Count total periods and free periods
                let totalPossiblePeriods = 0;
                let occupiedPeriods = data.length;

                // Build table body
                let bodyHtml = '';
                periods.forEach(period => {
                    if(period.is_break == 1) {
                        bodyHtml += `<tr>
                        <td class="period-cell break-cell" colspan="${days.length + 1}">
                            <i class="fas fa-coffee"></i> ${period.period_name} (${period.start_time} - ${period.end_time})
                        </td>
                    </tr>`;
                    } else {
                        totalPossiblePeriods += days.length;

                        bodyHtml += `<tr>
                        <td class="period-cell">
                            <strong>${period.period_name}</strong><br>
                            <small>${period.start_time}<br>${period.end_time}</small>
                        </td>`;

                        days.forEach(day => {
                            const entry = data.find(e => e.day_id == day.id && e.period_id == period.id);
                            const isToday = (day.day_number == currentDay);

                            if(entry) {
                                bodyHtml += `<td class="${isToday ? 'current-day' : ''}">
                                <div class="class-entry">
                                    <div class="class-name">
                                        <i class="fas fa-users"></i> ${entry.class_name} - ${entry.section_name}
                                    </div>
                                    <div class="subject-name">
                                        <i class="fas fa-book"></i> ${entry.subject_name}
                                    </div>
                                    ${entry.room_number ? `<div class="room-info"><i class="fas fa-door-open"></i> ${entry.room_number}</div>` : ''}
                                </div>
                            </td>`;
                            } else {
                                bodyHtml += `<td class="${isToday ? 'current-day' : ''}">
                                <div class="free-period">
                                    <i class="fas fa-coffee"></i> Free
                                </div>
                            </td>`;
                            }
                        });

                        bodyHtml += '</tr>';
                    }
                });

                $('#timetable-table tbody').html(bodyHtml);

                // Update free periods count
                const freePeriods = totalPossiblePeriods - occupiedPeriods;
                $('#free-periods').text(freePeriods);
            }

            function displayTodaySchedule(data, days, periods) {
                const currentDay = new Date().getDay();
                const todayEntries = data.filter(e => {
                    const day = days.find(d => d.id == e.day_id);
                    return day && day.day_number == currentDay;
                });

                if(todayEntries.length === 0) {
                    $('#today-schedule').html('<p class="text-muted text-center">No classes scheduled for today</p>');
                    return;
                }

                // Sort by period
                todayEntries.sort((a, b) => {
                    const periodA = periods.find(p => p.id == a.period_id);
                    const periodB = periods.find(p => p.id == b.period_id);
                    return periodA.period_number - periodB.period_number;
                });

                let scheduleHtml = '';
                todayEntries.forEach(entry => {
                    const period = periods.find(p => p.id == entry.period_id);
                    scheduleHtml += `
                    <div class="day-summary">
                        <div>
                            <strong>${period.period_name}</strong> (${period.start_time} - ${period.end_time})
                        </div>
                        <div>
                            ${entry.class_name} - ${entry.section_name} | ${entry.subject_name}
                            ${entry.room_number ? `| Room ${entry.room_number}` : ''}
                        </div>
                    </div>
                `;
                });

                $('#today-schedule').html(scheduleHtml);
            }
        </script>

    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Login to continue | <?php echo $school_name; ?></title>
        <?php include '../admin/includes/styles.php'; ?>
    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6>You need to login to continue</h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $teacher_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>