<?php
session_start();
require_once 'db_connect.php';

$student_id = $_SESSION['student_id'] ?? null;
$class_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$student_id || !$class_id) {
    header("Location: live_classes.php");
    exit;
}

try {
    // 1. Fetch Student Data
    $stmt = $pdo->prepare("SELECT is_trial, trial_attended FROM students WHERE id = ?");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);

    // 2. Fetch Class Meeting Link (Updated column name to join_link)
    $class_stmt = $pdo->prepare("SELECT join_link FROM live_classes WHERE id = ?");
    $class_stmt->execute([$class_id]);
    $class = $class_stmt->fetch(PDO::FETCH_ASSOC);

    if ($student && $class) {
        
        // 3. TRIAL LOGIC: If student is on a trial
        if ($student['is_trial'] == 1) {
            
            if ($student['trial_attended'] < 3) {
                
                // Smart Logic: Prevent double-counting if they click the same link multiple times in one session
                $session_key = 'attended_class_' . $class_id;
                if (!isset($_SESSION[$session_key])) {
                    // Increment trial count by 1
                    $update = $pdo->prepare("UPDATE students SET trial_attended = trial_attended + 1 WHERE id = ?");
                    $update->execute([$student_id]);
                    
                    // Mark this class as attended in the current browser session
                    $_SESSION[$session_key] = true; 
                }
                
                // Redirect to actual Zoom/Meet link (Using join_link)
                header("Location: " . $class['join_link']);
                exit;
            } else {
                // If limit reached, send back with error
                header("Location: live_classes.php?error=limit_reached");
                exit;
            }
        } else {
            // REGULAR STUDENT: Direct join, no counting needed
            header("Location: " . $class['join_link']);
            exit;
        }

    } else {
        header("Location: live_classes.php");
        exit;
    }

} catch (PDOException $e) {
    die("Connection Error: " . $e->getMessage());
}
?>