<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start output buffering
ob_start();

// Start session
session_start();

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

// Debug function
function debug_log($message) {
    error_log("[DEBUG get_cheat_log.php] " . $message);
}

try {
    debug_log("Script started");
    
    // Check if connection file exists
    if (!file_exists('connection.php')) {
        throw new Exception("connection.php file not found");
    }
    
    require_once 'connection.php';
    debug_log("Connection file included");
    
    // Check if admin is logged in (commented out for debugging)
    // if (!isset($_SESSION['admin_id'])) {
    //     debug_log("Session check failed");
    //     echo json_encode(['error' => 'Unauthorized access']);
    //     exit;
    // }
    
    // Check if ID is provided
    if (!isset($_GET['id']) || empty($_GET['id'])) {
        debug_log("ID parameter missing");
        echo json_encode(['error' => 'Applicant ID is required']);
        exit;
    }
    
    $id = intval($_GET['id']);
    debug_log("Processing ID: " . $id);
    
    // Validate ID
    if ($id <= 0) {
        debug_log("Invalid ID: " . $id);
        echo json_encode(['error' => 'Invalid applicant ID']);
        exit;
    }
    
    // Check database connection
    if (!isset($conn)) {
        throw new Exception("Database connection variable \$conn not found");
    }
    
    if ($conn->connect_error) {
        throw new Exception("Database connection failed: " . $conn->connect_error);
    }
    
    debug_log("Database connection successful");
    
    // First, check if cheat_detection table exists
    $table_check = $conn->query("SHOW TABLES LIKE 'cheat_detection'");
    if ($table_check->num_rows == 0) {
        debug_log("cheat_detection table does not exist");
        echo json_encode([]);
        exit;
    }
    
    // Check if there are any records for this user
    $count_query = "SELECT COUNT(*) as count FROM cheat_detection WHERE id_pelamar = ?";
    $count_stmt = $conn->prepare($count_query);
    if (!$count_stmt) {
        throw new Exception("Prepare count statement failed: " . $conn->error);
    }
    
    $count_stmt->bind_param("i", $id);
    $count_stmt->execute();
    $count_result = $count_stmt->get_result();
    $count_row = $count_result->fetch_assoc();
    debug_log("Found " . $count_row['count'] . " cheat records for ID " . $id);
    $count_stmt->close();
    
    // Get cheating log data
    $query = "SELECT task_type, cheat_type, details, timestamp 
              FROM cheat_detection 
              WHERE id_pelamar = ? 
              ORDER BY timestamp DESC";
    
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception("Prepare statement failed: " . $conn->error);
    }
    
    $stmt->bind_param("i", $id);
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }
    
    $result = $stmt->get_result();
    $cheat_logs = [];
    
    debug_log("Query executed successfully, processing results");
    
    while ($row = $result->fetch_assoc()) {
        // Format timestamp
        if ($row['timestamp']) {
            $row['timestamp'] = date('d/m/Y H:i:s', strtotime($row['timestamp']));
        }
        $cheat_logs[] = $row;
    }
    
    debug_log("Processed " . count($cheat_logs) . " cheat log records");
    
    // Clean up
    $stmt->close();
    
    // Clear any output that might have been generated
    ob_clean();
    
    // Return data as JSON
    echo json_encode($cheat_logs);
    debug_log("JSON response sent");
    
} catch (Exception $e) {
    // Clear any output
    ob_clean();
    
    debug_log("Exception caught: " . $e->getMessage());
    error_log("Error in get_cheat_log.php: " . $e->getMessage());
    
    echo json_encode([
        'error' => 'Database error occurred',
        'debug' => $e->getMessage(),
        'file' => __FILE__,
        'line' => $e->getLine()
    ]);
} finally {
    if (isset($conn) && $conn) {
        $conn->close();
        debug_log("Database connection closed");
    }
    
    // End output buffering
    ob_end_flush();
}
?>