<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../include/config.php";

// Check login
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

$email = $_SESSION['email'] ?? '';

// Handle time update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_time'])) {
    $exam_id = $conn->real_escape_string($_POST['exam_id']);
    $start_time = $conn->real_escape_string($_POST['start_time']);
    $end_time = $conn->real_escape_string($_POST['end_time']);
    $exam_date = $conn->real_escape_string($_POST['exam_date']);
    
    $update_sql = "UPDATE exam_schedule SET start_time='$start_time', end_time='$end_time', exam_date='$exam_date', updated_at=NOW() WHERE id='$exam_id' AND email='$email'";
    
    if ($conn->query($update_sql)) {
        $_SESSION['msg'] = "Exam schedule updated successfully!";
    } else {
        $_SESSION['msg'] = "Error updating schedule: " . $conn->error;
    }
    
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// Fetch all exams created by this teacher
$sql = "SELECT * FROM exam_schedule WHERE email='$email' ORDER BY exam_date ASC, start_time DESC";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Scheduled Exams</title>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap" rel="stylesheet">

  <style>
    body {
      background-color: #f8f9fa; 
      font-family: 'Source Sans Pro', sans-serif;
    }
    .table-container {
      background: white;
      border-radius: 10px;
      box-shadow: 0 2px 15px rgba(0,0,0,0.1);
      overflow: hidden;
    }
    .table thead {
      background: linear-gradient(135deg, var(--primary), #b02a37);
      color: white;
    }
    .table thead th {
      border: none;
      padding: 15px 12px;
      font-weight: 600;
    }
    .table tbody tr {
      transition: all 0.3s ease;
    }
    .table tbody tr:hover {
      background-color: #f8f9fa;
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    .btn-edit {
      background: var(--primary);
      border: none;
      color: white;
      transition: all 0.3s ease;
    }
    .btn-edit:hover {
      background: #b02a37;
      transform: translateY(-2px);
    }
    .btn-view {
      background: #6c757d;
      border: none;
      color: white;
      transition: all 0.3s ease;
    }
    .btn-view:hover {
      background: #5a6268;
      transform: translateY(-2px);
    }
    .exam-title {
      color: var(--primary);
      font-weight: 600;
    }
    .badge-taken {
      background: #28a745;
    }
    .badge-pending {
      background: #ffc107;
      color: #000;
    }
    .timestamp {
      font-size: 0.8rem;
      color: #6c757d;
    }
    .form-control-sm {
      border-radius: 5px;
    }
  </style>
</head>
<body>

<?php include "../include/nav.php"; ?>

<div class="content">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="mb-0"><i class="fa fa-calendar-check-o"></i> Scheduled Exams</h3>
    <span class="badge bg-primary"><?= $result->num_rows ?> Exams</span>
  </div>

  <?php if (isset($_SESSION['msg'])): ?>
    <div class="alert alert-info alert-dismissible fade show mt-3" role="alert">
      <?= $_SESSION['msg']; unset($_SESSION['msg']); ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  <?php endif; ?>

  <?php if ($result->num_rows > 0): ?>
    <div class="table-containe">
      <div class="table-responsive">
        <table class="table table-hover table-striped mb-0">
          <thead>
            <tr>
              <th>Exam Details</th>
              <th>Program & Intake</th>
              <th>Date & Time</th>
              <th>Students</th>
              <th>Last Updated</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php while($exam = $result->fetch_assoc()): 
              $exam_id = $exam['id'];
              $count_submitted = $conn->query("SELECT COUNT(*) as total FROM exam_results_summary WHERE exam_id='$exam_id'");
              $students_taken = $count_submitted->fetch_assoc()['total'];
              $last_updated = !empty($exam['updated_at']) ? date("d M Y, H:i", strtotime($exam['updated_at'])) : 'Not updated';
            ?>
              <tr>
                <td>
                  <div class="exam-title"><?= htmlspecialchars($exam['exam_title']) ?></div>
                  <small class="text-muted"><?= htmlspecialchars($exam['course']) ?></small>
                </td>
                <td>
                  <div><strong><?= htmlspecialchars($exam['program']) ?></strong></div>
                  <small class="text-muted">Intake: <?= htmlspecialchars($exam['intake']) ?></small>
                </td>
                <td>
                  <form action="" method="POST" class="exam-time-form">
                    <input type="hidden" name="exam_id" value="<?= $exam_id ?>">
                    <div class="row g-2">
                      <div class="col-12">
                        <label class="form-label small text-muted mb-1">Date</label>
                        <input type="date" name="exam_date" value="<?= htmlspecialchars($exam['exam_date']) ?>" class="form-control form-control-sm" required>
                      </div>
                      <div class="col-6">
                        <label class="form-label small text-muted mb-1">Start</label>
                        <input type="time" name="start_time" value="<?= htmlspecialchars($exam['start_time']) ?>" class="form-control form-control-sm" required>
                      </div>
                      <div class="col-6">
                        <label class="form-label small text-muted mb-1">End</label>
                        <input type="time" name="end_time" value="<?= htmlspecialchars($exam['end_time']) ?>" class="form-control form-control-sm" required>
                      </div>
                    </div>
                </td>
                <td>
                  <span class="badge <?= $students_taken > 0 ? 'badge-taken' : 'badge-pending' ?>">
                    <?= $students_taken ?> taken
                  </span>
                </td>
                <td>
                  <span class="timestamp">
                    <i class="fa fa-clock-o"></i><br>
                    <?= $last_updated ?>
                  </span>
                </td>
                <td>
                  <div class="d-flex flex-column gap-2">
                    <button type="submit" name="update_time" class="btn btn-edit btn-sm">
                      <i class="fa fa-save"></i> Update
                    </button>
                    </form>
                    <a href="viewresults.php?exam_id=<?= $exam_id ?>" class="btn btn-view btn-sm">
                      <i class="fa fa-eye"></i> Results
                    </a>
                  </div>
                </td>
              </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php else: ?>
    <div class="text-center py-5">
      <i class="fa fa-calendar-times-o fa-4x text-muted mb-3"></i>
      <h4 class="text-muted">No Scheduled Exams</h4>
      <p class="text-muted">You haven't created any exams yet.</p>
    </div>
  <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // Add confirmation for time updates
  document.querySelectorAll('.exam-time-form').forEach(form => {
    form.addEventListener('submit', function(e) {
      const startTime = this.querySelector('input[name="start_time"]').value;
      const endTime = this.querySelector('input[name="end_time"]').value;
      const examDate = this.querySelector('input[name="exam_date"]').value;
      
      if (startTime >= endTime) {
        e.preventDefault();
        alert('End time must be after start time!');
        return false;
      }
      
      const today = new Date().toISOString().split('T')[0];
      if (examDate < today) {
        if (!confirm('You are scheduling an exam for a past date. Are you sure?')) {
          e.preventDefault();
          return false;
        }
      }
      
      return true;
    });
  });
</script>
</body>
</html>