<?php
/**
 * Get Violations API
 * Returns all violations for a specific session or all violations
 */

require_once '../config/database.php';

header('Content-Type: application/json');

// Handle CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

try {
    $session_token = $_GET['session_token'] ?? null;
    
    if ($session_token) {
        // Get violations for specific session
        $stmt = $pdo->prepare("
            SELECT 
                sv.violation_id as id,
                sv.session_token,
                sv.violation_type,
                sv.violation_details as description,
                sv.detected_at as recorded_at,
                ep.student_name,
                ep.student_email,
                ep.roll_no
            FROM security_violations sv
            LEFT JOIN exam_progress ep ON sv.session_token = ep.session_token
            WHERE sv.session_token = ?
            ORDER BY sv.detected_at DESC
        ");
        $stmt->execute([$session_token]);
    } else {
        // Get all recent violations
        $stmt = $pdo->prepare("
            SELECT 
                sv.violation_id as id,
                sv.session_token,
                sv.violation_type,
                sv.violation_details as description,
                sv.detected_at as recorded_at,
                ep.student_name,
                ep.student_email,
                ep.roll_no
            FROM security_violations sv
            LEFT JOIN exam_progress ep ON sv.session_token = ep.session_token
            ORDER BY sv.detected_at DESC
            LIMIT 100
        ");
        $stmt->execute();
    }
    
    $violations = $stmt->fetchAll();
    
    // Format timestamps
    $formatted = array_map(function($v) {
        return [
            'id' => $v['id'],
            'session_token' => $v['session_token'],
            'type' => $v['violation_type'],
            'description' => $v['description'] ?? '',
            'recorded_at' => $v['recorded_at'],
            'student' => [
                'name' => $v['student_name'] ?? 'Unknown',
                'email' => $v['student_email'] ?? '',
                'roll_no' => $v['roll_no'] ?? ''
            ]
        ];
    }, $violations);
    
    echo json_encode([
        'success' => true,
        'count' => count($formatted),
        'violations' => $formatted
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error', 'details' => $e->getMessage()]);
}
?>

