<?php
require_once 'connection.php';

// Initialize variables
$current_step = 'registration';
$pelamar_id = null;
$error = '';
$success = '';
$time_remaining = 0;
$current_task_type = '';

// Handle new test session checks
if ($_SERVER["REQUEST_METHOD"] == "GET" && !isset($_SESSION['pelamar_id'])) {
    // Check if there's a name parameter in the URL (used for registration)
    if (isset($_GET['name']) && !empty($_GET['name'])) {
        // Check if this name already exists in the database
        $name = $_GET['name'];
        $stmt = $conn->prepare("SELECT id FROM pelamar WHERE nama_lengkap = ?");
        $stmt->bind_param("s", $name);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            // Name already exists, redirect with error
            header("Location: index.php?error=name_exists");
            exit;
        }
    }
}

// Check if the applicant already has an active session
if (isset($_SESSION['pelamar_id'])) {
    $pelamar_id = $_SESSION['pelamar_id'];
    
    // Check which step the applicant is at
    $stmt = $conn->prepare("SELECT 
        tugas1_bagian1_status, 
        tugas1_bagian2_status, 
        tugas2_status,
        tugas1_bagian1_start,
        tugas1_bagian2_start,
        tugas2_start
        FROM hasil_tes WHERE id_pelamar = ?");
    $stmt->bind_param("i", $pelamar_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        
        if ($row['tugas1_bagian1_status'] == 'Not Attempted') {
            $current_step = 'task1_part1';
            $current_task_type = 'tugas1_bagian1';
            
            // Start timer if not already started
            if (!$row['tugas1_bagian1_start'] && !isTaskInProgress($current_task_type)) {
                startTaskTimer($conn, $pelamar_id, $current_task_type);
            }
        } elseif ($row['tugas1_bagian2_status'] == 'Not Attempted') {
            $current_step = 'task1_part2';
            $current_task_type = 'tugas1_bagian2';
            
            // Start timer if not already started
            if (!$row['tugas1_bagian2_start'] && !isTaskInProgress($current_task_type)) {
                startTaskTimer($conn, $pelamar_id, $current_task_type);
            }
        } elseif ($row['tugas2_status'] == 'Not Attempted') {
            $current_step = 'task2';
            $current_task_type = 'tugas2';
            
            // Start timer if not already started
            if (!$row['tugas2_start'] && !isTaskInProgress($current_task_type)) {
                startTaskTimer($conn, $pelamar_id, $current_task_type);
            }
        } else {
            $current_step = 'thank_you';
        }
        
        // Calculate remaining time across all tasks
        if (!empty($current_task_type) && $current_step != 'thank_you') {
            $time_remaining = getRemainingTime($current_task_type);
            
            // Auto-save and move to next step if time limit exceeded for entire test
            if (isTimeLimitExceeded($current_task_type)) {
                // Handle time expiration based on current step
                if ($current_step == 'task1_part1') {
                    $code = isset($_POST['html_code']) ? $_POST['html_code'] : '';
                    $status = 'Time Expired';
                    
                    $stmt = $conn->prepare("UPDATE hasil_tes SET 
                        tugas1_bagian1_code = ?, 
                        tugas1_bagian1_status = ? 
                        WHERE id_pelamar = ?");
                    $stmt->bind_param("ssi", $code, $status, $pelamar_id);
                    $stmt->execute();
                    $stmt->close();
                    
                    endTaskTimer($conn, $pelamar_id, $current_task_type);
                    $current_step = 'task1_part2';
                    $current_task_type = 'tugas1_bagian2';
                    startTaskTimer($conn, $pelamar_id, $current_task_type);
                } 
                elseif ($current_step == 'task1_part2') {
                    $code = isset($_POST['html_code']) ? $_POST['html_code'] : '';
                    $status = 'Time Expired';
                    
                    $stmt = $conn->prepare("UPDATE hasil_tes SET 
                        tugas1_bagian2_code = ?, 
                        tugas1_bagian2_status = ? 
                        WHERE id_pelamar = ?");
                    $stmt->bind_param("ssi", $code, $status, $pelamar_id);
                    $stmt->execute();
                    $stmt->close();
                    
                    endTaskTimer($conn, $pelamar_id, $current_task_type);
                    $current_step = 'task2';
                    $current_task_type = 'tugas2';
                    startTaskTimer($conn, $pelamar_id, $current_task_type);
                }
                elseif ($current_step == 'task2') {
                    $language = isset($_POST['language']) ? $_POST['language'] : '';
                    $code = isset($_POST['program_code']) ? $_POST['program_code'] : '';
                    $status = 'Time Expired';
                    
                    $stmt = $conn->prepare("UPDATE hasil_tes SET 
                        tugas2_language = ?, 
                        tugas2_code = ?, 
                        tugas2_status = ?,
                        completed_at = NOW()
                        WHERE id_pelamar = ?");
                    $stmt->bind_param("sssi", $language, $code, $status, $pelamar_id);
                    $stmt->execute();
                    $stmt->close();
                    
                    endTaskTimer($conn, $pelamar_id, $current_task_type);
                    $current_step = 'thank_you';
                }
            }
        }
    }
    
    $stmt->close();
}

// Handle Registration Form
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register'])) {
    $nama_lengkap = $_POST['nama_lengkap'];
    $umur = $_POST['umur'];
    // Date is already in YYYY-MM-DD format from the date input
    $tanggal_kelulusan = $_POST['tanggal_kelulusan'];
    $pendidikan = $_POST['pendidikan'];
    $nama_institusi = isset($_POST['nama_institusi']) ? $_POST['nama_institusi'] : '';
    $jurusan = isset($_POST['jurusan']) ? $_POST['jurusan'] : '';
    $tingkat = isset($_POST['tingkat']) ? $_POST['tingkat'] : null;
    
    // Validate inputs
    if (empty($nama_lengkap) || empty($umur) || empty($tanggal_kelulusan) || 
        empty($pendidikan) || empty($nama_institusi) || empty($jurusan)) {
        $error = "Semua field harus diisi. Mohon periksa kembali form Anda.";
    } elseif (!is_numeric($umur) || $umur < 15 || $umur > 100) {
        $error = "Umur harus berupa angka antara 15 hingga 100.";
    } else {
        // Check if name already exists
        $stmt = $conn->prepare("SELECT id FROM pelamar WHERE nama_lengkap = ?");
        $stmt->bind_param("s", $nama_lengkap);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $error = "Nama tersebut sudah terdaftar. Silakan pilih 'Melanjutkan' jika itu Anda, atau gunakan nama lain.";
        } else {
            // Insert applicant data
            $stmt = $conn->prepare("INSERT INTO pelamar 
                (nama_lengkap, umur, tanggal_kelulusan, pendidikan, nama_institusi, jurusan, tingkat) 
                VALUES (?, ?, ?, ?, ?, ?, ?)");
            
            if (!$stmt) {
                $error = "Prepare statement error: " . $conn->error;
            } else {
                $stmt->bind_param("sisssss", $nama_lengkap, $umur, $tanggal_kelulusan, $pendidikan, $nama_institusi, $jurusan, $tingkat);
                
                if ($stmt->execute()) {
                    $pelamar_id = $stmt->insert_id;
                    $_SESSION['pelamar_id'] = $pelamar_id;
                    $_SESSION['nama_lengkap'] = $nama_lengkap;
                    
                    // Initialize test results record
                    $stmt2 = $conn->prepare("INSERT INTO hasil_tes (id_pelamar) VALUES (?)");
                    $stmt2->bind_param("i", $pelamar_id);
                    
                    if ($stmt2->execute()) {
                        $current_step = 'task1_part1';
                        $current_task_type = 'tugas1_bagian1';
                        startTaskTimer($conn, $pelamar_id, $current_task_type);
                        $success = "Pendaftaran berhasil! Anda akan segera memulai Tugas 1.";
                    } else {
                        $error = "Terjadi kesalahan saat membuat record hasil tes: " . $stmt2->error;
                    }
                    
                    $stmt2->close();
                } else {
                    $error = "Terjadi kesalahan saat menyimpan data: " . $stmt->error;
                }
                
                $stmt->close();
            }
        }
    }
}

// Handle Task 1 Part 1 (HTML/CSS Test - First Part)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_task1_part1'])) {
    $code = $_POST['html_code'];
    $status = 'Completed';
    
    $stmt = $conn->prepare("UPDATE hasil_tes SET 
        tugas1_bagian1_code = ?, 
        tugas1_bagian1_status = ? 
        WHERE id_pelamar = ?");
    $stmt->bind_param("ssi", $code, $status, $pelamar_id);
    
    if ($stmt->execute()) {
        endTaskTimer($conn, $pelamar_id, 'tugas1_bagian1');
        $current_step = 'task1_part2';
        $current_task_type = 'tugas1_bagian2';
        startTaskTimer($conn, $pelamar_id, $current_task_type);
        $success = "Kode disimpan! Lanjutkan ke bagian berikutnya.";
    } else {
        $error = "Terjadi kesalahan saat menyimpan kode. Silakan coba lagi.";
    }
    
    $stmt->close();
}

// Handle Fail for Task 1 Part 1
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['fail_task1_part1'])) {
    $code = isset($_POST['html_code']) ? $_POST['html_code'] : '';
    $status = 'Failed';
    
    $stmt = $conn->prepare("UPDATE hasil_tes SET 
        tugas1_bagian1_code = ?, 
        tugas1_bagian1_status = ? 
        WHERE id_pelamar = ?");
    $stmt->bind_param("ssi", $code, $status, $pelamar_id);
    
    if ($stmt->execute()) {
        endTaskTimer($conn, $pelamar_id, 'tugas1_bagian1');
        $current_step = 'task1_part2';
        $current_task_type = 'tugas1_bagian2';
        startTaskTimer($conn, $pelamar_id, $current_task_type);
        $success = "Tidak masalah! Mari lanjutkan ke bagian berikutnya.";
    } else {
        $error = "Terjadi kesalahan. Silakan coba lagi.";
    }
    
    $stmt->close();
}

// Handle Task 1 Part 2 (HTML/CSS Test - Second Part)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_task1_part2'])) {
    $code = $_POST['html_code'];
    $status = 'Completed';
    
    $stmt = $conn->prepare("UPDATE hasil_tes SET 
        tugas1_bagian2_code = ?, 
        tugas1_bagian2_status = ? 
        WHERE id_pelamar = ?");
    $stmt->bind_param("ssi", $code, $status, $pelamar_id);
    
    if ($stmt->execute()) {
        endTaskTimer($conn, $pelamar_id, 'tugas1_bagian2');
        $current_step = 'task2';
        $current_task_type = 'tugas2';
        startTaskTimer($conn, $pelamar_id, $current_task_type);
        $success = "Kode disimpan! Lanjutkan ke Tugas 2.";
    } else {
        $error = "Terjadi kesalahan saat menyimpan kode. Silakan coba lagi.";
    }
    
    $stmt->close();
}

// Handle Fail for Task 1 Part 2
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['fail_task1_part2'])) {
    $code = isset($_POST['html_code']) ? $_POST['html_code'] : '';
    $status = 'Failed';
    
    $stmt = $conn->prepare("UPDATE hasil_tes SET 
        tugas1_bagian2_code = ?, 
        tugas1_bagian2_status = ? 
        WHERE id_pelamar = ?");
    $stmt->bind_param("ssi", $code, $status, $pelamar_id);
    
    if ($stmt->execute()) {
        endTaskTimer($conn, $pelamar_id, 'tugas1_bagian2');
        $current_step = 'task2';
        $current_task_type = 'tugas2';
        startTaskTimer($conn, $pelamar_id, $current_task_type);
        $success = "Tidak masalah! Mari lanjutkan ke Tugas 2.";
    } else {
        $error = "Terjadi kesalahan. Silakan coba lagi.";
    }
    
    $stmt->close();
}

// Handle Task 2 (Programming Test) - MODIFIED TO FIX SUBMISSION ISSUES
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_task2'])) {
    $nama = $_POST['nama'];
    $language = $_POST['language'];
    $code = $_POST['program_code'];
    $status = 'Completed';
    $screenshot = null;
    
    // Handle screenshot upload with better error handling
    if (isset($_FILES['screenshot']) && $_FILES['screenshot']['error'] == 0) {
        $allowed = array('jpg', 'jpeg', 'png', 'gif');
        $filename = $_FILES['screenshot']['name'];
        $file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($file_ext, $allowed)) {
            $new_filename = "screenshot_" . $pelamar_id . "_" . time() . "." . $file_ext;
            $upload_path = "uploads/screenshots/";
            
            // Create directory if it doesn't exist
            if (!file_exists($upload_path)) {
                mkdir($upload_path, 0777, true);
            }
            
            if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $upload_path . $new_filename)) {
                $screenshot = $upload_path . $new_filename;
            } else {
                // Set a warning but don't prevent form submission
                $error = "Peringatan: Terjadi kesalahan saat mengupload screenshot, tetapi data akan tetap disimpan.";
                // Still proceed with submission
            }
        } else {
            // Set a warning but don't prevent form submission
            $error = "Peringatan: Format file tidak didukung. Gunakan JPG, JPEG, PNG, atau GIF. Data akan tetap disimpan.";
            // Still proceed with submission
        }
    } else {
        // Set a warning but don't prevent form submission
        $error = "Peringatan: Screenshot tidak tersedia. Data akan tetap disimpan.";
        // Still proceed with submission
    }
    
    // Always update database regardless of screenshot status
    $stmt = $conn->prepare("UPDATE hasil_tes SET 
        tugas2_language = ?, 
        tugas2_code = ?, 
        tugas2_screenshot = ?, 
        tugas2_status = ?,
        completed_at = NOW()
        WHERE id_pelamar = ?");
    $stmt->bind_param("ssssi", $language, $code, $screenshot, $status, $pelamar_id);
    
    if ($stmt->execute()) {
        endTaskTimer($conn, $pelamar_id, 'tugas2');
        $current_step = 'thank_you';  // Important: Always advance to thank you page
        $success = "Kode" . ($screenshot ? " dan screenshot" : "") . " disimpan! Tes telah selesai.";
        
        // Clear the global timer
        unset($_SESSION['global_test_start_time']);
    } else {
        $error = "Terjadi kesalahan saat menyimpan data. Silakan coba lagi.";
    }
    
    $stmt->close();
}

// Handle Fail for Task 2
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['fail_task2'])) {
    $language = isset($_POST['language']) ? $_POST['language'] : '';
    $code = isset($_POST['program_code']) ? $_POST['program_code'] : '';
    $status = 'Failed';
    
    $stmt = $conn->prepare("UPDATE hasil_tes SET 
        tugas2_language = ?, 
        tugas2_code = ?, 
        tugas2_status = ?,
        completed_at = NOW()
        WHERE id_pelamar = ?");
    $stmt->bind_param("sssi", $language, $code, $status, $pelamar_id);
    
    if ($stmt->execute()) {
        endTaskTimer($conn, $pelamar_id, 'tugas2');
        $current_step = 'thank_you';
        $success = "Tidak masalah! Tes telah selesai.";
        
        // Clear the global timer
        unset($_SESSION['global_test_start_time']);
    } else {
        $error = "Terjadi kesalahan. Silakan coba lagi.";
    }
    
    $stmt->close();
}

// Handle AJAX requests for cheat detection - MODIFIED for more selective detection
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reportCheating') {
    $pelamar_id = $_SESSION['pelamar_id'] ?? null;
    $task_type = $_POST['task_type'] ?? null;
    $cheat_type = $_POST['cheat_type'] ?? null;
    $details = $_POST['details'] ?? null;
    
    if ($pelamar_id && $task_type && $cheat_type) {
        recordCheating($conn, $pelamar_id, $task_type, $cheat_type, $details);
        
        // Return success response
        header('Content-Type: application/json');
        echo json_encode(['status' => 'success']);
        exit;
    }
    
    // Return error response
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Invalid data']);
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistem Tes Pelamar</title>
    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .container {
            width: 90%;
            max-width: 1200px;
            margin: 20px auto;
            background: white;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 5px;
        }
        h1, h2, h3 {
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
        }
        input[type="text"],
        input[type="number"],
        input[type="date"],
        select,
        textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        textarea {
            height: 200px;
            font-family: monospace;
            resize: vertical;
        }
        .btn {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn:hover {
            background-color: #45a049;
        }
        .btn-fail {
            background-color: #f44336;
        }
        .btn-fail:hover {
            background-color: #d32f2f;
        }
        .error {
            color: red;
            margin-bottom: 15px;
        }
        .success {
            color: green;
            margin-bottom: 15px;
        }
        .preview-container {
            display: flex;
            flex-direction: row;
            margin-top: 20px;
            gap: 20px;
        }
        
        @media (max-width: 768px) {
            .preview-container {
                flex-direction: column;
            }
        }
        
        .editor {
            flex: 1;
        }
        .preview-section {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        .reference-image {
            border: 1px solid #ddd;
            padding: 10px;
            background-color: white;
            margin-bottom: 15px;
            height: auto;
            min-height: 150px;
            max-height: 180px;
            overflow: hidden;
        }
        .reference-image h3 {
            font-size: 14px;
            margin-top: 0;
            margin-bottom: 8px;
        }
        .reference-image img {
            max-width: 90%;
            max-height: 140px;
            display: block;
            margin: 0 auto;
        }
        .reference-image h4 {
            font-size: 12px;
            margin-top: 5px;
            margin-bottom: 5px;
        }
        .preview {
            border: 1px solid #ddd;
            padding: 10px;
            background-color: white;
            height: auto;
            min-height: 200px;
            max-height: 250px;
            overflow: auto;
        }
        .preview-iframe {
            width: 100%;
            height: 100%;
            min-height: 180px;
            border: none;
            background-color: white;
        }
        .hidden {
            display: none;
        }
        /* Conditional fields */
        #university_fields, #highschool_fields {
            display: none;
            margin-top: 10px;
            padding: 15px;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .reference-images-row {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
        }
        .reference-image-container {
            flex: 1;
        }
        
        /* Dynamic content height adjustment */
        .auto-height-content {
            overflow: visible;
            max-height: none;
        }
        
        /* Timer styles */
        .timer-container {
            background-color: #f8f8f8;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-radius: 4px;
        }
        .timer {
            font-size: 24px;
            font-weight: bold;
            color: #333;
        }
        .timer.warning {
            color: #ff9800;
        }
        .timer.danger {
            color: #f44336;
            animation: blinking 1s infinite;
        }
        @keyframes blinking {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        /* Responsive adjustments */
        @media (max-width: 992px) {
            .container {
                width: 95%;
                padding: 15px;
            }
            .preview-container {
                flex-direction: column;
            }
            .editor, .preview-section {
                width: 100%;
            }
            .reference-image, .preview {
                max-height: none;
            }
        }
    </style>
    <script>
        // Initialize form state when document is loaded
        document.addEventListener('DOMContentLoaded', function() {
            toggleEducationFields();
            
            // Initialize preview if we're on a task page
            if (document.getElementById('preview_frame')) {
                updatePreview();
                
                // Set auto height for preview containers based on content
                adjustPreviewHeight();
            }
            
            // Start timer if timer element exists
            if (document.getElementById('timer')) {
                startTimer();
            }
            
            // Initialize improved copy-paste tracking
            initCopyPasteTracking();
            
            // Initialize improved tab switching tracking
            initTabSwitchingTracking();
        });
        
        // Function to show/hide fields based on education selection
        function toggleEducationFields() {
            var education = document.getElementById('pendidikan');
            if (!education) return;
            
            var educationValue = education.value;
            var uniFields = document.getElementById('university_fields');
            var highFields = document.getElementById('highschool_fields');
            
            if (educationValue === 'Universitas') {
                uniFields.style.display = 'block';
                highFields.style.display = 'none';
                
                // Enable university fields and disable high school fields
                enableFieldset('nama_universitas', 'jurusan_universitas', 'tingkat');
                disableFieldset('nama_sekolah', 'jurusan_sekolah');
            } else if (educationValue === 'SMA/SMK') {
                uniFields.style.display = 'none';
                highFields.style.display = 'block';
                
                // Enable high school fields and disable university fields
                enableFieldset('nama_sekolah', 'jurusan_sekolah');
                disableFieldset('nama_universitas', 'jurusan_universitas', 'tingkat');
            } else {
                uniFields.style.display = 'none';
                highFields.style.display = 'none';
                
                // Disable all conditional fields
                disableFieldset('nama_universitas', 'jurusan_universitas', 'tingkat');
                disableFieldset('nama_sekolah', 'jurusan_sekolah');
            }
        }
        
        // Function to enable form fields
        function enableFieldset(...ids) {
            ids.forEach(id => {
                var field = document.getElementById(id);
                if (field) {
                    field.disabled = false;
                    field.required = true;
                }
            });
        }
        
        // Function to disable form fields
        function disableFieldset(...ids) {
            ids.forEach(id => {
                var field = document.getElementById(id);
                if (field) {
                    field.disabled = true;
                    field.required = false;
                }
            });
        }
        
        // Function to update the preview for HTML/CSS tasks
        function updatePreview() {
            var code = document.getElementById('html_code').value;
            var previewFrame = document.getElementById('preview_frame');
            
            if (previewFrame) {
                var preview = previewFrame.contentWindow || previewFrame.contentDocument.document || previewFrame.contentDocument;
                
                preview.document.open();
                preview.document.write(code);
                preview.document.close();
                
                // Adjust the height of the preview container based on content
                setTimeout(adjustPreviewHeight, 100);
            } else {
                // Fallback for live preview div if iframe is not available
                var livePreview = document.getElementById('live_preview');
                if (livePreview) {
                    livePreview.innerHTML = code;
                }
            }
        }
        
        // Function to adjust the height of preview containers based on content
        function adjustPreviewHeight() {
            var previewFrame = document.getElementById('preview_frame');
            if (previewFrame) {
                try {
                    var previewContent = previewFrame.contentDocument.body;
                    var previewContainer = document.querySelector('.preview');
                    
                    if (previewContent && previewContainer) {
                        var contentHeight = previewContent.scrollHeight;
                        
                        // If content is small, don't show scrollbars
                        if (contentHeight <= 200) {
                            previewContainer.style.overflow = 'hidden';
                            previewContainer.style.height = 'auto';
                            previewContainer.classList.add('auto-height-content');
                        } else {
                            previewContainer.style.overflow = 'auto';
                            previewContainer.style.height = '250px';
                            previewContainer.classList.remove('auto-height-content');
                        }
                    }
                } catch (e) {
                    console.log("Could not adjust preview height: " + e.message);
                }
            }
        }
        
        // Timer functions
        var remainingTime = <?php echo $time_remaining; ?>;
        var timerInterval;
        
        function startTimer() {
            timerInterval = setInterval(updateTimer, 1000);
            updateTimer(); // Update immediately
        }
        
        function updateTimer() {
            if (remainingTime <= 0) {
                clearInterval(timerInterval);
                
                // Auto-submit the form
                document.querySelector('form').submit();
                return;
            }
            
            var minutes = Math.floor(remainingTime / 60);
            var seconds = remainingTime % 60;
            
            // Format time as MM:SS
            var formattedTime = padZero(minutes) + ":" + padZero(seconds);
            
            var timerElement = document.getElementById('timer');
            timerElement.textContent = formattedTime;
            
            // Apply warning classes based on remaining time
            if (remainingTime <= 60) { // 1 minute or less
                timerElement.className = 'timer danger';
            } else if (remainingTime <= 300) { // 5 minutes or less
                timerElement.className = 'timer warning';
            } else {
                timerElement.className = 'timer';
            }
            
            remainingTime--;
        }
        
        function padZero(num) {
            return (num < 10) ? "0" + num : num;
        }
        
        // IMPROVED COPY-PASTE TRACKING - Only detects external copy-paste operations
        var copyPasteCount = 0;
        var lastPastedText = '';
        var currentTaskType = '<?php echo $current_task_type; ?>';
        var isInternalCopyPaste = false;
        var lastInternalCopyContent = '';
        
        function initCopyPasteTracking() {
            if (!currentTaskType) return;
            
            // Get all text areas in the page
            const textAreas = document.querySelectorAll('textarea');
            
            // First, set up listeners for internal copying
            textAreas.forEach(textArea => {
                // Monitor when the user selects text within our text areas (to track internal copying)
                textArea.addEventListener('select', function() {
                    lastInternalCopyContent = window.getSelection().toString();
                });
                
                // Monitor when user focuses in our text areas (to track context for paste operations)
                textArea.addEventListener('focus', function() {
                    isInternalCopyPaste = true;
                });
                
                // Monitor when user focuses out of our text areas
                textArea.addEventListener('blur', function() {
                    isInternalCopyPaste = false;
                });
            });
            
            // Track copying globally
            document.addEventListener('copy', function(e) {
                // Only count external copying, not internal
                if (!isInternalCopyPaste) {
                    copyPasteCount++;
                    console.log('External copy event detected', copyPasteCount);
                    checkCopyPasteLimit();
                }
            });
            
            // Track pasting
            document.addEventListener('paste', function(e) {
                // Get pasted text if possible
                if (e.clipboardData && e.clipboardData.getData) {
                    var pastedText = e.clipboardData.getData('text/plain');
                    
                    // Check if this paste matches our last known internal copy
                    // If it does, it's likely an internal paste operation
                    if (pastedText === lastInternalCopyContent) {
                        console.log('Internal paste detected, not counting');
                        return; // Don't count internal pastes
                    }
                    
                    // It's an external paste
                    copyPasteCount++;
                    console.log('External paste event detected', copyPasteCount);
                    lastPastedText = pastedText;
                    
                    // If pasted text is very large, report it as potential code copying
                    if (pastedText.length > 200) {
                        reportCheatingToServer('Large Code Paste', 'External paste with length: ' + pastedText.length);
                    }
                    
                    checkCopyPasteLimit();
                }
            });
        }
        
        function checkCopyPasteLimit() {
            // Only report after several external copy-paste operations
            if (copyPasteCount > 10) {
                // Report excessive copy-paste as potential cheating
                reportCheatingToServer('Excessive Copy Paste', 'More than 10 external copy-paste operations detected');
            }
        }
        
        // IMPROVED TAB SWITCHING TRACKING - Only detect extended absences or visits to specific sites
        var wasHidden = false;
        var tabSwitchCount = 0;
        var tabHiddenTime = 0;
        
        // Lists of suspicious websites
        var aiWebsites = [
            'claude.ai',
            'chat.openai.com', 
            'gemini.google.com',
            'perplexity.ai',
            'bard.google.com',
            'chatgpt.com',
            'openai.com',
            'bing.com/chat',
            'phind.com',
            'anthropic.com'
        ];
        
        // List of social media to monitor
        var socialMedia = [
            'facebook.com',
            'twitter.com',
            'instagram.com',
            'tiktok.com',
            'linkedin.com',
            'reddit.com',
            'pinterest.com',
            'snapchat.com',
            'whatsapp.com',
            'telegram.org'
        ];
        
        function initTabSwitchingTracking() {
            if (!currentTaskType) return;
            
            // Track visibility changes (tab switching or minimizing)
            document.addEventListener('visibilitychange', function() {
                if (document.visibilityState === 'hidden') {
                    // Tab is now hidden
                    wasHidden = true;
                    tabSwitchCount++;
                    
                    // Record timestamp when tab was hidden
                    tabHiddenTime = new Date().getTime();
                    
                    // Don't immediately report tab switching as cheating
                    console.log('Tab hidden at: ', new Date().toISOString());
                    
                } else if (document.visibilityState === 'visible' && wasHidden) {
                    // Tab is now visible again after being hidden
                    wasHidden = false;
                    
                    // Calculate how long the tab was hidden
                    if (tabHiddenTime > 0) {
                        var hiddenDuration = (new Date().getTime() - tabHiddenTime) / 1000; // in seconds
                        console.log('Tab was hidden for', hiddenDuration, 'seconds');
                        
                        // Only report extended absences (over 30 seconds)
                        if (hiddenDuration > 10) {
                            reportCheatingToServer('Tab Hidden', 'Tab hidden for ' + hiddenDuration + ' seconds');
                        }
                    }
                }
            });
        }
        
        // Function to report cheating to the server - more selective now
        function reportCheatingToServer(cheatType, details) {
            // Create form data
            const formData = new FormData();
            formData.append('action', 'reportCheating');
            formData.append('task_type', currentTaskType);
            formData.append('cheat_type', cheatType);
            formData.append('details', details);
            
            // Check if any AI website or social media is in the details
            let containsSuspiciousURL = false;
            
            // Check for AI websites
            aiWebsites.forEach(site => {
                if (details.includes(site)) {
                    containsSuspiciousURL = true;
                    formData.set('cheat_type', 'AI Usage: ' + cheatType);
                }
            });
            
            // Check for social media sites
            socialMedia.forEach(site => {
                if (details.includes(site)) {
                    containsSuspiciousURL = true;
                    formData.set('cheat_type', 'Social Media: ' + cheatType);
                }
            });
            
            // Only send the report for significant issues
            if (containsSuspiciousURL || 
                cheatType.includes('Large Code Paste') || 
                (cheatType.includes('Tab Hidden') && parseInt(details.match(/\d+/)[0]) > 30)) {
                
                // Send the data using fetch
                fetch('test_pelamar.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    console.log('Cheat report response:', data);
                })
                .catch(error => {
                    console.error('Error reporting cheating:', error);
                });
            } else {
                console.log('Not reporting minor behavior: ' + cheatType);
            }
        }
        
        // Auto-save functionality before window/tab close - improved
        window.addEventListener('beforeunload', function(e) {
            // Only report as cheating if tab was closed for a long time
            if (currentTaskType) {
                // Use navigator.sendBeacon for reliable data transmission during page unload
                const formData = new FormData();
                formData.append('action', 'reportCheating');
                formData.append('task_type', currentTaskType);
                formData.append('cheat_type', 'Tab Closed');
                formData.append('details', 'User closed or refreshed tab');
                
                navigator.sendBeacon('test_pelamar.php', formData);
            }
            
            // Don't show confirmation dialog
        });
        
        // Function to trigger 'Skip' on Task 2 without requiring fields
        function skipTask2() {
            Swal.fire({
                title: 'Yakin?',
                text: 'Jika memilih "Iya", data apa adanya akan tersimpan. Jika kosong, berarti data kosong.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Iya',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Create a hidden form for submission
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = 'test_pelamar.php';
                    
                    // Add the fail_task2 field
                    const skipInput = document.createElement('input');
                    skipInput.type = 'hidden';
                    skipInput.name = 'fail_task2';
                    skipInput.value = '1';
                    form.appendChild(skipInput);
                    
                    // Add any other necessary fields
                    const languageInput = document.createElement('input');
                    languageInput.type = 'hidden';
                    languageInput.name = 'language';
                    languageInput.value = '';
                    form.appendChild(languageInput);
                    
                    const codeInput = document.createElement('input');
                    codeInput.type = 'hidden';
                    codeInput.name = 'program_code';
                    codeInput.value = '';
                    form.appendChild(codeInput);
                    
                    // Append to body, submit, and remove
                    document.body.appendChild(form);
                    form.submit();
                    document.body.removeChild(form);
                }
            });
        }
        
        // Function to handle registration form submission with confirmation
        function submitRegistrationForm(event) {
            event.preventDefault();
            
            // Check if form is valid
            if (!document.getElementById('registration-form').checkValidity()) {
                document.getElementById('registration-form').reportValidity();
                return;
            }
            
            Swal.fire({
                title: 'Perhatian!',
                text: 'Pastikan data yang diisi pada formulir sudah benar, sebelum lanjut ke test',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Sudah',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    document.getElementById('registration-form').submit();
                }
            });
        }
        
        // Function to handle Task 1 Part 1 form submission with confirmation
        function submitTask1Part1Form(event, action) {
            event.preventDefault();
            
            if (action === 'save') {
                Swal.fire({
                    title: 'Sudah Yakin?',
                    text: 'Apakah Anda yakin ingin menyimpan dan melanjutkan?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Iya',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        document.querySelector('input[name="save_task1_part1"]').click();
                        // Form will be submitted directly
                    }
                });
            } else if (action === 'skip') {
                Swal.fire({
                    title: 'Yakin?',
                    text: 'Jika memilih "Iya", data apa adanya akan tersimpan. Jika kosong, berarti data kosong.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Iya',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        document.querySelector('input[name="fail_task1_part1"]').click();
                        // Form will be submitted directly
                    }
                });
            }
        }
        
        // Function to handle Task 1 Part 2 form submission with confirmation
        function submitTask1Part2Form(event, action) {
            event.preventDefault();
            
            if (action === 'save') {
                Swal.fire({
                    title: 'Sudah Yakin?',
                    text: 'Apakah Anda yakin ingin menyimpan dan melanjutkan?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Iya',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        document.querySelector('input[name="save_task1_part2"]').click();
                        // Form will be submitted directly
                    }
                });
            } else if (action === 'skip') {
                Swal.fire({
                    title: 'Yakin?',
                    text: 'Jika memilih "Iya", data apa adanya akan tersimpan. Jika kosong, berarti data kosong.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Iya',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        document.querySelector('input[name="fail_task1_part2"]').click();
                        // Form will be submitted directly
                    }
                });
            }
        }
        
        // FIXED: Function to handle Task 2 form submission with confirmation
function submitTask2Form(event, action) {
    event.preventDefault();
    
    if (action === 'save') {
        // Don't strictly validate form fields - allow submission even with issues
        Swal.fire({
            title: 'Sudah Yakin?',
            text: 'Apakah Anda yakin ingin menyimpan dan menyelesaikan tes?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Iya',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                // Remove the required attribute from the screenshot if it exists
                const screenshotInput = document.getElementById('screenshot');
                if (screenshotInput) {
                    screenshotInput.removeAttribute('required');
                }
                
                // PERBAIKAN: Gunakan click() pada elemen submit tersembunyi
                // alih-alih memanggil submit() langsung pada form
                document.querySelector('input[name="save_task2"]').click();
            }
        });
    }
    // Skip handled by skipTask2() function
}
    </script>
</head>
<body>
    <div class="container">
        <h1>Sistem Tes Pelamar</h1>
        
        <?php if (!empty($error)): ?>
            <div class="error"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <?php if (!empty($success)): ?>
            <div class="success"><?php echo $success; ?></div>
            
            <?php if ($current_step == 'task1_part2' && strpos($success, 'Kode disimpan!') !== false): ?>
                <script>
                    Swal.fire({
                        title: 'Berhasil!',
                        text: 'Berhasil Tersimpan, lanjut test Tugas 1 lanjutan',
                        icon: 'success',
                        confirmButtonColor: '#3085d6',
                        confirmButtonText: 'OK'
                    });
                </script>
            <?php elseif ($current_step == 'task2' && strpos($success, 'Kode disimpan!') !== false): ?>
                <script>
                    Swal.fire({
                        title: 'Berhasil!',
                        text: 'Berhasil Tersimpan, lanjut test Tugas 2',
                        icon: 'success',
                        confirmButtonColor: '#3085d6',
                        confirmButtonText: 'OK'
                    });
                </script>
            <?php elseif ($current_step == 'thank_you' && strpos($success, 'Kode') !== false): ?>
                <script>
                    Swal.fire({
                        title: 'Berhasil!',
                        text: 'Berhasil Tersimpan, dan sudah selesai',
                        icon: 'success',
                        confirmButtonColor: '#3085d6',
                        confirmButtonText: 'OK'
                    });
                </script>
            <?php endif; ?>
        <?php endif; ?>
        
        <?php if ($current_step == 'registration' && !isset($_SESSION['pelamar_id'])): ?>
            <!-- Registration Form -->
            <h2>Form Pendaftaran Pelamar</h2>
            <form id="registration-form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" onsubmit="submitRegistrationForm(event)">
                <div class="form-group">
                    <label for="nama_lengkap">Nama Lengkap:</label>
                    <input type="text" id="nama_lengkap" name="nama_lengkap" required>
                </div>
                
                <div class="form-group">
                    <label for="umur">Umur:</label>
                    <input type="number" id="umur" name="umur" min="15" max="100" required>
                </div>
                
                <div class="form-group">
                    <label for="tanggal_kelulusan">Tanggal Kelulusan:</label>
                    <input type="date" id="tanggal_kelulusan" name="tanggal_kelulusan" required>
                </div>
                
                <div class="form-group">
                    <label for="pendidikan">Asal Pendidikan:</label>
                    <select id="pendidikan" name="pendidikan" onchange="toggleEducationFields()" required>
                        <option value="">-- Pilih Pendidikan --</option>
                        <option value="Universitas">Universitas</option>
                        <option value="SMA/SMK">SMA/SMK</option>
                    </select>
                </div>
                
                <!-- University Fields (shown conditionally) -->
                <div id="university_fields">
                    <div class="form-group">
                        <label for="nama_universitas">Nama Universitas:</label>
                        <input type="text" id="nama_universitas" name="nama_institusi" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="jurusan_universitas">Jurusan:</label>
                        <input type="text" id="jurusan_universitas" name="jurusan" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="tingkat">Tingkat:</label>
                        <select id="tingkat" name="tingkat" required>
                            <option value="D3">D3</option>
                            <option value="S1">S1</option>
                        </select>
                    </div>
                </div>
                
                <!-- High School Fields (shown conditionally) -->
                <div id="highschool_fields">
                    <div class="form-group">
                        <label for="nama_sekolah">Nama Sekolah:</label>
                        <input type="text" id="nama_sekolah" name="nama_institusi" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="jurusan_sekolah">Jurusan:</label>
                        <input type="text" id="jurusan_sekolah" name="jurusan" required>
                    </div>
                </div>
                
                <button type="submit" class="btn">Mulai</button>
                <input type="hidden" name="register" value="1">
            </form>
        
        <?php elseif ($current_step == 'registration' && isset($_SESSION['pelamar_id'])): ?>
            <!-- Resume Session Form (if browser was closed) -->
            <h2>Lanjutkan Sesi Tes</h2>
            <p>Sepertinya Anda telah keluar dari browser. Silakan masukkan nama dan umur Anda untuk melanjutkan tes.</p>
            
            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                <div class="form-group">
                    <label for="resume_nama">Nama Lengkap:</label>
                    <input type="text" id="resume_nama" name="nama_lengkap" required>
                </div>
                
                <div class="form-group">
                    <label for="resume_umur">Umur:</label>
                    <input type="number" id="resume_umur" name="umur" min="15" max="100" required>
                </div>
                
                <button type="submit" name="resume_session" class="btn">Lanjutkan Tes</button>
            </form>
        
        <?php elseif ($current_step == 'task1_part1'): ?>
            <!-- Task 1 Part 1 (HTML/CSS Test - First Part) -->
            <h2>Tugas 1: Tes HTML/CSS (Bagian 1)</h2>
            
            <!-- Timer display -->
            <div class="timer-container">
                <div>Waktu Tersisa:</div>
                <div id="timer" class="timer">15:00</div>
            </div>
            
            <p>Buatlah tampilan seperti pada gambar referensi dengan menggunakan HTML dan CSS.</p>
            
            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                <div class="preview-container">
                    <div class="editor">
                        <h3>Editor Kode</h3>
                        <textarea id="html_code" name="html_code" onkeyup="updatePreview()"><!DOCTYPE html>
                        <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .logo-img {
            max-width: 120px; /* Smaller width for the logo */
            height: auto;
            display: block;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <img src="logo.jpg" alt="Logo" class="logo-img">
    
</body>
</html>
</textarea>
                    </div>
                    
                    <div class="preview-section">
                        <div class="reference-image">
                            <h3>Gambar Referensi</h3>
                            <img src="images/task1_reference.jpg" alt="Referensi Tampilan">
                        </div>
                        
                        <div class="preview">
                            <h3>Preview</h3>
                            <iframe id="preview_frame" class="preview-iframe"></iframe>
                        </div>
                    </div>
                </div>
                
                <div style="margin-top: 20px;">
                    <button type="button" onclick="submitTask1Part1Form(event, 'save')" class="btn">Done</button>
                    <button type="button" onclick="submitTask1Part1Form(event, 'skip')" class="btn btn-fail">Skip</button>
                    <input type="submit" name="save_task1_part1" style="display: none;">
                    <input type="submit" name="fail_task1_part1" style="display: none;">
                </div>
            </form>
        
        <?php elseif ($current_step == 'task1_part2'): ?>
            <!-- Task 1 Part 2 (HTML/CSS Test - Second Part) -->
            <h2>Tugas 1: Tes HTML/CSS (Bagian 2)</h2>
            
            <!-- Timer display -->
            <div class="timer-container">
                <div>Waktu Tersisa:</div>
                <div id="timer" class="timer">15:00</div>
            </div>
            
            <p>Perbaiki kode template yang rusak agar sesuai dengan tampilan yang benar pada gambar referensi.</p>
            
            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                <div class="preview-container">
                    <div class="editor">
                        <h3>Editor Kode</h3>
                        <textarea id="html_code" name="html_code" onkeyup="updatePreview()">
<!-- Kode template yang rusak -->
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aplikasi Form</title>
    <style>
        body {
            font-family: sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 20px;
        }

        .container {
            background-color: white;
            padding: 20px;
            max-width: 500px;
            margin: 0 auto;
        }

        .header {
            margin-bottom: 15px;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }

        .judul {
            margin: 0;
            font-size: 20px;
        }

        .info-box {
            background-color: #e6f7ff;
            border-left: 4px solid #1890ff;
            padding: 10px;
            margin-bottom: 15px;
        }

        .daftar {
            background-color: #f9f9f9;
            padding: 10px 10px 10px 30px;
            margin: 15px 0;
        }

        .tombol-primary {
            background-color: #1890ff;
            color: white;
            border: none;
            padding: 8px 16px;
            margin-right: 10px;
        }

        .tombol-secondary {
            background-color: white;
            color: #333;
            border: 1px solid #ddd;
            padding: 8px 16px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 class="judul">Form Aplikasi</h1>
        </div>
        
        <div class="info-box">
            Penting: Silakan lengkapi semua kolom yang diperlukan.
        </div>
        
        <p>Ini adalah versi lengkap dari antarmuka formulir dengan semua elemen yang ditampilkan dengan benar.</p>
        
        <ul class="daftar">
            <li>Informasi pribadi</li>
        </ul>
        
        <div>
            <button class="tombol-primary">Kirim</button>
        </div>
    </div>
</body>
</html>
                        </textarea>
                    </div>
                    
                    <div class="preview-section">
                        <div class="reference-image">
                            <h3>Gambar Referensi</h3>
                            <div class="reference-images-row">
                                <div class="reference-image-container">
                                    <h4>Tampilan Rusak:</h4>
                                    <img src="images/task1_broken.jpg" alt="Tampilan Rusak">
                                </div>
                                <div class="reference-image-container">
                                    <h4>Tampilan yang Diinginkan:</h4>
                                    <img src="images/task1_correct.jpg" alt="Tampilan Benar">
                                </div>
                            </div>
                        </div>
                        
                        <div class="preview">
                            <h3>Preview</h3>
                            <iframe id="preview_frame" class="preview-iframe"></iframe>
                        </div>
                    </div>
                </div>
                
                <div style="margin-top: 20px;">
                    <button type="button" onclick="submitTask1Part2Form(event, 'save')" class="btn">Done</button>
                    <button type="button" onclick="submitTask1Part2Form(event, 'skip')" class="btn btn-fail">Skip</button>
                    <input type="submit" name="save_task1_part2" style="display: none;">
                    <input type="submit" name="fail_task1_part2" style="display: none;">
                </div>
            </form>
        
        <?php elseif ($current_step == 'task2'): ?>
            <!-- Task 2 (Programming Test) -->
            <h2>Tugas 2: Tes Pemrograman</h2>
            
            <!-- Timer display -->
            <div class="timer-container">
                <div>Waktu Tersisa:</div>
                <div id="timer" class="timer">15:00</div>
            </div>
            
            <p>Silakan pilih bahasa pemrograman yang Anda kuasai, tulis program, jalankan, dan upload screenshot hasil eksekusi.</p>
            
            <form id="task2-form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="nama">Nama:</label>
                    <input type="text" id="nama" name="nama" value="<?php echo isset($_SESSION['nama_lengkap']) ? $_SESSION['nama_lengkap'] : ''; ?>">
                </div>
                
                <div class="form-group">
                    <label for="language">Bahasa Pemrograman:</label>
                    <select id="language" name="language">
                        <option value="">-- Pilih Bahasa --</option>
                        <option value="Python">Python</option>
                        <option value="C++">C++</option>
                    </select>
                </div>
                
                <div id="python_info" class="hidden">
                    <p>Petunjuk untuk Python: Gunakan Google Colab atau VS Code untuk menjalankan kode.</p>
                </div>
                
                <div id="cpp_info" class="hidden">
                    <p>Petunjuk untuk C++: Gunakan VS Code dengan output di terminal.</p>
                </div>
                
                <div class="form-group">
                    <label for="program_code">Kode Program:</label>
                    <textarea id="program_code" name="program_code"></textarea>
                </div>
                
                <div class="form-group">
                    <label for="screenshot">Upload Screenshot Hasil Eksekusi (Opsional):</label>
                    <input type="file" id="screenshot" name="screenshot" accept="image/*">
                    <p><small>Format yang didukung: JPG, JPEG, PNG, GIF. Ukuran maksimal: 2MB.</small></p>
                </div>
                
                <div style="margin-top: 20px;">
                    <button type="button" onclick="submitTask2Form(event, 'save')" class="btn">Done</button>
                    <button type="button" onclick="skipTask2()" class="btn btn-fail">Skip</button>
                    <input type="submit" name="save_task2" style="display: none;">
                </div>
            </form>
            
            <script>
                // Show appropriate info based on language selection
                document.getElementById('language').addEventListener('change', function() {
                    var language = this.value;
                    var pythonInfo = document.getElementById('python_info');
                    var cppInfo = document.getElementById('cpp_info');
                    
                    if (language === 'Python') {
                        pythonInfo.classList.remove('hidden');
                        cppInfo.classList.add('hidden');
                    } else if (language === 'C++') {
                        pythonInfo.classList.add('hidden');
                        cppInfo.classList.remove('hidden');
                    } else {
                        pythonInfo.classList.add('hidden');
                        cppInfo.classList.add('hidden');
                    }
                });
            </script>
        
        <?php elseif ($current_step == 'thank_you'): ?>
            <!-- Thank You Screen -->
            <h2>Terima Kasih!</h2>
            <div style="text-align: center; margin: 30px 0;">
                <p>Terimakasih untuk pengerjaan testnya. Silahkan menunggu informasi dari Penguji dan Tim Recruitment untuk mengambil keputusan.</p>
                <p>Semua hasil tes Anda telah disimpan dalam sistem.</p>
            </div>
            
            <div style="text-align: center;">
                <a href="logout.php" class="btn">Keluar</a>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>