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

    if(!isset($_GET['id'])) {
        header("Location: manage-templates");
        exit();
    }

    $template_id = $_GET['id'];
    ?>
    <!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>Edit Template | <?php echo $school_name; ?></title>

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

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

        // Get template details
        $sql = "SELECT t.*, c.name as class_name, s.name as section_name
            FROM timetable_templates t
            LEFT JOIN classes c ON t.class_id = c.id
            LEFT JOIN sections s ON t.section_id = s.id
            WHERE t.id = :template_id";
        $conn->query($sql);
        $conn->bind(':template_id', $template_id);
        $template = $conn->fetchSingle();

        if(!$template) {
            header("Location: manage-templates.php");
            exit();
        }

        // Get template entries
        $sql = "SELECT td.*, 
            s.subject_name,
            t.name as teacher_name,
            d.day_name,
            p.period_name, p.start_time, p.end_time, p.period_number
            FROM timetable_template_details td
            LEFT JOIN subjects s ON td.subject_id = s.id
            LEFT JOIN teachers t ON td.teacher_id = t.id
            LEFT JOIN timetable_days d ON td.day_id = d.id
            LEFT JOIN timetable_periods p ON td.period_id = p.id
            WHERE td.template_id = :template_id
            ORDER BY d.day_number, p.period_number";
        $conn->query($sql);
        $conn->bind(':template_id', $template_id);
        $entries = $conn->fetchMultiple();

        ?>
        <style>
            .template-info-card {
                background: white;
                padding: 20px;
                border-radius: 8px;
                margin-bottom: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .entry-card {
                background: #f8f9fa;
                border-left: 4px solid #007bff;
                padding: 15px;
                margin-bottom: 10px;
                border-radius: 4px;
                transition: all 0.3s;
            }
            .entry-card:hover {
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            }
            .entry-actions {
                display: flex;
                gap: 5px;
            }
        </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">Edit Template</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"><a href="<?php echo $conn->base_url();?>manage-templates">Manage Templates</a></li>
                                <li class="breadcrumb-item active">Edit Template </li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

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

                    <!-- Template Info -->
                    <div class="template-info-card">
                        <form id="update-template-form">
                            <input type="hidden" name="template_id" value="<?php echo $template_id; ?>">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Template Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" name="template_name"
                                               value="<?php echo htmlspecialchars($template->template_name); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Description</label>
                                        <input type="text" class="form-control" name="description"
                                               value="<?php echo htmlspecialchars($template->description); ?>">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Class</label>
                                        <input type="text" class="form-control"
                                               value="<?php echo htmlspecialchars($template->class_name); ?>" readonly>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Section</label>
                                        <input type="text" class="form-control"
                                               value="<?php echo htmlspecialchars($template->section_name); ?>" readonly>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Status</label>
                                        <select name="is_active" class="form-control">
                                            <option value="1" <?php echo $template->is_active ? 'selected' : ''; ?>>Active</option>
                                            <option value="0" <?php echo !$template->is_active ? 'selected' : ''; ?>>Inactive</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>&nbsp;</label>
                                        <button type="submit" class="btn btn-primary btn-block">
                                            <i class="fas fa-save"></i> Update Template Info
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Entries Management -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Template Entries (<?php echo count($entries); ?>)</h3>
                            <div class="card-tools">
                                <button class="btn btn-success btn-sm" data-toggle="modal" data-target="#addEntryModal">
                                    <i class="fas fa-plus"></i> Add Entry
                                </button>
                                <a href="manage-templates.php" class="btn btn-secondary btn-sm">
                                    <i class="fas fa-arrow-left"></i> Back
                                </a>
                            </div>
                        </div>
                        <div class="card-body">
                            <?php if(count($entries) > 0): ?>
                                <div id="entries-container">
                                    <?php foreach($entries as $entry): ?>
                                        <div class="entry-card" id="entry-<?php echo $entry->id; ?>">
                                            <div class="row align-items-center">
                                                <div class="col-md-10">
                                                    <strong><?php echo $entry->day_name; ?> - <?php echo $entry->period_name; ?></strong>
                                                    (<?php echo $entry->start_time; ?> - <?php echo $entry->end_time; ?>)
                                                    <br>
                                                    <small>
                                                        <i class="fas fa-book"></i> <?php echo $entry->subject_name; ?> |
                                                        <i class="fas fa-chalkboard-teacher"></i> <?php echo $entry->teacher_name; ?>
                                                        <?php if($entry->room_number): ?>
                                                            | <i class="fas fa-door-open"></i> <?php echo $entry->room_number; ?>
                                                        <?php endif; ?>
                                                    </small>
                                                </div>
                                                <div class="col-md-2 text-right">
                                                    <div class="entry-actions">
                                                        <button class="btn btn-sm btn-danger" onclick="deleteTemplateEntry(<?php echo $entry->id; ?>)">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="alert alert-info text-center">
                                    <i class="fas fa-info-circle"></i> No entries in this template yet. Add entries to get started.
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
            </section>

        </div>

        <!-- Add Entry Modal -->
        <div class="modal fade" id="addEntryModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header bg-success text-white">
                        <h5 class="modal-title">Add Template Entry</h5>
                        <button type="button" class="close text-white" data-dismiss="modal">
                            <span>&times;</span>
                        </button>
                    </div>
                    <form id="add-entry-form">
                        <input type="hidden" name="template_id" value="<?php echo $template_id; ?>">
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Day <span class="text-danger">*</span></label>
                                        <select name="day_id" class="form-control" required>
                                            <option value="">Select Day</option>
                                            <?php
                                            $days = $timetable->getActiveDays();
                                            foreach($days as $day) {
                                                echo "<option value='{$day->id}'>{$day->day_name}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Period <span class="text-danger">*</span></label>
                                        <select name="period_id" class="form-control" required>
                                            <option value="">Select Period</option>
                                            <?php
                                            $periods = $timetable->getAllPeriods();
                                            foreach($periods as $period) {
                                                if($period->is_break == 0) {
                                                    echo "<option value='{$period->id}'>{$period->period_name} ({$period->start_time} - {$period->end_time})</option>";
                                                }
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Subject <span class="text-danger">*</span></label>
                                        <select name="subject_id" class="form-control" required>
                                            <option value="">Select Subject</option>
                                            <?php
                                            $sql = "SELECT * FROM subjects WHERE class_id = :class_id ORDER BY subject_name";
                                            $conn->query($sql);
                                            $conn->bind(':class_id', $template->class_id);
                                            $subjects = $conn->fetchMultiple();
                                            foreach($subjects as $subject) {
                                                echo "<option value='{$subject->id}'>{$subject->subject_name}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Teacher <span class="text-danger">*</span></label>
                                        <select name="teacher_id" class="form-control" required>
                                            <option value="">Select Teacher</option>
                                            <?php
                                            $sql = "SELECT id, name 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>
                            <div class="form-group">
                                <label>Room Number</label>
                                <input type="text" class="form-control" name="room_number" placeholder="e.g., 101">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-plus"></i> Add Entry
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

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

        <script>
            $(document).ready(function() {
                // Update template info
                $('#update-template-form').on('submit', function(e) {
                    e.preventDefault();
                    updateTemplateInfo();
                });

                // Add entry
                $('#add-entry-form').on('submit', function(e) {
                    e.preventDefault();
                    addTemplateEntry();
                });
            });

            function updateTemplateInfo() {
                const formData = $('#update-template-form').serialize();

                $.ajax({
                    url: 'update-template-info.php',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            toastr.success('Template information updated successfully');
                        } else {
                            toastr.error(response.message || 'Error updating template');
                        }
                    },
                    error: function() {
                        toastr.error('Error connecting to server');
                    }
                });
            }

            function addTemplateEntry() {
                const formData = $('#add-entry-form').serialize();

                $.ajax({
                    url: 'add-template-entry.php',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            toastr.success('Entry added successfully');
                            $('#addEntryModal').modal('hide');
                            location.reload();
                        } else {
                            toastr.error(response.message || 'Error adding entry');
                        }
                    },
                    error: function() {
                        toastr.error('Error connecting to server');
                    }
                });
            }

            function deleteTemplateEntry(entryId) {
                if(!confirm('Are you sure you want to delete this entry?')) {
                    return;
                }

                $.ajax({
                    url: 'delete-template-entry.php',
                    type: 'POST',
                    data: {entry_id: entryId},
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            $('#entry-' + entryId).fadeOut(300, function() {
                                $(this).remove();
                            });
                            toastr.success('Entry deleted successfully');
                        } else {
                            toastr.error(response.message || 'Error deleting entry');
                        }
                    },
                    error: function() {
                        toastr.error('Error connecting to server');
                    }
                });
            }
        </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
}
?>