<?php 
// ================= DEBUG =================
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// ==========================================

require_once(__DIR__ . "/../header.php");
require_once(__DIR__ . "/../../public/connection.php");

if(!isset($_SESSION['staff'])){
    header("Location: ../../login.php");
    exit;
}

$teacher_id = $_SESSION['staff'];

// ================= FETCH DROPDOWNS ACCORDING TO TEACHER ROLE =================

// Classes assigned via class teacher
$class_teacher_classes = $connection->query("
    SELECT DISTINCT class 
    FROM teacher_classes 
    WHERE teacher_id = '$teacher_id'
");

// Classes assigned via subject teacher
$subject_teacher_classes = $connection->query("
    SELECT DISTINCT class 
    FROM subject_teacher 
    WHERE staff_id = '$teacher_id'
");

// Merge classes into one array for dropdown
$classes_arr = [];
while($row = $class_teacher_classes->fetch_assoc()) $classes_arr[$row['class']] = $row['class'];
while($row = $subject_teacher_classes->fetch_assoc()) $classes_arr[$row['class']] = $row['class'];

// Subjects assigned via subject_teacher
$subjects = $connection->query("
    SELECT DISTINCT subject 
    FROM subject_teacher 
    WHERE staff_id = '$teacher_id'
");

// Sessions as before
$sessions = $connection->query("SELECT sessions FROM sessions ORDER BY sessions DESC");



// ================= FETCH ZOOM SETTINGS =================
$zoom = $connection->query("SELECT * FROM zoom_settings LIMIT 1")->fetch_assoc();
$zoom_account_id     = $zoom['account_id'] ?? '';
$zoom_client_id      = $zoom['api_key'] ?? '';
$zoom_client_secret  = $zoom['api_secret'] ?? '';
$zoom_enabled        = (int)($zoom['enabled'] ?? 0);

$alert_msg = "";

// ================= ZOOM TOKEN FUNCTION =================
function getZoomAccessToken($account_id, $client_id, $client_secret){
    $url = "https://zoom.us/oauth/token";
    $postFields = http_build_query([
        'grant_type' => 'account_credentials',
        'account_id' => $account_id
    ]);
    $headers = [
        "Authorization: Basic " . base64_encode($client_id . ":" . $client_secret),
        "Content-Type: application/x-www-form-urlencoded"
    ];
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postFields,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    $response = curl_exec($ch);
    if($response===false) throw new Exception("Curl Error (Token): " . curl_error($ch));
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $data = json_decode($response,true);
    if($status!==200 || empty($data['access_token'])) throw new Exception("Zoom Token Error: ".$response);
    return $data['access_token'];
}

// ================= HANDLE DELETE =================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_class'])) {
    $delete_id = intval($_POST['delete_id']);
    $stmt = $connection->prepare("DELETE FROM virtual_classes WHERE id=? AND teacher_id=?");
    $stmt->bind_param("ii", $delete_id, $teacher_id);
    $stmt->execute();
    $stmt->close();
    $alert_msg = "Class deleted successfully!";
}

// ================= HANDLE CREATE =================
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['create_class'])) {
    $class   = $_POST['class'];
    $subject = $_POST['subject'];
    $session = $_POST['session'];
    $title   = trim($_POST['title']);
    $term    = $_POST['term'] ?? 'First Term';
    $start_date = $_POST['start_date'];
    $start_time = $_POST['start_time'];
    $end_time   = $_POST['end_time'];

    $start_datetime = date("Y-m-d H:i:s", strtotime("$start_date $start_time"));
    $end_datetime   = date("Y-m-d H:i:s", strtotime("$start_date $end_time"));

    $start_url = $join_url = null;

    if($zoom_enabled && $zoom_account_id && $zoom_client_id && $zoom_client_secret){
        try {
            $access_token = getZoomAccessToken($zoom_account_id,$zoom_client_id,$zoom_client_secret);
            $payload = json_encode([
                "topic"=>$title,
                "type"=>2,
                "start_time"=>date("Y-m-d\TH:i:s",strtotime($start_datetime)),
                "duration"=>max(1,ceil((strtotime($end_datetime)-strtotime($start_datetime))/60)),
                "timezone"=>"Africa/Lagos",
                "settings"=>[
                    "host_video"=>true,
                    "participant_video"=>true,
                    "join_before_host"=>true,
                    "mute_upon_entry"=>false
                ]
            ]);
            $ch = curl_init();
            curl_setopt_array($ch,[
                CURLOPT_URL=>"https://api.zoom.us/v2/users/me/meetings",
                CURLOPT_RETURNTRANSFER=>true,
                CURLOPT_POST=>true,
                CURLOPT_POSTFIELDS=>$payload,
                CURLOPT_HTTPHEADER=>[
                    "Authorization: Bearer $access_token",
                    "Content-Type: application/json"
                ]
            ]);
            $response = curl_exec($ch);
            if($response===false) throw new Exception("Curl Error (Meeting): ".curl_error($ch));
            curl_close($ch);
            $zoom_data = json_decode($response,true);
            if(empty($zoom_data['start_url'])) throw new Exception("Zoom Meeting Error: ".$response);
            $start_url = $zoom_data['start_url'];
            $join_url  = $zoom_data['join_url'];
        } catch(Exception $e){
            die("<pre>".$e->getMessage()."</pre>");
        }
    }

    $stmt = $connection->prepare("
        INSERT INTO virtual_classes 
        (teacher_id, title, class, subjects, term, sessions, start_url, join_url, start_datetime, end_datetime)
        VALUES (?,?,?,?,?,?,?,?,?,?)
    ");
    $stmt->bind_param("isssssssss",$teacher_id,$title,$class,$subject,$term,$session,$start_url,$join_url,$start_datetime,$end_datetime);
    $stmt->execute();
    $stmt->close();

    $alert_msg = "Class created successfully!";
}

// ================= FETCH CREATED CLASSES =================
$created_classes = $connection->query("SELECT * FROM virtual_classes WHERE teacher_id='$teacher_id' ORDER BY start_datetime DESC");
?>

<div class="container mt-5">

<!-- Desktop Alert -->
<?php if($alert_msg): ?>
<div class="d-none d-lg-block alert alert-success alert-dismissible fade show shadow-lg" role="alert" id="desktopAlert">
    <?= $alert_msg ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>

<!-- Create Class Card -->
<div class="card shadow-lg mb-4">
    <div class="card-header bg-primary text-white fw-bold fs-5">Create Virtual Class</div>
    <div class="card-body">
        <form method="POST" class="row g-3">
            <input type="hidden" name="create_class">
            <div class="col-md-12">
                <label class="fw-semibold">Class Title</label>
                <input type="text" name="title" class="form-control" placeholder="Enter class title" required>
            </div>
            <div class="col-md-4">
    <label>Class</label>
    <select name="class" class="form-control" required>
        <option value="">Select Class</option>
        <?php foreach($classes_arr as $class_name): ?>
            <option value="<?= htmlspecialchars($class_name) ?>"><?= htmlspecialchars($class_name) ?></option>
        <?php endforeach; ?>
    </select>
</div>

<div class="col-md-4">
    <label>Subject</label>
    <select name="subject" class="form-control" required>
        <option value="">Select Subject</option>
        <?php while($s = $subjects->fetch_assoc()): ?>
            <option value="<?= htmlspecialchars($s['subject']) ?>"><?= htmlspecialchars($s['subject']) ?></option>
        <?php endwhile; ?>
    </select>
</div>


            <div class="col-md-4">
                <label>Session</label>
                <select name="session" class="form-control" required>
                    <option value="">Select Session</option>
                    <?php while($se = $sessions->fetch_assoc()): ?>
                        <option value="<?= htmlspecialchars($se['sessions']) ?>"><?= htmlspecialchars($se['sessions']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label>Term</label>
                <select name="term" class="form-control" required>
                    <option value="">Select Term</option>
                    <option value="First Term">First Term</option>
                    <option value="Second Term">Second Term</option>
                    <option value="Third Term">Third Term</option>
                </select>
            </div>
            <div class="col-md-4">
                <label>Start Date</label>
                <input type="date" name="start_date" class="form-control" required>
            </div>
            <div class="col-md-4">
                <label>Start Time</label>
                <input type="time" name="start_time" class="form-control" required>
            </div>
            <div class="col-md-4">
                <label>End Time</label>
                <input type="time" name="end_time" class="form-control" required>
            </div>
            <div class="col-md-12">
                <button class="btn btn-success w-100 py-2"><i class="bi bi-camera-video"></i> Create & Generate Zoom Link</button>
            </div>
        </form>
    </div>
</div>

<!-- Created Classes Table -->
<div class="card shadow-lg">
    <div class="card-header bg-secondary text-white fw-bold fs-5">Your Created Classes</div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-striped table-hover table-bordered align-middle mb-0">
                <thead class="table-dark">
                    <tr>
                        <th>Title</th>
                        <th>Class</th>
                        <th>Subject</th>
                        <th>Term</th>
                        <th>Session</th>
                        <th>Time</th> <!-- changed label -->
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if($created_classes->num_rows>0): ?>
                    <?php while($row=$created_classes->fetch_assoc()): ?>
                    <tr>
                        <td><?= htmlspecialchars($row['title']) ?></td>
                        <td><?= htmlspecialchars($row['class']) ?></td>
                        <td><?= htmlspecialchars($row['subjects']) ?></td>
                        <td><?= htmlspecialchars($row['term']) ?></td>
                        <td><?= htmlspecialchars($row['sessions']) ?></td>
                        <td>
                            <?= date("d M Y", strtotime($row['start_datetime'])) ?> 
                            (<?= date("h:i A", strtotime($row['start_datetime'])) ?> - <?= date("h:i A", strtotime($row['end_datetime'])) ?>)
                        </td>
                        <td class="d-flex gap-1">
                            <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this class?')">
                                <input type="hidden" name="delete_id" value="<?= $row['id'] ?>">
                                <button type="submit" name="delete_class" class="btn btn-sm btn-danger">Delete</button>
                            </form>
                            <button class="btn btn-sm btn-primary" onclick="navigator.clipboard.writeText('<?= $row['join_url'] ?>'); alert('Join link copied!')">Copy Link</button>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="7" class="text-center py-3">No classes created yet.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

</div>

<!-- Mobile Toast -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
  <div id="mobileToast" class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="d-flex">
      <div class="toast-body"><?= $alert_msg ?></div>
      <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
  </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function(){
    if(window.innerWidth<992){ // Mobile
        let toastEl = document.getElementById('mobileToast');
        if(toastEl && "<?= $alert_msg ?>" !== ""){
            let toast = new bootstrap.Toast(toastEl);
            toast.show();
        }
    }
});
</script>

<style>
table th, table td { vertical-align: middle !important; }
.table-hover tbody tr:hover { background-color: #f0f2f5; }
.card-header { letter-spacing: 0.5px; }
</style>
