<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
session_start();
include "../include/config.php";

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

$staff_email = $_SESSION['email'];
$success = "";
$error   = "";

// ✅ Load Google API
require_once __DIR__ . '/google/vendor/autoload.php';

// Function to get Google Client
function getClient() {
    $client = new Google_Client();
    $client->setAuthConfig(__DIR__ . '/credentials.json'); // download JSON from Google Cloud Console
    $client->addScope(Google_Service_Calendar::CALENDAR);
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    $tokenPath = __DIR__ . '/token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // Refresh token if expired
    if ($client->isAccessTokenExpired()) {
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            $authUrl = $client->createAuthUrl();
            die("Open the following link in your browser to authorize: <a href='$authUrl' target='_blank'>$authUrl</a>");
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }

    return $client;
}

// ✅ Create new class
if (isset($_POST['create_class'])) {
    $program    = $conn->real_escape_string($_POST['program']);
    $course     = $conn->real_escape_string($_POST['course']);
    $intake     = $conn->real_escape_string($_POST['intake']);
    $title      = $conn->real_escape_string($_POST['title']);
    $start_time = str_replace('T', ' ', $_POST['start_time']); // Fix input format

    try {
        $client  = getClient();
        $service = new Google_Service_Calendar($client);

        $event = new Google_Service_Calendar_Event([
            'summary' => $title,
            'start' => [
                'dateTime' => date('c', strtotime($start_time)),
                'timeZone' => 'Africa/Lusaka'
            ],
            'end' => [
                'dateTime' => date('c', strtotime($start_time . ' +1 hour')),
                'timeZone' => 'Africa/Lusaka'
            ],
            'conferenceData' => [
                'createRequest' => [
                    'requestId' => uniqid(),
                    'conferenceSolutionKey' => ['type' => 'hangoutsMeet']
                ]
            ]
        ]);

        $calendarId = 'primary';
        $event = $service->events->insert($calendarId, $event, ['conferenceDataVersion' => 1]);

        $meet_link = $event->getHangoutLink() ?? '';

        // Save class in DB
        $insert = $conn->query("INSERT INTO classes (staff_email, program, course, intake, title, meet_link, start_time)
                                VALUES ('$staff_email', '$program', '$course', '$intake', '$title', '$meet_link', '$start_time')");
        if ($insert) {
            $success = "Class created successfully! <a href='$meet_link' target='_blank'>Join Meet</a>";
        } else {
            $error = "Database error: " . $conn->error;
        }

    } catch (Exception $e) {
        $error = "Error creating Google Meet: " . $e->getMessage();
    }
}

// ✅ Fetch programs & courses for dropdowns
$programs = $conn->query("SELECT DISTINCT program FROM programs ORDER BY program ASC");
$courses  = $conn->query("SELECT DISTINCT course FROM courses ORDER BY course ASC");

// ✅ Fetch all classes
$classes = $conn->query("SELECT * FROM classes ORDER BY created_at DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Teacher Classes</title>
  <link rel="stylesheet" href="../../boostrap/1.css">
  <link rel="stylesheet" href="../../boostrap/2.css">
  <link rel="icon" href="favicon.png" type="image/png">
  <meta name="theme-color" content="#d03f4d">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<?php include "../include/nav.php"; ?>

<div class="content">
<br><br><br>
<div class="container mt-5">
  <h3 class="mb-4 text-danger"><i class="fa fa-video-camera"></i> Teacher Classes</h3>

  <?php if ($success) { ?>
    <div class="alert alert-success text-center">
      <i class="fa fa-check-circle"></i> <?= $success; ?>
    </div>
  <?php } ?>

  <?php if ($error) { ?>
    <div class="alert alert-danger text-center">
      <i class="fa fa-exclamation-triangle"></i> <?= $error; ?>
    </div>
  <?php } ?>

  <!-- Create Class Form -->
  <div class="box mb-4 p-3 border rounded shadow-sm">
    <h5 class="text-primary mb-3">Create New Class</h5>
    <form method="POST">
      <div class="row g-3">
        <div class="col-md-4">
          <label class="form-label">Program</label>
          <select name="program" required class="form-control">
            <option value="">-- Select Program --</option>
            <?php while ($row = $programs->fetch_assoc()) { ?>
              <option value="<?= htmlspecialchars($row['program']); ?>"><?= htmlspecialchars($row['program']); ?></option>
            <?php } ?>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label">Course</label>
          <select name="course" required class="form-control">
            <option value="">-- Select Course --</option>
            <?php while ($row = $courses->fetch_assoc()) { ?>
              <option value="<?= htmlspecialchars($row['course']); ?>"><?= htmlspecialchars($row['course']); ?></option>
            <?php } ?>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label">Intake</label>
          <input type="text" name="intake" class="form-control" required>
        </div>
        <div class="col-md-6">
          <label class="form-label">Title</label>
          <input type="text" name="title" class="form-control" required>
        </div>
        <div class="col-md-6">
          <label class="form-label">Start Time</label>
          <input type="datetime-local" name="start_time" class="form-control" required>
        </div>
        <div class="col-md-12 text-end">
          <button type="submit" name="create_class" class="btn btn-danger"><i class="fa fa-plus-circle"></i> Create Class</button>
        </div>
      </div>
    </form>
  </div>

  <!-- Classes Table -->
  <div class="box p-3 border rounded shadow-sm">
    <h5 class="text-secondary mb-3">All Classes</h5>

    <div class="table-responsive">
      <table class="table table-bordered table-hover align-middle">
        <thead class="table-dark">
          <tr>
            <th>#</th>
            <th>Program</th>
            <th>Course</th>
            <th>Intake</th>
            <th>Title</th>
            <th>Meet Link</th>
            <th>Start Time</th>
            <th>Posted By</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($classes->num_rows > 0) {
            $sn = 1;
            while ($row = $classes->fetch_assoc()) { ?>
              <tr>
                <td><?= $sn++; ?></td>
                <td><?= htmlspecialchars($row['program']); ?></td>
                <td><?= htmlspecialchars($row['course']); ?></td>
                <td><?= htmlspecialchars($row['intake']); ?></td>
                <td><?= htmlspecialchars($row['title']); ?></td>
                <td>
                  <?php if ($row['meet_link']) { ?>
                    <a href="<?= $row['meet_link']; ?>" target="_blank" class="btn btn-sm btn-success"><i class="fa fa-video-camera"></i> Join</a>
                  <?php } else { echo "No link"; } ?>
                </td>
                <td><?= htmlspecialchars($row['start_time']); ?></td>
                <td><?= htmlspecialchars($row['staff_email']); ?></td>
              </tr>
          <?php } } else { ?>
            <tr>
              <td colspan="8" class="text-center text-muted">No classes scheduled yet.</td>
            </tr>
          <?php } ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
</div>
</body>
</html>