<?php
$pageTitle = 'Video Tasks';
require_once 'side.php';

// Handle task completion submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'complete_task') {
        $taskId = intval($_POST['task_id']);
        $proofText = sanitize($_POST['proof_text'] ?? '');
        $startTime = intval($_POST['start_time'] ?? 0);
        $currentTime = time();
        $timeTaken = $currentTime - $startTime;
        
        // Get task details
        $task = $conn->query("SELECT * FROM tasks WHERE id=$taskId AND status='active' AND task_type='video'")->fetch_assoc();
        
        if (!$task) {
            setFlash('error', 'Task not found or inactive.');
            header('Location: ' . $_SERVER['PHP_SELF']); exit;
        }
        
        // Check minimum duration
        $minDuration = $task['min_duration_seconds'] ?? 0;
        if ($minDuration > 0 && $timeTaken < $minDuration) {
            setFlash('error', 'Please spend at least ' . $minDuration . ' seconds on this task.');
            header('Location: ' . $_SERVER['PHP_SELF'] . '?task_id=' . $taskId); exit;
        }
        
        // Check if user already completed today
        $todayStart = date('Y-m-d 00:00:00');
        $todayEnd = date('Y-m-d 23:59:59');
        $completedToday = $conn->query("
            SELECT COUNT(*) as count 
            FROM task_completions 
            WHERE user_id=$userId 
            AND task_id=$taskId 
            AND created_at BETWEEN '$todayStart' AND '$todayEnd'
        ")->fetch_assoc()['count'];
        
        $dailyLimit = $task['daily_limit_per_user'] ?? 0;
        if ($dailyLimit > 0 && $completedToday >= $dailyLimit) {
            setFlash('error', 'You have reached the daily limit for this task.');
            header('Location: ' . $_SERVER['PHP_SELF']); exit;
        }
        
        // Handle screenshot upload
        $screenshotPath = null;
        if (isset($_FILES['proof_screenshot']) && $_FILES['proof_screenshot']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../uploads/task_proofs/';
            
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $fileExtension = strtolower(pathinfo($_FILES['proof_screenshot']['name'], PATHINFO_EXTENSION));
            $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            
            if (in_array($fileExtension, $allowedExtensions)) {
                if ($_FILES['proof_screenshot']['size'] <= 5 * 1024 * 1024) {
                    $fileName = 'proof_' . $userId . '_' . $taskId . '_' . time() . '.' . $fileExtension;
                    $uploadPath = $uploadDir . $fileName;
                    
                    if (move_uploaded_file($_FILES['proof_screenshot']['tmp_name'], $uploadPath)) {
                        $screenshotPath = 'uploads/task_proofs/' . $fileName;
                    }
                }
            }
        }
        
        // Check task settings for auto-approve
        $taskType = 'video';
        $taskSettingsQuery = $conn->query("SELECT * FROM task_settings WHERE task_type='$taskType'");
        $taskSettings = $taskSettingsQuery ? $taskSettingsQuery->fetch_assoc() : null;
        $autoApprove = ($taskSettings && $taskSettings['auto_approve'] == 1) ? true : false;
        
        $status = $autoApprove ? 'approved' : 'pending';
        
        // Insert completion
        $completionDate = date('Y-m-d');
        $rewardEarned = floatval($task['reward'] ?? 0);
        $adminNotes = '';
        
        $stmt = $conn->prepare("
            INSERT INTO task_completions 
            (user_id, task_id, task_type, completion_date, reward_earned, status, screenshot, admin_notes, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        $stmt->bind_param("iissdsss", $userId, $taskId, $taskType, $completionDate, $rewardEarned, $status, $screenshotPath, $adminNotes);
        
        if ($stmt->execute()) {
            $conn->query("UPDATE tasks SET total_completions = total_completions + 1 WHERE id=$taskId");
            
            if ($status === 'approved') {
                $walletCheck = $conn->query("SELECT id FROM wallets WHERE user_id=$userId");
                
                if ($walletCheck && $walletCheck->num_rows > 0) {
                    $conn->query("UPDATE wallets SET video_wallet = video_wallet + $rewardEarned, updated_at = NOW() WHERE user_id=$userId");
                } else {
                    $conn->query("INSERT INTO wallets (user_id, video_wallet, created_at, updated_at) VALUES ($userId, $rewardEarned, NOW(), NOW())");
                }
                
                setFlash('success', 'Task completed! Ksh ' . number_format($rewardEarned, 2) . ' added to your wallet.');
            } else {
                setFlash('success', 'Task submitted for review. You will be notified once approved.');
            }
        } else {
            setFlash('error', 'Failed to submit task. Please try again.');
        }
        
        header('Location: ' . $_SERVER['PHP_SELF']); exit;
    }
}

// Get tasks
$tasks = $conn->query("
    SELECT t.*,
           (SELECT COUNT(*) FROM task_completions tc 
            WHERE tc.task_id = t.id AND tc.user_id = $userId 
            AND DATE(tc.created_at) = CURDATE()) as user_completed_today
    FROM tasks t
    WHERE task_type='video' AND status='active'
    ORDER BY show_in_sidebar DESC, created_at DESC
");

// Get user statistics
$userStatsResult = $conn->query("
    SELECT 
        COUNT(*) as total_completed,
        COALESCE(SUM(CASE WHEN status='approved' THEN 1 ELSE 0 END), 0) as approved_tasks,
        COALESCE(SUM(CASE WHEN status='pending' THEN 1 ELSE 0 END), 0) as pending_tasks,
        COALESCE(SUM(CASE WHEN status='approved' THEN reward_earned ELSE 0 END), 0) as total_earnings
    FROM task_completions
    WHERE user_id=$userId AND task_type='video'
");

$userStats = $userStatsResult ? $userStatsResult->fetch_assoc() : [
    'total_completed' => 0,
    'approved_tasks' => 0,
    'pending_tasks' => 0,
    'total_earnings' => 0
];

// Get wallet balance
$walletResult = $conn->query("SELECT video_wallet FROM wallets WHERE user_id=$userId");
$walletBalance = ($walletResult && $walletResult->num_rows > 0) ? floatval($walletResult->fetch_assoc()['video_wallet']) : 0;

// Get specific task if task_id is provided
$selectedTask = null;
if (isset($_GET['task_id'])) {
    $taskId = intval($_GET['task_id']);
    $selectedTask = $conn->query("
        SELECT t.*,
               (SELECT COUNT(*) FROM task_completions tc 
                WHERE tc.task_id = t.id AND tc.user_id = $userId 
                AND DATE(tc.created_at) = CURDATE()) as user_completed_today
        FROM tasks t
        WHERE t.id=$taskId AND t.status='active' AND t.task_type='video'
    ")->fetch_assoc();
}
?>

<style>
    * { box-sizing: border-box; }
    
    .tasks-container { max-width: 1400px; margin: 0 auto; padding: 8px; }
    .tasks-header { margin-bottom: 12px; }
    
    .tasks-title {
        font-size: clamp(24px, 5vw, 32px);
        font-weight: 900;
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 12px;
    }
    
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
        gap: 6px;
        margin-bottom: 10px;
    }
    
    .stat-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        padding: 10px;
        transition: all 0.3s;
        position: relative;
        overflow: hidden;
    }
    
    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: linear-gradient(90deg, #f59e0b, #d97706);
        transform: scaleX(0);
        transition: transform 0.3s;
    }
    
    .stat-card:hover::before { transform: scaleX(1); }
    .stat-card:hover { transform: translateY(-4px); box-shadow: 0 12px 24px rgba(0,0,0,0.15); }
    
    .stat-label { font-size: 9px; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; margin-bottom: 4px; }
    .stat-value { font-size: clamp(20px, 5vw, 26px); font-weight: 900; background: linear-gradient(135deg, #f59e0b, #d97706); -webkit-background-clip: text; -webkit-text-fill-color: transparent; line-height: 1; }
    
    .wallet-box {
        background: linear-gradient(135deg, #10b981, #059669);
        border-radius: 10px;
        padding: 12px;
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .wallet-box span:first-child { font-weight: 700; color: white; font-size: 12px; }
    .wallet-box span:last-child { font-size: 18px; font-weight: 900; color: white; }
    
    .tasks-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(min(100%, 280px), 1fr));
        gap: 8px;
    }
    
    .task-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        padding: 12px;
        transition: all 0.4s;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    
    .task-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, #f59e0b, #d97706);
        transform: scaleX(0);
        transition: transform 0.4s;
    }
    
    .task-card:hover::before { transform: scaleX(1); }
    .task-card:hover { transform: translateY(-8px); box-shadow: 0 20px 40px rgba(0,0,0,0.2); border-color: #f59e0b; }
    
    .task-card-header { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 8px; }
    
    .task-icon {
        width: 40px;
        height: 40px;
        background: linear-gradient(135deg, #f59e0b, #d97706);
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 18px;
        flex-shrink: 0;
    }
    
    .task-info { flex: 1; min-width: 0; }
    .task-title { font-size: 14px; font-weight: 800; color: var(--text-primary); margin-bottom: 3px; line-height: 1.3; }
    .task-description { font-size: 11px; color: var(--text-secondary); margin-bottom: 8px; line-height: 1.4; }
    
    .task-reward {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
        padding: 10px;
        border-radius: 8px;
        text-align: center;
        margin-bottom: 8px;
    }
    
    .reward-label { font-size: 9px; opacity: 0.95; margin-bottom: 3px; font-weight: 700; text-transform: uppercase; }
    .reward-amount { font-size: 20px; font-weight: 900; }
    
    .btn-start-task {
        width: 100%;
        padding: 10px;
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
        border: none;
        border-radius: 8px;
        font-weight: 800;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.3s;
        text-transform: uppercase;
    }
    
    .btn-start-task:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(245, 158, 11, 0.4); }
    .btn-start-task:disabled { opacity: 0.5; cursor: not-allowed; }
    
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.8);
        backdrop-filter: blur(8px);
        z-index: 10000;
        overflow-y: auto;
        padding: 8px;
        animation: fadeIn 0.3s;
    }
    
    @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
    
    .modal.active { display: flex; align-items: center; justify-content: center; }
    
    .modal-content {
        background: var(--card-bg);
        border-radius: 12px;
        padding: 16px;
        max-width: 900px;
        width: 100%;
        max-height: 90vh;
        overflow-y: auto;
        animation: slideUp 0.3s;
    }
    
    @keyframes slideUp { from { transform: translateY(50px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
    
    .modal-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px; }
    .modal-title { font-size: clamp(16px, 4vw, 22px); font-weight: 900; color: var(--text-primary); flex: 1; }
    .modal-close {
        background: var(--darker-bg);
        border: none;
        width: 32px;
        height: 32px;
        border-radius: 8px;
        font-size: 16px;
        cursor: pointer;
        color: var(--text-secondary);
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s;
        flex-shrink: 0;
        margin-left: 8px;
    }
    
    .modal-close:hover { background: var(--theme-color); color: white; }
    
    .video-container {
        position: relative;
        width: 100%;
        padding-bottom: 56.25%;
        background: #000;
        border-radius: 10px;
        overflow: hidden;
        margin-bottom: 10px;
    }
    
    .video-container iframe,
    .video-container video {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border: none;
    }
    
    .instructions-box {
        background: var(--darker-bg);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        padding: 12px;
        margin-bottom: 10px;
    }
    
    .instructions-title { font-size: 13px; font-weight: 800; color: var(--text-primary); margin-bottom: 8px; }
    
    .timer-box {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
        padding: 12px;
        border-radius: 10px;
        text-align: center;
        margin-bottom: 10px;
        transition: all 0.3s;
    }
    
    .timer-box.complete {
        background: linear-gradient(135deg, #10b981, #059669);
        animation: pulse 2s infinite;
    }
    
    @keyframes pulse {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.02); }
    }
    
    .timer-label { font-size: 10px; margin-bottom: 8px; opacity: 0.95; font-weight: 700; text-transform: uppercase; }
    .timer-value { font-size: 36px; font-weight: 900; font-family: 'Courier New', monospace; line-height: 1; }
    .timer-message { font-size: 11px; margin-top: 8px; opacity: 0.95; }
    
    .form-group { margin-bottom: 12px; }
    .form-label { display: block; font-size: 12px; font-weight: 700; color: var(--text-primary); margin-bottom: 6px; }
    .form-control {
        width: 100%;
        padding: 10px;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        background: var(--darker-bg);
        color: var(--text-primary);
        font-size: 12px;
        transition: all 0.3s;
    }
    
    .form-control:focus {
        outline: none;
        border-color: #f59e0b;
        box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.1);
    }
    
    textarea.form-control { min-height: 80px; resize: vertical; }
    
    .file-upload-wrapper { position: relative; overflow: hidden; display: inline-block; width: 100%; }
    .file-upload-input { position: absolute; left: -9999px; }
    .file-upload-label {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        padding: 12px;
        background: var(--darker-bg);
        border: 2px dashed var(--border-color);
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s;
    }
    
    .file-upload-label:hover { border-color: #f59e0b; background: rgba(245, 158, 11, 0.05); }
    
    .file-preview {
        margin-top: 8px;
        padding: 10px;
        background: var(--darker-bg);
        border-radius: 8px;
        display: none;
        border: 1px solid var(--border-color);
    }
    
    .file-preview.active { display: block; }
    .file-preview img { max-width: 100%; height: auto; border-radius: 6px; margin-top: 8px; }
    
    .empty-state { grid-column: 1/-1; text-align: center; padding: 40px 16px; color: var(--text-secondary); }
    .empty-state i { font-size: 56px; opacity: 0.2; margin-bottom: 16px; }
</style>

<div class="tasks-container">
    <div class="tasks-header">
        <h1 class="tasks-title">
            <i class="fas fa-video"></i> Video Tasks
        </h1>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-label"><i class="fas fa-check-circle"></i> Completed</div>
            <div class="stat-value"><?php echo $userStats['total_completed']; ?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label"><i class="fas fa-thumbs-up"></i> Approved</div>
            <div class="stat-value"><?php echo $userStats['approved_tasks']; ?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label"><i class="fas fa-clock"></i> Pending</div>
            <div class="stat-value"><?php echo $userStats['pending_tasks']; ?></div>
        </div>
    </div>

    <div class="wallet-box">
        <span><i class="fas fa-wallet"></i> Video Wallet</span>
        <span>Ksh <?php echo number_format($walletBalance, 2); ?></span>
    </div>

    <div class="tasks-grid">
        <?php if ($tasks && $tasks->num_rows > 0): ?>
            <?php while ($task = $tasks->fetch_assoc()): 
                $canComplete = $task['user_completed_today'] < ($task['daily_limit_per_user'] ?? 1);
                $remainingCompletions = ($task['daily_limit_per_user'] ?? 1) - $task['user_completed_today'];
            ?>
                <div class="task-card" onclick="openTaskModal(<?php echo htmlspecialchars(json_encode($task)); ?>)">
                    <div class="task-card-header">
                        <div class="task-icon">
                            <i class="fas fa-video"></i>
                        </div>
                        <div class="task-info">
                            <div class="task-title"><?php echo htmlspecialchars($task['title'] ?? 'Video Task'); ?></div>
                        </div>
                    </div>
                    <div class="task-description">
                        <?php 
                        $desc = $task['description'] ?? '';
                        echo htmlspecialchars(substr($desc, 0, 120)); 
                        if (strlen($desc) > 120): ?>...<?php endif; ?>
                    </div>
                    <div class="task-reward">
                        <div class="reward-label">Reward</div>
                        <div class="reward-amount">Ksh <?php echo number_format(floatval($task['reward'] ?? 0), 2); ?></div>
                    </div>
                    <?php if ($canComplete): ?>
                        <button class="btn-start-task" onclick="event.stopPropagation(); openTaskModal(<?php echo htmlspecialchars(json_encode($task)); ?>)">
                            <i class="fas fa-play"></i> Watch Video
                            <?php if ($remainingCompletions < ($task['daily_limit_per_user'] ?? 1)): ?>
                                (<?php echo $remainingCompletions; ?> left today)
                            <?php endif; ?>
                        </button>
                    <?php else: ?>
                        <button class="btn-start-task" disabled>
                            <i class="fas fa-check"></i> Daily Limit Reached
                        </button>
                    <?php endif; ?>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-video"></i>
                <h3>No video tasks available</h3>
                <p>Check back later for new videos!</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="modal" id="taskModal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title" id="modalTaskTitle"></h2>
            <button class="modal-close" onclick="closeTaskModal()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div id="modalTaskContent"></div>
    </div>
</div>

<script>
let currentTask = null;
let taskStartTime = 0;
let timerInterval = null;
let timerComplete = false;

function getVideoEmbedCode(url) {
    if (!url) return null;
    
    // YouTube detection
    const youtubeRegex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/;
    const youtubeMatch = url.match(youtubeRegex);
    if (youtubeMatch) {
        return '<iframe src="https://www.youtube.com/embed/' + youtubeMatch[1] + '?autoplay=1" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
    }
    
    // Vimeo detection
    const vimeoRegex = /vimeo\.com\/(\d+)/;
    const vimeoMatch = url.match(vimeoRegex);
    if (vimeoMatch) {
        return '<iframe src="https://player.vimeo.com/video/' + vimeoMatch[1] + '?autoplay=1" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>';
    }
    
    // Direct video file (mp4, webm, etc.)
    if (url.match(/\.(mp4|webm|ogg)$/i)) {
        return '<video controls autoplay><source src="' + url + '" type="video/mp4">Your browser does not support video playback.</video>';
    }
    
    // Fallback - external link button
    return '<div style="display: flex; align-items: center; justify-content: center; height: 100%; background: var(--darker-bg);"><a href="' + url + '" target="_blank" style="padding: 20px 40px; background: linear-gradient(135deg, #f59e0b, #d97706); color: white; text-decoration: none; border-radius: 10px; font-weight: 800; font-size: 16px;"><i class="fas fa-external-link-alt"></i> Open Video in New Tab</a></div>';
}

function openTaskModal(task) {
    currentTask = task;
    taskStartTime = Math.floor(Date.now() / 1000);
    timerComplete = false;
    
    document.getElementById('modalTaskTitle').textContent = task.title || 'Video Task';
    
    let content = '';
    
    // Video player
    if (task.task_url) {
        const embedCode = getVideoEmbedCode(task.task_url);
        if (embedCode) {
            content += '<div class="video-container">' + embedCode + '</div>';
        }
    }
    
    // Instructions
    content += '<div class="instructions-box"><div class="instructions-title"><i class="fas fa-list-ol"></i> Instructions</div><div style="color: var(--text-secondary); line-height: 1.4; font-size: 12px;">' + (task.description || 'Watch the video completely and wait for the timer') + '</div></div>';
    
    // Timer
    if ((task.min_duration_seconds || 0) > 0) {
        content += '<div class="timer-box" id="timerBox"><div class="timer-label">Time Remaining</div><div class="timer-value" id="taskTimer">00:00</div><div class="timer-message" id="timerMessage">Please wait and watch the video...</div></div>';
        setTimeout(function() { startTimer(task.min_duration_seconds); }, 100);
    }
    
    // Form
    content += '<form method="POST" enctype="multipart/form-data" onsubmit="return validateSubmission()"><input type="hidden" name="action" value="complete_task"><input type="hidden" name="task_id" value="' + task.id + '"><input type="hidden" name="start_time" value="' + taskStartTime + '"><div class="form-group"><label class="form-label"><i class="fas fa-camera"></i> Upload Screenshot (Optional)</label><div class="file-upload-wrapper"><input type="file" name="proof_screenshot" id="proofScreenshot" class="file-upload-input" accept="image/*" onchange="previewFile(this)"><label for="proofScreenshot" class="file-upload-label"><i class="fas fa-cloud-upload-alt"></i><div><div style="font-weight: 700; font-size: 12px;">Click to upload screenshot</div><div style="font-size: 10px; color: var(--text-secondary); margin-top: 3px;">JPG, PNG, GIF (Max 5MB)</div></div></label></div><div class="file-preview" id="filePreview"><div class="file-preview-name" id="fileName"></div><img id="fileImage" alt="Preview"></div></div><div class="form-group"><label class="form-label"><i class="fas fa-file-alt"></i> Additional Information (Optional)</label><textarea name="proof_text" class="form-control" placeholder="Enter any additional details"></textarea></div><button type="submit" class="btn-start-task" id="submitBtn" ' + ((task.min_duration_seconds || 0) > 0 ? 'disabled' : '') + '><i class="fas fa-check"></i> Submit Task</button></form>';
    
    document.getElementById('modalTaskContent').innerHTML = content;
    document.getElementById('taskModal').classList.add('active');
    document.body.style.overflow = 'hidden';
}

function previewFile(input) {
    const file = input.files[0];
    const preview = document.getElementById('filePreview');
    const fileName = document.getElementById('fileName');
    const fileImage = document.getElementById('fileImage');
    
    if (file) {
        fileName.textContent = file.name;
        const reader = new FileReader();
        reader.onload = function(e) {
            fileImage.src = e.target.result;
            preview.classList.add('active');
        };
        reader.readAsDataURL(file);
    }
}

function closeTaskModal() {
    document.getElementById('taskModal').classList.remove('active');
    document.body.style.overflow = '';
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
    timerComplete = false;
}

function startTimer(minSeconds) {
    let elapsed = 0;
    const timerElement = document.getElementById('taskTimer');
    const timerMessage = document.getElementById('timerMessage');
    const timerBox = document.getElementById('timerBox');
    const submitBtn = document.getElementById('submitBtn');
    
    timerInterval = setInterval(function() {
        elapsed++;
        const remaining = Math.max(0, minSeconds - elapsed);
        const minutes = Math.floor(remaining / 60);
        const seconds = remaining % 60;
        timerElement.textContent = String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
        
        if (remaining === 0 && !timerComplete) {
            timerComplete = true;
            timerBox.classList.add('complete');
            timerMessage.textContent = '✅ Time complete! You can now submit the task.';
            submitBtn.disabled = false;
            clearInterval(timerInterval);
        }
    }, 1000);
}

function validateSubmission() {
    if (!currentTask) return false;
    
    const elapsed = Math.floor(Date.now() / 1000) - taskStartTime;
    const minSeconds = currentTask.min_duration_seconds || 0;
    
    if (minSeconds > 0 && elapsed < minSeconds) {
        alert('Please wait for the timer to complete before submitting!');
        return false;
    }
    
    return confirm('Submit this task for completion?');
}

document.getElementById('taskModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeTaskModal();
    }
});

<?php if ($selectedTask): ?>
window.addEventListener('DOMContentLoaded', function() {
    openTaskModal(<?php echo json_encode($selectedTask); ?>);
});
<?php endif; ?>
</script>

<?php include 'footer.php'; ?>