<?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>
        .period-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-left: 4px solid;
            transition: transform 0.2s;
        }
        .period-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        .period-card.class-period { border-color: #007bff; }
        .period-card.break-period { border-color: #ffc107; background: #fffbf0; }
        .period-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .period-name {
            font-size: 1.2rem;
            font-weight: 600;
            color: #333;
        }
        .period-time {
            font-size: 1.1rem;
            color: #666;
        }
        .period-duration {
            display: inline-block;
            padding: 4px 12px;
            background: #e3f2fd;
            color: #1976d2;
            border-radius: 20px;
            font-size: 0.9rem;
            margin-right: 10px;
        }
        .period-actions {
            display: flex;
            gap: 10px;
        }
        .drag-handle {
            cursor: move;
            color: #999;
            margin-right: 10px;
        }
    </style>
    <title> Manage Periods |  <?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 Periods</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">Timetable</li>
                  <li class="breadcrumb-item active">Manage Periods</li>
              </ol>
          </div><!-- /.col -->
        </div><!-- /.row -->
      </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->

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

              <!-- Action Buttons -->
              <div class="row mb-3">
                  <div class="col-md-12">
                      <button class="btn btn-primary" id="add-period-btn">
                          <i class="fas fa-plus"></i> Add New Period
                      </button>
                      <button class="btn btn-success" id="add-break-btn">
                          <i class="fas fa-coffee"></i> Add Break
                      </button>
                      <button class="btn btn-info" id="reset-default-btn">
                          <i class="fas fa-redo"></i> Reset to Default
                      </button>
                  </div>
              </div>

              <!-- Periods List -->
              <div class="row">
                  <div class="col-md-12">
                      <div class="card">
                          <div class="card-header bg-primary">
                              <h3 class="card-title">School Periods & Breaks</h3>
                              <div class="card-tools">
                                  <span class="badge badge-light" id="period-count">0 periods</span>
                              </div>
                          </div>
                          <div class="card-body">
                              <div id="periods-container">
                                  <!-- Periods will be loaded here -->
                              </div>
                          </div>
                      </div>
                  </div>
              </div>

          </div>
      </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
  <?php include "includes/footer.php";?>

    <!-- Add/Edit Period Modal -->
    <div class="modal fade" id="periodModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="periodModalTitle">Add Period</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form id="period-form">
                    <input type="hidden" id="period-id" name="period_id">
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Period Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="period-name" name="period_name" required placeholder="e.g., Period 1, Morning Break">
                        </div>

                        <div class="form-group">
                            <label>Period Number <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="period-number" name="period_number" required min="1" placeholder="Order number">
                            <small class="text-muted">Determines the display order</small>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Start Time <span class="text-danger">*</span></label>
                                    <input type="time" class="form-control" id="start-time" name="start_time" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>End Time <span class="text-danger">*</span></label>
                                    <input type="time" class="form-control" id="end-time" name="end_time" required>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Duration (minutes) <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="duration" name="duration" required min="1" readonly>
                            <small class="text-muted">Auto-calculated from start and end time</small>
                        </div>

                        <div class="form-group">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" id="is-break" name="is_break" value="1">
                                <label class="custom-control-label" for="is-break">
                                    This is a break period (lunch, recess, etc.)
                                </label>
                            </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-primary" id="save-period-btn">
                            <i class="fas fa-save"></i> Save Period
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

  <?php
  ?>
    <script>
        $(document).ready(function() {
            loadPeriods();

            // Add period button
            $('#add-period-btn').on('click', function() {
                openPeriodModal();
            });

            // Add break button
            $('#add-break-btn').on('click', function() {
                openPeriodModal(null, true);
            });

            // Calculate duration when times change
            $('#start-time, #end-time').on('change', function() {
                calculateDuration();
            });

            // Period form submission
            $('#period-form').on('submit', function(e) {
                e.preventDefault();
                savePeriod();
            });

            // Reset to default
            $('#reset-default-btn').on('click', function() {
                if(confirm('This will delete all custom periods and reset to default school periods. Continue?')) {
                    resetToDefault();
                }
            });
        });

        function loadPeriods() {
            $.ajax({
                url: 'get-periods-list.php',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        renderPeriods(response.periods);
                        $('#period-count').text(response.periods.length + ' period' + (response.periods.length !== 1 ? 's' : ''));
                    }
                },
                error: function() {
                    alert('Error loading periods');
                }
            });
        }

        function renderPeriods(periods) {
            let html = '';

            if(periods.length === 0) {
                html = '<div class="alert alert-info text-center">No periods configured. Click "Add New Period" to create one.</div>';
            } else {
                periods.forEach(period => {
                    const cardClass = period.is_break == 1 ? 'break-period' : 'class-period';
                    const icon = period.is_break == 1 ? 'fa-coffee' : 'fa-chalkboard-teacher';
                    const typeLabel = period.is_break == 1 ? 'Break' : 'Class Period';

                    html += `
                <div class="period-card ${cardClass}" data-id="${period.id}">
                    <div class="period-header">
                        <div>
                            <i class="fas ${icon}" style="color: #666; margin-right: 10px;"></i>
                            <span class="period-name">${period.period_name}</span>
                            <span class="badge badge-secondary ml-2">${typeLabel}</span>
                        </div>
                        <div class="period-actions">
                            <button class="btn btn-sm btn-info edit-period" data-id="${period.id}">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger delete-period" data-id="${period.id}">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div>
                        <span class="period-time">
                            <i class="fas fa-clock"></i> ${formatTime(period.start_time)} - ${formatTime(period.end_time)}
                        </span>
                        <span class="period-duration">${period.duration} minutes</span>
                    </div>
                </div>
            `;
                });
            }

            $('#periods-container').html(html);

            // Attach event handlers
            $('.edit-period').on('click', function() {
                const periodId = $(this).data('id');
                editPeriod(periodId);
            });

            $('.delete-period').on('click', function() {
                const periodId = $(this).data('id');
                deletePeriod(periodId);
            });
        }

        function openPeriodModal(periodId = null, isBreak = false) {
            $('#period-form')[0].reset();
            $('#period-id').val('');

            if(isBreak) {
                $('#is-break').prop('checked', true);
            }

            $('#periodModalTitle').text(periodId ? 'Edit Period' : 'Add Period');
            $('#periodModal').modal('show');
        }

        function editPeriod(periodId) {
            $.ajax({
                url: 'get-period-details.php',
                type: 'POST',
                data: {period_id: periodId},
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        const period = response.period;
                        $('#period-id').val(period.id);
                        $('#period-name').val(period.period_name);
                        $('#period-number').val(period.period_number);
                        $('#start-time').val(period.start_time);
                        $('#end-time').val(period.end_time);
                        $('#duration').val(period.duration);
                        $('#is-break').prop('checked', period.is_break == 1);

                        $('#periodModalTitle').text('Edit Period');
                        $('#periodModal').modal('show');
                    }
                }
            });
        }

        function calculateDuration() {
            const startTime = $('#start-time').val();
            const endTime = $('#end-time').val();

            if(startTime && endTime) {
                const start = new Date('2000-01-01 ' + startTime);
                const end = new Date('2000-01-01 ' + endTime);
                const diff = (end - start) / 1000 / 60; // Minutes

                if(diff > 0) {
                    $('#duration').val(diff);
                }
            }
        }

        function savePeriod() {
            const formData = $('#period-form').serialize();
            const url = $('#period-id').val() ? 'update-period.php' : 'create-period.php';

            $('#save-period-btn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');

            $.ajax({
                url: url,
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        $('#periodModal').modal('hide');
                        loadPeriods();
                        alert('Period saved successfully');
                    } else {
                        alert('Error: ' + response.message);
                    }
                },
                error: function() {
                    alert('Error saving period');
                },
                complete: function() {
                    $('#save-period-btn').prop('disabled', false).html('<i class="fas fa-save"></i> Save Period');
                }
            });
        }

        function deletePeriod(periodId) {
            if(confirm('Are you sure you want to delete this period? This will also delete all timetable entries using this period.')) {
                $.ajax({
                    url: 'delete-period.php',
                    type: 'POST',
                    data: {period_id: periodId},
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            loadPeriods();
                            alert('Period deleted successfully');
                        } else {
                            alert('Error: ' + response.message);
                        }
                    }
                });
            }
        }

        function resetToDefault() {
            $.ajax({
                url: 'reset-default-periods.php',
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        loadPeriods();
                        alert('Periods reset to default successfully');
                    } else {
                        alert('Error: ' + response.message);
                    }
                }
            });
        }

        function formatTime(time) {
            const date = new Date('2000-01-01 ' + time);
            return date.toLocaleTimeString('en-US', {hour: '2-digit', minute: '2-digit'});
        }
    </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
    }

  ?>
