<?php
session_start();
include "../include/config.php";

if (!isset($_SESSION['email'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $class_id = intval($_POST['class_id']);
    $action = $_POST['action'];
    $userlogin = $_SESSION['email'];
    
    if ($action === 'join') {
        // Check if already joined
        $check = $conn->query("SELECT id FROM class_attendance WHERE class_id = $class_id AND student_email = '$userlogin' AND left_at IS NULL");
        
        if ($check->num_rows == 0) {
            $stmt = $conn->prepare("INSERT INTO class_attendance (class_id, student_email, joined_at) VALUES (?, ?, NOW())");
            $stmt->bind_param("is", $class_id, $userlogin);
            $stmt->execute();
        }
        echo json_encode(['success' => true]);
        
    } elseif ($action === 'leave') {
        $stmt = $conn->prepare("UPDATE class_attendance SET left_at = NOW(), duration_minutes = TIMESTAMPDIFF(MINUTE, joined_at, NOW()) WHERE class_id = ? AND student_email = ? AND left_at IS NULL");
        $stmt->bind_param("is", $class_id, $userlogin);
        $stmt->execute();
        echo json_encode(['success' => true]);
    }
}
?>