<?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'; ?>

    <?php
    require_once 'Classes/Timetable.php';
    $timetable = new Timetable();
    ?>
    <style>
        .template-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: all 0.3s;
        }
        .template-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        .template-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }
        .template-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #333;
        }
        .template-badge {
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.85rem;
            font-weight: 600;
        }
        .badge-active {
            background: #d4edda;
            color: #155724;
        }
        .badge-inactive {
            background: #f8d7da;
            color: #721c24;
        }
        .template-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        .info-item {
            padding: 10px;
            background: #f8f9fa;
            border-radius: 4px;
        }
        .info-label {
            font-size: 0.75rem;
            color: #6c757d;
            text-transform: uppercase;
        }
        .info-value {
            font-size: 1rem;
            font-weight: 600;
            color: #333;
        }
        .template-actions {
            display: flex;
            gap: 10px;
        }
        .fa-eye{
            background-color: transparent;
        }
    </style>
    <title> Manage Timetable Templates |  <?php echo $school_name; ?> </title>
    <?php
    $module_name = 'Timetable';
    include "check-admin-privilege.php";
    ?>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

  <!-- Navbar -->
    <?php include 'includes/notifications.php'; ?>
  <!-- /.navbar -->

  <!-- Main Sidebar Container -->
<?php include "includes/sidebar.php";?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <div class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1 class="m-0">Manage Timetable Templates</h1>
          </div><!-- /.col -->
          <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-timetable';?>">Timetable</a></li>
                  <li class="breadcrumb-item active">Manage Templates</li>
              </ol>
          </div><!-- /.col -->
        </div><!-- /.row -->
      </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->

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

              <div class="row mb-3">
                  <div class="col-12">
                      <button class="btn btn-primary" data-toggle="modal" data-target="#createTemplateModal">
                          <i class="fas fa-plus"></i> Create New Template
                      </button>
                      <button class="btn btn-info" data-toggle="modal" data-target="#saveCurrentModal">
                          <i class="fas fa-save"></i> Save Current Timetable as Template
                      </button>
                  </div>
              </div>

              <!-- Templates List -->
              <div class="row" id="templates-container">
                  <?php
                  $sql = "SELECT t.*, c.name as class_name, s.name as section_name,
                        (SELECT COUNT(*) FROM timetable_template_details WHERE template_id = t.id) as entry_count
                        FROM timetable_templates t
                        LEFT JOIN classes c ON t.class_id = c.id
                        LEFT JOIN sections s ON t.section_id = s.id
                        ORDER BY t.created_at DESC";
                  $conn->query($sql);
                  $templates = $conn->fetchMultiple();

                  if($conn->rowCount() > 0):
                      foreach($templates as $template):
                          ?>
                          <div class="col-md-6">
                              <div class="template-card">
                                  <div class="template-header">
                                      <div>
                                          <div class="template-title"><?php echo htmlspecialchars($template->template_name); ?></div>
                                          <small class="text-muted"><?php echo htmlspecialchars($template->description); ?></small>
                                      </div>
                                      <span class="template-badge <?php echo $template->is_active ? 'badge-active' : 'badge-inactive'; ?>">
                                <?php echo $template->is_active ? 'Active' : 'Inactive'; ?>
                            </span>
                                  </div>

                                  <div class="template-info">
                                      <div class="info-item">
                                          <div class="info-label">Class</div>
                                          <div class="info-value"><?php echo htmlspecialchars($template->class_name); ?></div>
                                      </div>
                                      <div class="info-item">
                                          <div class="info-label">Section</div>
                                          <div class="info-value"><?php echo htmlspecialchars($template->section_name); ?></div>
                                      </div>
                                      <div class="info-item">
                                          <div class="info-label">Entries</div>
                                          <div class="info-value"><?php echo $template->entry_count; ?></div>
                                      </div>
                                      <div class="info-item">
                                          <div class="info-label">Created</div>
                                          <div class="info-value"><?php echo date('M d, Y', strtotime($template->created_at)); ?></div>
                                      </div>
                                  </div>

                                  <div class="template-actions">
                                      <button class="btn btn-sm btn-primary" onclick="viewTemplate(<?php echo $template->id; ?>)">
                                          <i class="fas fa-eye"></i> View
                                      </button>
                                      <button class="btn btn-sm btn-success" onclick="applyTemplate(<?php echo $template->id; ?>)">
                                          <i class="fas fa-check"></i> Apply to Class
                                      </button>
                                      <button class="btn btn-sm btn-info" onclick="editTemplate(<?php echo $template->id; ?>)">
                                          <i class="fas fa-edit"></i> Edit
                                      </button>
                                      <button class="btn btn-sm btn-warning" onclick="duplicateTemplate(<?php echo $template->id; ?>)">
                                          <i class="fas fa-clone"></i> Duplicate
                                      </button>
                                      <button class="btn btn-sm btn-danger" onclick="deleteTemplate(<?php echo $template->id; ?>)">
                                          <i class="fas fa-trash"></i> Delete
                                      </button>
                                  </div>
                              </div>
                          </div>
                      <?php
                      endforeach;
                  else:
                      ?>
                      <div class="col-12">
                          <div class="alert alert-info text-center">
                              <i class="fas fa-info-circle"></i> No templates found. Create your first template to reuse timetable configurations.
                          </div>
                      </div>
                  <?php endif; ?>
              </div>

          </div>
      </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
  <?php include "includes/footer.php";?>
    <!-- Create Template Modal -->
    <div class="modal fade" id="createTemplateModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">Create New Template</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form id="create-template-form">
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Template Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="template_name" required placeholder="e.g., Science Stream Template">
                        </div>
                        <div class="form-group">
                            <label>Description</label>
                            <textarea class="form-control" name="description" rows="2" placeholder="Optional description"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Class <span class="text-danger">*</span></label>
                                    <select name="class_id" id="template_class_id" class="form-control" required>
                                        <option value="">Select Class</option>
                                        <?php
                                        $sql = "SELECT * FROM classes ORDER BY name";
                                        $conn->query($sql);
                                        $classes = $conn->fetchMultiple();
                                        foreach($classes as $class) {
                                            echo "<option value='{$class->id}'>{$class->name}</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Section <span class="text-danger">*</span></label>
                                    <select name="section_id" id="template_section_id" class="form-control" required>
                                        <option value="">Select Section</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Academic Year</label>
                            <input type="text" class="form-control" name="academic_year" placeholder="e.g., 2024">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Create Template
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Save Current as Template Modal -->
    <div class="modal fade" id="saveCurrentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title">Save Current Timetable as Template</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form id="save-current-form">
                    <div class="modal-body">
                        <div class="alert alert-info">
                            This will save the current timetable entries as a reusable template.
                        </div>
                        <div class="form-group">
                            <label>Template Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="template_name" required>
                        </div>
                        <div class="form-group">
                            <label>Description</label>
                            <textarea class="form-control" name="description" rows="2"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Class <span class="text-danger">*</span></label>
                                    <select name="class_id" id="save_class_id" class="form-control" required>
                                        <option value="">Select Class</option>
                                        <?php
                                        foreach($classes as $class) {
                                            echo "<option value='{$class->id}'>{$class->name}</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Section <span class="text-danger">*</span></label>
                                    <select name="section_id" id="save_section_id" class="form-control" required>
                                        <option value="">Select Section</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Academic Year</label>
                                    <input type="text" class="form-control" name="academic_year">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Term</label>
                                    <input type="text" class="form-control" name="term">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-info">
                            <i class="fas fa-save"></i> Save as Template
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Apply Template Modal -->
    <div class="modal fade" id="applyTemplateModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title">Apply Template</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form id="apply-template-form">
                    <input type="hidden" name="template_id" id="apply_template_id">
                    <div class="modal-body">
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i> This will create timetable entries based on this template.
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Academic Year <span class="text-danger">*</span></label>
                                    <select name="academic_year" class="form-control" required>
                                        <?php
                                        $currentYear = date('Y');
                                        for($i = $currentYear - 1; $i <= $currentYear + 2; $i++) {
                                            $selected = ($i == $currentYear) ? 'selected' : '';
                                            echo "<option value='{$i}' {$selected}>{$i}</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Term <span class="text-danger">*</span></label>
                                    <select name="term" class="form-control" required>
                                        <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>
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" name="clear_existing" id="clear_existing">
                            <label class="form-check-label" for="clear_existing">
                                Clear existing timetable entries before applying
                            </label>
                        </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-check"></i> Apply Template
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
  <?php
  ?>
    <script>
        $(document).ready(function() {
            // Load sections for create template
            $('#template_class_id').on('change', function() {
                loadSections($(this).val(), '#template_section_id');
            });

            // Load sections for save current
            $('#save_class_id').on('change', function() {
                loadSections($(this).val(), '#save_section_id');
            });

            // Create template form
            $('#create-template-form').on('submit', function(e) {
                e.preventDefault();
                createTemplate();
            });

            // Save current form
            $('#save-current-form').on('submit', function(e) {
                e.preventDefault();
                saveCurrentAsTemplate();
            });

            // Apply template form
            $('#apply-template-form').on('submit', function(e) {
                e.preventDefault();
                applyTemplateToClass();
            });
        });

        function loadSections(classId, targetSelector) {
            if(!classId) return;

            $.ajax({
                url: 'fetch_section.php',
                type: 'POST',
                data: {classesID: classId},
                success: function(html) {
                    $(targetSelector).html(html);
                }
            });
        }

        function createTemplate() {
            const formData = $('#create-template-form').serialize() + '&created_by=<?php echo $_SESSION['username']; ?>';

            $.ajax({
                url: 'create-template.php',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        toastr.success('Template created successfully');
                        $('#createTemplateModal').modal('hide');
                        location.reload();
                    } else {
                        toastr.error(response.message || 'Error creating template');
                    }
                },
                error: function() {
                    toastr.error('Error connecting to server');
                }
            });
        }

        function saveCurrentAsTemplate() {
            const formData = $('#save-current-form').serialize() + '&created_by=<?php echo $_SESSION['username']; ?>';

            $.ajax({
                url: 'save-current-as-template.php',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        toastr.success('Template saved successfully');
                        $('#saveCurrentModal').modal('hide');
                        location.reload();
                    } else {
                        toastr.error(response.message || 'Error saving template');
                    }
                },
                error: function() {
                    toastr.error('Error connecting to server');
                }
            });
        }

        function viewTemplate(templateId) {
            window.location.href = 'view-template.php?id=' + templateId;
        }

        function editTemplate(templateId) {
            window.location.href = 'edit-template.php?id=' + templateId;
        }

        function applyTemplate(templateId) {
            $('#apply_template_id').val(templateId);
            $('#applyTemplateModal').modal('show');
        }

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

            $.ajax({
                url: 'apply-template.php',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        toastr.success(`Template applied successfully! Created ${response.created} entries.`);
                        $('#applyTemplateModal').modal('hide');

                        if(response.errors && response.errors.length > 0) {
                            alert(`Note: ${response.errors.length} entries had conflicts and were skipped.`);
                        }

                        setTimeout(() => {
                            window.location.href = 'manage-timetable.php';
                        }, 2000);
                    } else {
                        toastr.error(response.message || 'Error applying template');
                    }
                },
                error: function() {
                    toastr.error('Error connecting to server');
                }
            });
        }

        function duplicateTemplate(templateId) {
            const newName = prompt('Enter name for duplicated template:');
            if(!newName) return;

            $.ajax({
                url: 'duplicate-template.php',
                type: 'POST',
                data: {
                    template_id: templateId,
                    new_name: newName
                },
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        toastr.success('Template duplicated successfully');
                        location.reload();
                    } else {
                        toastr.error(response.message || 'Error duplicating template');
                    }
                }
            });
        }

        function deleteTemplate(templateId) {
            if(!confirm('Are you sure you want to delete this template? This action cannot be undone.')) {
                return;
            }

            $.ajax({
                url: 'delete-template.php',
                type: 'POST',
                data: {template_id: templateId},
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        toastr.success('Template deleted successfully');
                        location.reload();
                    } else {
                        toastr.error(response.message || 'Error deleting template');
                    }
                }
            });
        }
    </script>
    <?php
  }else{
      ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no">
        <title>Login to continue |  <?php echo $school_name; ?> </title>

        <?php include 'includes/styles.php'; ?>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </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>

    <?php
    }

  ?>
