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

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

        $module_name = 'Timetable';
        include "check-admin-privilege.php";

        ?>
        <style>
            .teacher-card {
                background: white;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .teacher-info {
                display: flex;
                align-items: center;
                gap: 20px;
                margin-bottom: 20px;
            }
            .teacher-photo {
                width: 80px;
                height: 80px;
                border-radius: 50%;
                object-fit: cover;
                border: 3px solid #007bff;
            }
            .workload-stats {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 15px;
                margin: 20px 0;
            }
            .stat-box {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 20px;
                border-radius: 8px;
                text-align: center;
            }
            .stat-number {
                font-size: 2rem;
                font-weight: bold;
            }
            .stat-label {
                font-size: 0.9rem;
                opacity: 0.9;
            }
            .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;
            }
            .timetable-table td {
                border: 1px solid #dee2e6;
                padding: 10px;
                vertical-align: top;
            }
            .period-cell {
                background: #f8f9fa;
                font-weight: 600;
                text-align: center;
                width: 120px;
            }
            .class-entry {
                background: #e7f3ff;
                border-left: 4px solid #007bff;
                padding: 10px;
                margin: 5px 0;
                border-radius: 4px;
            }
            .class-name {
                font-weight: 600;
                color: #0056b3;
            }
            .subject-name {
                font-size: 0.9rem;
                color: #666;
            }
            .room-info {
                font-size: 0.8rem;
                color: #999;
            }
            .free-period {
                text-align: center;
                color: #999;
                font-style: italic;
                padding: 20px;
            }
            .break-cell {
                background: #fff3cd;
                text-align: center;
                font-style: italic;
                color: #856404;
            }

            .fa-eye{
                background-color: transparent;
            }
        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php include 'includes/notifications.php'; ?>
        <?php include "includes/sidebar.php"; ?>

        <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-chalkboard-teacher"></i> Teacher Timetable</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
                                <li class="breadcrumb-item">Timetable</li>
                                <li class="breadcrumb-item active">Teacher View</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

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

                    <!-- Filter Section -->
                    <div class="teacher-card">
                        <h5>Select Teacher</h5>
                        <form id="filter-form">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Teacher <span class="text-danger">*</span></label>
                                        <select name="teacher_id" id="teacher_id" class="form-control" required>
                                            <option value="">Select Teacher</option>
                                            <?php
                                            $sql = "SELECT id, name, email FROM teachers ORDER BY name";
                                            $conn->query($sql);
                                            $teachers = $conn->fetchMultiple();
                                            foreach($teachers as $teacher) {
                                                echo "<option value='{$teacher->id}'>{$teacher->name}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Academic Year</label>
                                        <select name="academic_year" id="academic_year" class="form-control">
                                            <option value="">Select 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-3">
                                    <div class="form-group">
                                        <label>Term</label>
                                        <select name="term" id="term" class="form-control">
                                            <option value="">Select 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-2">
                                    <div class="form-group">
                                        <label>&nbsp;</label>
                                        <button type="submit" class="btn btn-primary btn-block">
                                            <i class="fas fa-search"></i> Load
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Teacher Info & Workload -->
                    <div id="teacher-info" style="display:none;">
                        <div class="teacher-card">
                            <div class="teacher-info">
                                <img id="teacher-photo" src="" alt="Teacher Photo" class="teacher-photo">
                                <div>
                                    <h3 id="teacher-name"></h3>
                                    <p class="mb-0" id="teacher-email"></p>
                                </div>
                            </div>

                            <div class="workload-stats">
                                <div class="stat-box" style="background: linear-gradient(135deg, #667eea, #764ba2);">
                                    <div class="stat-number" id="total-periods">0</div>
                                    <div class="stat-label">Total Periods</div>
                                </div>
                                <div class="stat-box" style="background: linear-gradient(135deg, #f093fb, #f5576c);">
                                    <div class="stat-number" id="teaching-days">0</div>
                                    <div class="stat-label">Teaching Days</div>
                                </div>
                                <div class="stat-box" style="background: linear-gradient(135deg, #4facfe, #00f2fe);">
                                    <div class="stat-number" id="classes-taught">0</div>
                                    <div class="stat-label">Classes Taught</div>
                                </div>
                            </div>

                            <div class="text-right">
<!--                                <button class="btn btn-primary" id="print-btn">-->
<!--                                    <i class="fas fa-print"></i> Print Timetable-->
<!--                                </button>-->

                                <button class="btn btn-success" id="export-excel-btn">
                                    <i class="fas fa-file-excel"></i> Export Excel
                                </button>
                                <button class="btn btn-danger" id="export-pdf-btn">
                                    <i class="fas fa-file-pdf"></i> Export PDF/Print
                                </button>
                            </div>
                        </div>

                        <!-- Timetable Grid -->
                        <div class="teacher-card">
                            <h4>Weekly Timetable</h4>
                            <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>

                    <!-- 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">Select a Teacher to View Timetable</h4>
                        <p class="text-muted">Choose a teacher from the dropdown above</p>
                    </div>

                </div>
            </section>

        </div>

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

        <script>
            let currentTeacherId = null;

            $(document).ready(function() {
                $('#teacher_id').select2();

                $('#filter-form').on('submit', function(e) {
                    e.preventDefault();

                    currentTeacherId = $('#teacher_id').val();
                    if(!currentTeacherId) {
                        alert('Please select a teacher');
                        return;
                    }

                    loadTeacherTimetable();
                });

                // $('#print-btn').on('click', function() {
                //     const params = {
                //         teacher_id: currentTeacherId,
                //         academic_year: $('#academic_year').val(),
                //         term: $('#term').val()
                //     };
                //     window.open('print-teacher-timetable.php?' + $.param(params), '_blank');
                // });

                // Export to Excel
                $('#export-excel-btn').on('click', function() {

                    // Merge current filters with the required backend tags
                    const params = {
                        teacher_id: currentTeacherId,
                        academic_year: $('#academic_year').val(),
                        term: $('#term').val(),
                        type: 'teacher',
                        format: 'excel'
                    };

                    // Construct URL and open
                    window.open('export-timetable.php?' + $.param(params), '_blank');
                });

                // Export to PDF/Print
                $('#export-pdf-btn').on('click', function() {

                    // Merge current filters with the required backend tags
                    const params = {
                        teacher_id: currentTeacherId,
                        academic_year: $('#academic_year').val(),
                        term: $('#term').val(),
                        type: 'teacher',
                        format: 'pdf'
                    };

                    // Construct URL and open
                    window.open('export-timetable.php?' + $.param(params), '_blank');
                });
            });

            function loadTeacherTimetable() {
                $.ajax({
                    url: 'get-teacher-timetable-data.php',
                    type: 'POST',
                    data: {
                        teacher_id: currentTeacherId,
                        academic_year: $('#academic_year').val(),
                        term: $('#term').val()
                    },
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            displayTeacherInfo(response.teacher);
                            displayWorkload(response.workload);
                            renderTimetable(response.timetable, response.days, response.periods);
                            $('#empty-state').hide();
                            $('#teacher-info').show();
                        } else {
                            alert('Error loading timetable');
                        }
                    },
                    error: function() {
                        alert('Error connecting to server');
                    }
                });
            }

            function displayTeacherInfo(teacher) {
                $('#teacher-photo').attr('src', teacher.photo || '../upload/default-avatar.png');
                $('#teacher-name').text(teacher.name);
                $('#teacher-email').text(teacher.email);
            }

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

            function renderTimetable(data, days, periods) {
                // Build table header
                let headerHtml = '<tr><th>Period / Day</th>';
                days.forEach(day => {
                    headerHtml += `<th>${day.day_name}</th>`;
                });
                headerHtml += '</tr>';
                $('#timetable-table thead').html(headerHtml);

                // 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}">
                    ${period.period_name} (${period.start_time} - ${period.end_time})
                </td>
            </tr>`;
                    } else {
                        bodyHtml += `<tr>
                <td class="period-cell">
                    <strong>${period.period_name}</strong><br>
                    <small>${period.start_time} - ${period.end_time}</small>
                </td>`;

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

                            if(entry) {
                                bodyHtml += `<td>
                        <div class="class-entry">
                            <div class="class-name">${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><div class="free-period">Free</div></td>`;
                            }
                        });

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

                $('#timetable-table tbody').html(bodyHtml);
            }
        </script>

    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPEhtml>
    <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 '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 $link; ?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>