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

// Start output buffering to prevent any output before JSON
ob_start();

// Start session
session_start();

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

// Debug function
function debug_log($message) {
    error_log("[DEBUG get_applicant_details.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
    if (!isset($_SESSION['admin_id'])) {
        debug_log("Session check failed. Session data: " . json_encode($_SESSION));
        echo json_encode([
            'error' => 'Unauthorized access',
            'debug' => 'Session admin_id not found',
            'session_data' => $_SESSION
        ]);
        exit;
    }
    
    debug_log("Admin session valid: " . $_SESSION['admin_id']);
    
    // 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");
    
    // Test simple query first
    $test_query = "SELECT COUNT(*) as count FROM pelamar WHERE id = ?";
    $test_stmt = $conn->prepare($test_query);
    if (!$test_stmt) {
        throw new Exception("Prepare test statement failed: " . $conn->error);
    }
    $test_stmt->bind_param("i", $id);
    $test_stmt->execute();
    $test_result = $test_stmt->get_result();
    $test_row = $test_result->fetch_assoc();
    debug_log("Found " . $test_row['count'] . " records for ID " . $id);
    $test_stmt->close();
    
    if ($test_row['count'] == 0) {
        echo json_encode(['error' => 'Applicant not found', 'id' => $id]);
        exit;
    }
    
    // Get applicant details - simplified query first
    $query = "SELECT p.nama_lengkap, p.umur, p.tanggal_kelulusan, p.pendidikan, 
              p.nama_institusi, p.jurusan, p.tingkat, p.created_at
              FROM pelamar p
              WHERE p.id = ?";
    
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception("Prepare main statement failed: " . $conn->error);
    }
    
    $stmt->bind_param("i", $id);
    if (!$stmt->execute()) {
        throw new Exception("Execute main statement failed: " . $stmt->error);
    }
    
    $result = $stmt->get_result();
    if ($result->num_rows === 0) {
        echo json_encode(['error' => 'Applicant not found in main query']);
        exit;
    }
    
    $data = $result->fetch_assoc();
    debug_log("Basic applicant data retrieved for: " . $data['nama_lengkap']);
    $stmt->close();
    
    // Get test results separately
    $test_query = "SELECT tugas1_bagian1_code, tugas1_bagian1_status,
                   tugas1_bagian2_code, tugas1_bagian2_status,
                   tugas2_language, tugas2_code, tugas2_screenshot, tugas2_status,
                   completed_at, tugas1_bagian1_start, tugas1_bagian1_end,
                   tugas1_bagian2_start, tugas1_bagian2_end,
                   tugas2_start, tugas2_end
                   FROM hasil_tes WHERE id_pelamar = ?";
    
    $test_stmt = $conn->prepare($test_query);
    if ($test_stmt) {
        $test_stmt->bind_param("i", $id);
        $test_stmt->execute();
        $test_result = $test_stmt->get_result();
        
        if ($test_result->num_rows > 0) {
            $test_data = $test_result->fetch_assoc();
            $data = array_merge($data, $test_data);
            debug_log("Test results merged");
        } else {
            debug_log("No test results found");
            // Set default values for test data
            $data['tugas1_bagian1_code'] = null;
            $data['tugas1_bagian1_status'] = 'Not Attempted';
            $data['tugas1_bagian2_code'] = null;
            $data['tugas1_bagian2_status'] = 'Not Attempted';
            $data['tugas2_code'] = null;
            $data['tugas2_status'] = 'Not Attempted';
            $data['tugas2_language'] = null;
            $data['tugas2_screenshot'] = null;
            $data['completed_at'] = null;
        }
        $test_stmt->close();
    }
    
    // Format dates
    if ($data['tanggal_kelulusan']) {
        $data['tanggal_kelulusan'] = date('d/m/Y', strtotime($data['tanggal_kelulusan']));
    }
    if ($data['created_at']) {
        $data['created_at'] = date('d/m/Y H:i', strtotime($data['created_at']));
    }
    if ($data['completed_at']) {
        $data['completed_at'] = date('d/m/Y H:i', strtotime($data['completed_at']));
    }
    
    // Format timestamp fields
    $timestamp_fields = [
        'tugas1_bagian1_start', 'tugas1_bagian1_end',
        'tugas1_bagian2_start', 'tugas1_bagian2_end',
        'tugas2_start', 'tugas2_end'
    ];
    
    foreach ($timestamp_fields as $field) {
        if (isset($data[$field]) && $data[$field]) {
            $data[$field] = date('Y-m-d H:i:s', strtotime($data[$field]));
        }
    }
    
    // Get cheating count
    $cheat_query = "SELECT COUNT(*) as cheat_count FROM cheat_detection WHERE id_pelamar = ?";
    $cheat_stmt = $conn->prepare($cheat_query);
    if ($cheat_stmt) {
        $cheat_stmt->bind_param("i", $id);
        $cheat_stmt->execute();
        $cheat_result = $cheat_stmt->get_result();
        $cheat_row = $cheat_result->fetch_assoc();
        $data['cheat_count'] = $cheat_row['cheat_count'];
        $cheat_stmt->close();
    } else {
        $data['cheat_count'] = 0;
    }
    
    debug_log("Data prepared successfully");
    
    // Clear any output that might have been generated
    ob_clean();
    
    // Return data as JSON
    echo json_encode($data);
    debug_log("JSON response sent");
    
} catch (Exception $e) {
    // Clear any output
    ob_clean();
    
    debug_log("Exception caught: " . $e->getMessage());
    error_log("Error in get_applicant_details.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();
}
?>