<?php
/**
 * Record Violation API
 * Logs security violations for monitoring
 */

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

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

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(['error' => 'Method not allowed']));
}

$data = json_decode(file_get_contents('php://input'), true);

$session_token = $data['session_token'] ?? '';
$violation_type = $data['violation_type'] ?? 'unknown';
$description = $data['description'] ?? '';

if (empty($session_token)) {
    http_response_code(400);
    die(json_encode(['error' => 'Session token required']));
}

try {
    // Insert violation record - use JSON for violation_details as per schema
    $details_json = json_encode([
        'description' => $description,
        'timestamp' => date('Y-m-d H:i:s'),
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
    ]);
    
    $stmt = $pdo->prepare("
        INSERT INTO security_violations (
            session_token, violation_type, violation_severity, 
            violation_details, detected_at, action_taken
        ) VALUES (?, ?, 'high', ?, NOW(), 'warning')
    ");
    $stmt->execute([$session_token, $violation_type, $details_json]);
    
    $violation_id = $pdo->lastInsertId();

    // Update violation count in active_sessions
    $stmt = $pdo->prepare("
        UPDATE active_sessions 
        SET violation_count = COALESCE(violation_count, 0) + 1
        WHERE session_token = ?
    ");
    $stmt->execute([$session_token]);
    
    // Also update exam_progress status to show violation state
    $stmt = $pdo->prepare("
        UPDATE exam_progress 
        SET status = CASE 
            WHEN status = 'active' THEN 'violation'
            ELSE status 
        END
        WHERE session_token = ?
    ");
    $stmt->execute([$session_token]);

    echo json_encode([
        'success' => true,
        'message' => 'Violation recorded',
        'violation_id' => $violation_id
    ]);

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