<?php
require_once '../config/config.php';
requireLogin('company');

$database = new Database();
$db = $database->getConnection();

$company_id = $_SESSION['company_id'];
$message = '';

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    $bulk_action = $_POST['bulk_action'];
    $selected_applications = isset($_POST['selected_applications']) ? $_POST['selected_applications'] : [];
    
    if (!empty($selected_applications) && !empty($bulk_action)) {
        $success_count = 0;
        $error_count = 0;
        $skipped_count = 0;
        
        foreach ($selected_applications as $application_id) {
            $application_id = (int)$application_id;
            
            // Verify the application belongs to this company and get deadline info
            $stmt = $db->prepare("
                SELECT ja.*, j.deadline FROM job_applications ja 
                JOIN jobs j ON ja.job_id = j.id 
                WHERE ja.id = ? AND j.company_id = ?
            ");
            $stmt->execute([$application_id, $company_id]);
            $application = $stmt->fetch();
            
            if ($application) {
                $new_status = null;
                $skip_reason = null;
                
                // Check if action is allowed for this application
                switch ($bulk_action) {
                    case 'longlist':
                        if ($application['status'] !== 'applied') {
                            $skip_reason = 'Only applied candidates can be longlisted';
                        } else {
                            $new_status = 'longlisted';
                        }
                        break;
                    case 'shortlist':
                        if ($application['status'] !== 'longlisted') {
                            $skip_reason = 'Only longlisted candidates can be shortlisted';
                        } else {
                            $new_status = 'shortlisted';
                        }
                        break;
                    case 'reject':
                        if (in_array($application['status'], ['hired', 'rejected'])) {
                            $skip_reason = 'Cannot reject hired/rejected';
                        } else {
                            $new_status = 'rejected';
                        }
                        break;
                    case 'interview':
                        if ($application['status'] !== 'shortlisted') {
                            $skip_reason = 'Only shortlisted candidates can be interviewed';
                        } else {
                            $new_status = 'interviewed';
                        }
                        break;
                }
                
                if ($new_status) {
                    try {
                        $old_status = $application['status'];
                        $stmt = $db->prepare("UPDATE job_applications SET status = ? WHERE id = ?");
                        $stmt->execute([$new_status, $application_id]);
                        
                        // Send notification to candidate
                        require_once '../includes/notification_system_smtp.php';
                        $notificationSystem = new NotificationSystemSMTP($db);
                        $notificationSystem->notifyApplicationStatusChange($application_id, $old_status, $new_status);
                        
                        $success_count++;
                    } catch (PDOException $e) {
                        $error_count++;
                    }
                } else {
                    $skipped_count++;
                }
            } else {
                $error_count++;
            }
        }
        
        // Create success message
        $message = "Bulk action completed: ";
        if ($success_count > 0) {
            $message .= "$success_count updated, ";
        }
        if ($skipped_count > 0) {
            $message .= "$skipped_count skipped, ";
        }
        if ($error_count > 0) {
            $message .= "$error_count errors, ";
        }
        $message = rtrim($message, ', ');
    } else {
        $message = 'No applications selected for bulk action.';
    }
}
// Handle single status updates
else if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $application_id = (int)$_POST['application_id'];
    $action = $_POST['action'];
    
    // Verify the application belongs to this company and get deadline info
    $stmt = $db->prepare("
        SELECT ja.*, j.deadline FROM job_applications ja 
        JOIN jobs j ON ja.job_id = j.id 
        WHERE ja.id = ? AND j.company_id = ?
    ");
    $stmt->execute([$application_id, $company_id]);
    $application = $stmt->fetch();
    
    if ($application) {
        // Handle different actions with proper status flow
        switch ($action) {
            case 'longlist':
                if ($application['status'] === 'applied') {
                    $new_status = 'longlisted';
                } else {
                    $message = 'Only applied candidates can be longlisted.';
                }
                break;
            case 'shortlist':
                if ($application['status'] === 'longlisted') {
                    $new_status = 'shortlisted';
                } else {
                    $message = 'Only longlisted candidates can be shortlisted.';
                }
                break;
            case 'reject':
                $new_status = 'rejected';
                break;
            case 'interview':
                if ($application['status'] === 'shortlisted') {
                    $new_status = 'interviewed';
                } else {
                    $message = 'Only shortlisted candidates can be interviewed.';
                }
                break;
            case 'hire':
                $new_status = 'hired';
                break;
        }
        
        if (isset($new_status) && $new_status && !$message) {
            try {
                // Store old status for notification
                $old_status = $application['status'];
                
                $stmt = $db->prepare("UPDATE job_applications SET status = ? WHERE id = ?");
                $stmt->execute([$new_status, $application_id]);
                
                // Send notification to candidate
                require_once '../includes/notification_system.php';
                $notificationSystem = new NotificationSystem($db);
                $notificationSystem->notifyApplicationStatusChange($application_id, $old_status, $new_status);
                
                $message = 'Application status updated successfully! Candidate has been notified.';
            } catch (PDOException $e) {
                $message = 'Error updating application status.';
            }
        }
    }
}

// Get filter parameters
$job_filter = isset($_GET['job']) ? (int)$_GET['job'] : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$nationality_filter = isset($_GET['nationality']) ? $_GET['nationality'] : '';
$candidate_type_filter = isset($_GET['candidate_type']) ? $_GET['candidate_type'] : '';
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';
$score_filter = isset($_GET['score_range']) ? $_GET['score_range'] : '';
$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'applied_at';
$sort_order = isset($_GET['order']) && $_GET['order'] === 'asc' ? 'ASC' : 'DESC';

// Build query conditions
$where_conditions = ["j.company_id = ?"];
$params = [$company_id];

if ($job_filter) {
    $where_conditions[] = "j.id = ?";
    $params[] = $job_filter;
}

if ($status_filter) {
    $where_conditions[] = "ja.status = ?";
    $params[] = $status_filter;
}

if ($nationality_filter) {
    $where_conditions[] = "c.nationality = ?";
    $params[] = $nationality_filter;
}

if ($candidate_type_filter) {
    $where_conditions[] = "c.candidate_type = ?";
    $params[] = $candidate_type_filter;
}

if ($search) {
    $where_conditions[] = "(c.first_name LIKE ? OR c.last_name LIKE ? OR c.email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

// Get applications with survey scores
$stmt = $db->prepare("
    SELECT ja.*, j.title as job_title, j.location, j.deadline,
           c.first_name, c.last_name, c.email, c.phone, c.profile_picture,
           c.nationality, c.candidate_type,
           r.title as resume_title
    FROM job_applications ja
    JOIN jobs j ON ja.job_id = j.id
    JOIN candidates c ON ja.candidate_id = c.id
    LEFT JOIN resumes r ON ja.resume_id = r.id
    $where_clause
    ORDER BY ja.applied_at DESC
");
$stmt->execute($params);
$applications = $stmt->fetchAll();

// Calculate survey scores for each application
foreach ($applications as &$application) {
    $survey_score = calculateSurveyScore($db, $application['id']);
    $application['survey_score'] = $survey_score;
}
unset($application); // Break reference

// Filter applications by survey score range
if ($score_filter) {
    $applications = array_filter($applications, function($application) use ($score_filter) {
        $score = $application['survey_score'];
        
        switch ($score_filter) {
            case '0-30':
                return $score >= 0 && $score < 30;
            case '30-50':
                return $score >= 30 && $score < 50;
            case '50-75':
                return $score >= 50 && $score < 75;
            case '75-100':
                return $score >= 75 && $score <= 100;
            default:
                return true;
        }
    });
    
    // Re-index the array after filtering
    $applications = array_values($applications);
}

// Sort applications based on selected criteria
if ($sort_by === 'survey_score') {
    usort($applications, function($a, $b) use ($sort_order) {
        if ($sort_order === 'ASC') {
            return $a['survey_score'] <=> $b['survey_score'];
        } else {
            return $b['survey_score'] <=> $a['survey_score'];
        }
    });
}

// Function to calculate survey score based on responses and question weights
function calculateSurveyScore($db, $application_id) {
    // Get all survey responses for this application with question weights
    $stmt = $db->prepare("
        SELECT jasr.response, jsq.weight, jsq.question_type, jsq.options
        FROM job_application_survey_responses jasr
        JOIN job_survey_questions jsq ON jasr.question_id = jsq.id
        WHERE jasr.application_id = ?
    ");
    $stmt->execute([$application_id]);
    $responses = $stmt->fetchAll();
    
    if (empty($responses)) {
        return 0; // No responses, score is 0
    }
    
    $total_score = 0;
    $total_weight = 0;
    
    foreach ($responses as $response) {
        $question_score = 0;
        $weight = (float)$response['weight'];
        $total_weight += $weight;
        
        $response_text = trim(strtolower($response['response']));
        
        // 1. Handle empty responses and explicit "No" answers
        if (empty($response_text) || $response_text === 'no') {
            $question_score = 0; // 0 points for empty or "No" responses
        } else {
            // 2. Enhanced Keyword Recognition System
            $question_score = getKeywordScore($response_text, $response['question_type']);
        }
        
        // Add weighted score to total
        $total_score += ($question_score * $weight / 100);
    }
    
    // Return percentage score
    return $total_weight > 0 ? round($total_score, 1) : 0;
}

// Enhanced keyword recognition function
function getKeywordScore($response_text, $question_type) {
    // Check qualifications first, but store the best qualification score
    $qualification_scores = [
        100 => ['doctorate', 'phd', 'ph.d', 'doctoral degree', 'doctor of philosophy'],
        85 => ['masters degree', 'master\'s degree', 'masters', 'master\'s', 'mba'],
        70 => ['degree', 'bachelor degree', 'bachelor\'s degree', 'bachelor', 'bachelor\'s', 'bachelors', 'undergraduate degree', 'ba degree', 'bs degree', 'bsc degree'],
        50 => ['advanced diploma', 'higher diploma', 'national diploma', 'diploma'],
        30 => ['professional certificate', 'certificate', 'certification', 'certified']
    ];
    
    $best_qualification_score = 0;
    
    // Check qualifications with exact matching first
    foreach ($qualification_scores as $score => $quals) {
        foreach ($quals as $qual) {
            if (strpos($response_text, $qual) !== false) {
                $best_qualification_score = max($best_qualification_score, $score);
            }
        }
    }
    
    // Check for specific master's abbreviations
    if (preg_match('/\b(msc|ma|ms)\b/', $response_text) && !preg_match('/\b(diploma|certificate)\b/', $response_text)) {
        $best_qualification_score = max($best_qualification_score, 85);
    }
    
    // Check for bachelor's abbreviations  
    if (preg_match('/\b(ba|bs|bsc)\b/', $response_text) && !preg_match('/\b(diploma|certificate)\b/', $response_text)) {
        $best_qualification_score = max($best_qualification_score, 70);
    }
    
    // Define other keyword categories and their scores
    $keywords = [
        '100' => [ // 100% Points (Full Weight)
            'yes', 'excellent', 'very good', 'expert', 'advanced skill',
            '6+', '9+', '10+ years', '10+ years experience',
            '6 years', '7 years', '8 years', '9 years', '10 years',
            '11 years', '12 years', '13 years', '14 years', '15 years'
        ],
        '70' => [ // 70% Points
            'good', 'satisfactory', 'intermediate',
            '3-5', '4-6 years', '3-5 years', '4-6 years experience',
            '3 years', '4 years', '5 years'
        ],
        '50' => [ // 50% Points
            'fair', 'average', 'basic', 'basic knowledge',
            '1-3', '2-4 years', '1-3 years', '2-4 years experience',
            '1 year', '2 years'
        ]
    ];
    
    $best_skill_score = 0;
    
    // Check for skill/experience keywords
    foreach ($keywords as $score_percent => $keyword_list) {
        foreach ($keyword_list as $keyword) {
            if (strpos($response_text, $keyword) !== false) {
                $best_skill_score = max($best_skill_score, (int)$score_percent);
            }
        }
    }
    
    // Special handling for experience years (numeric patterns)
    if (preg_match('/(\d+)\+?\s*years?/', $response_text, $matches)) {
        $years = (int)$matches[1];
        if ($years >= 6) {
            $best_skill_score = max($best_skill_score, 100); // 6+ years experience
        } elseif ($years >= 3) {
            $best_skill_score = max($best_skill_score, 70);  // 3-5 years experience
        } elseif ($years >= 1) {
            $best_skill_score = max($best_skill_score, 50);  // 1-2 years experience
        }
    }
    
    // Return the highest score between qualifications and skills/experience
    $best_score = max($best_qualification_score, $best_skill_score);
    if ($best_score > 0) {
        return $best_score;
    }
    
    // For text fields, if response exists but no keywords match
    if ($question_type === 'text' || $question_type === 'textarea') {
        if (!empty($response_text)) {
            return 25; // Minimal points for having some response
        }
    }
    
    // For radio/select/checkbox - if answered but no keywords
    if (in_array($question_type, ['radio', 'select', 'checkbox'])) {
        if (!empty($response_text)) {
            return 50; // Default moderate score for selections
        }
    }
    
    return 0; // No match found or empty response
}

// Get company's jobs for filter
$stmt = $db->prepare("SELECT id, title FROM jobs WHERE company_id = ? ORDER BY title");
$stmt->execute([$company_id]);
$company_jobs = $stmt->fetchAll();

// Get statistics
$stats = [];
$stmt = $db->prepare("
    SELECT ja.status, COUNT(*) as count 
    FROM job_applications ja 
    JOIN jobs j ON ja.job_id = j.id 
    WHERE j.company_id = ? 
    GROUP BY ja.status
");
$stmt->execute([$company_id]);
$status_counts = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$stats['total'] = array_sum($status_counts);
$stats['applied'] = $status_counts['applied'] ?? 0;
$stats['longlisted'] = $status_counts['longlisted'] ?? 0;
$stats['shortlisted'] = $status_counts['shortlisted'] ?? 0;
$stats['interviewed'] = $status_counts['interviewed'] ?? 0;
$stats['hired'] = $status_counts['hired'] ?? 0;
$stats['rejected'] = $status_counts['rejected'] ?? 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Applications - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        #bulkActionsToolbar {
            background: #f8f9fa;
            padding: 10px 15px;
            border-radius: 6px;
            border: 1px solid #dee2e6;
        }
        
        .application-checkbox:checked + td {
            background-color: #fff3cd !important;
        }
        
        tr:has(.application-checkbox:checked) {
            background-color: #fff3cd !important;
        }
        
        #selectAll:indeterminate {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }
        
        .bulk-action-info {
            font-size: 0.875rem;
            color: #6c757d;
            margin-top: 5px;
        }
        
        .table-responsive {
            border-radius: 0.375rem;
        }
        
        .fade-in {
            animation: fadeIn 0.3s ease-in;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* Survey Score Styling */
        .survey-score-display {
            min-width: 80px;
        }
        
        .survey-score-value {
            font-weight: 600;
            font-size: 1.1em;
        }
        
        .survey-score-bar {
            width: 100%;
            height: 4px;
            background-color: #e9ecef;
            border-radius: 2px;
            margin: 2px 0;
            overflow: hidden;
        }
        
        .survey-score-fill {
            height: 100%;
            background: linear-gradient(90deg, 
                #dc3545 0%, 
                #fd7e14 25%, 
                #ffc107 50%, 
                #28a745 75%, 
                #198754 100%);
            border-radius: 2px;
            transition: width 0.3s ease;
        }
        
        .survey-score-display small {
            font-size: 0.75em;
            font-weight: 500;
        }
        
        /* Sortable header styling */
        .sortable-header {
            cursor: pointer;
            user-select: none;
            transition: all 0.2s ease;
        }
        
        .sortable-header:hover {
            background-color: rgba(0, 123, 255, 0.1);
        }
        
        .sort-indicator {
            float: right;
            margin-left: 5px;
        }
        
        /* Status badge styling */
        .badge.status-applied {
            background-color: #17a2b8;
            color: white;
        }
        
        .badge.status-longlisted {
            background-color: #6f42c1;
            color: white;
            border: 2px solid #6c757d;
            box-shadow: 0 1px 3px rgba(108, 117, 125, 0.3);
            font-weight: 600;
            position: relative;
        }
        
        .badge.status-longlisted:before {
            content: '';
            position: absolute;
            top: -1px;
            left: -1px;
            right: -1px;
            bottom: -1px;
            border: 1px solid #dee2e6;
            border-radius: inherit;
            pointer-events: none;
        }
        
        .badge.status-shortlisted {
            background-color: #ffc107;
            color: #212529;
        }
        
        .badge.status-interviewed {
            background-color: #fd7e14;
            color: white;
        }
        
        .badge.status-hired {
            background-color: #28a745;
            color: white;
        }
        
        .badge.status-rejected {
            background-color: #dc3545;
            color: white;
        }
        
        /* Nationality and Type Badge Styling */
        .badge {
            font-size: 0.8rem;
            font-weight: 500;
            padding: 0.5rem 0.75rem;
        }
        
        .badge.bg-success {
            background-color: #198754 !important;
        }
        
        .badge.bg-info {
            background-color: #0dcaf0 !important;
            color: #000 !important;
        }
        
        .badge.bg-warning {
            background-color: #ffc107 !important;
        }
        
        .badge.bg-primary {
            background-color: #0d6efd !important;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['company_name']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="fas fa-building me-2"></i>Company Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="jobs.php">
                                <i class="fas fa-briefcase me-2"></i>Manage Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="post-job.php">
                                <i class="fas fa-plus-circle me-2"></i>Post New Job
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="internal-candidates.php">
                                <i class="fas fa-user-tie me-2"></i>Internal Candidates
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="interviews.php">
                                <i class="fas fa-calendar-alt me-2"></i>Interviews
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="change-password.php">
                                <i class="fas fa-lock me-2"></i>Change Password
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-file-alt me-2"></i>Job Applications
                        </h1>
                    </div>

                    <?php if ($message): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-primary mb-1">
                                        <i class="fas fa-file-alt fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['total']; ?></h4>
                                    <small class="text-muted">Total</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-info mb-1">
                                        <i class="fas fa-clock fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['applied']; ?></h4>
                                    <small class="text-muted">New</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-secondary mb-1">
                                        <i class="fas fa-list fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['longlisted']; ?></h4>
                                    <small class="text-muted">Longlisted</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-warning mb-1">
                                        <i class="fas fa-star fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['shortlisted']; ?></h4>
                                    <small class="text-muted">Shortlisted</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-purple mb-1">
                                        <i class="fas fa-calendar-alt fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['interviewed']; ?></h4>
                                    <small class="text-muted">Interviewed</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-success mb-1">
                                        <i class="fas fa-check-circle fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['hired']; ?></h4>
                                    <small class="text-muted">Hired</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-danger mb-1">
                                        <i class="fas fa-times-circle fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['rejected']; ?></h4>
                                    <small class="text-muted">Rejected</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label for="search" class="form-label">Search Candidates</label>
                                    <input type="text" class="form-control" id="search" name="search" 
                                           placeholder="Name or email..." value="<?php echo htmlspecialchars($search); ?>">
                                </div>
                                <div class="col-md-3">
                                    <label for="job" class="form-label">Job Position</label>
                                    <select class="form-select" id="job" name="job">
                                        <option value="">All Jobs</option>
                                        <?php foreach ($company_jobs as $job): ?>
                                            <option value="<?php echo $job['id']; ?>" <?php echo $job_filter == $job['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($job['title']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="">All Status</option>
                                        <option value="applied" <?php echo $status_filter === 'applied' ? 'selected' : ''; ?>>Applied</option>
                                        <option value="longlisted" <?php echo $status_filter === 'longlisted' ? 'selected' : ''; ?>>Longlisted</option>
                                        <option value="shortlisted" <?php echo $status_filter === 'shortlisted' ? 'selected' : ''; ?>>Shortlisted</option>
                                        <option value="interviewed" <?php echo $status_filter === 'interviewed' ? 'selected' : ''; ?>>Interviewed</option>
                                        <option value="hired" <?php echo $status_filter === 'hired' ? 'selected' : ''; ?>>Hired</option>
                                        <option value="rejected" <?php echo $status_filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label for="nationality" class="form-label">Nationality</label>
                                    <select class="form-select" id="nationality" name="nationality">
                                        <option value="">All Nationalities</option>
                                        <option value="south_african" <?php echo $nationality_filter === 'south_african' ? 'selected' : ''; ?>>South African</option>
                                        <option value="foreign" <?php echo $nationality_filter === 'foreign' ? 'selected' : ''; ?>>Foreign</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label for="candidate_type" class="form-label">Candidate Type</label>
                                    <select class="form-select" id="candidate_type" name="candidate_type">
                                        <option value="">All Types</option>
                                        <option value="internal" <?php echo $candidate_type_filter === 'internal' ? 'selected' : ''; ?>>Internal</option>
                                        <option value="external" <?php echo $candidate_type_filter === 'external' ? 'selected' : ''; ?>>External</option>
                                    </select>
                                </div>
                            </form>
                            
                            <form method="GET" class="row g-3 mt-2">
                                <!-- Preserve current filters -->
                                <input type="hidden" name="search" value="<?php echo htmlspecialchars($search); ?>">
                                <input type="hidden" name="job" value="<?php echo $job_filter; ?>">
                                <input type="hidden" name="status" value="<?php echo htmlspecialchars($status_filter); ?>">
                                <input type="hidden" name="nationality" value="<?php echo htmlspecialchars($nationality_filter); ?>">
                                <input type="hidden" name="candidate_type" value="<?php echo htmlspecialchars($candidate_type_filter); ?>">
                                
                                <div class="col-md-3">
                                    <label for="score_range" class="form-label">Survey Score</label>
                                    <select class="form-select" id="score_range" name="score_range">
                                        <option value="">All Scores</option>
                                        <option value="0-30" <?php echo $score_filter === '0-30' ? 'selected' : ''; ?>>0-30% (Poor)</option>
                                        <option value="30-50" <?php echo $score_filter === '30-50' ? 'selected' : ''; ?>>30-50% (Fair)</option>
                                        <option value="50-75" <?php echo $score_filter === '50-75' ? 'selected' : ''; ?>>50-75% (Good)</option>
                                        <option value="75-100" <?php echo $score_filter === '75-100' ? 'selected' : ''; ?>>75-100% (Excellent)</option>
                                    </select>
                                </div>
                                <div class="col-md-9 d-flex align-items-end">
                                    <button type="submit" class="btn btn-primary me-2">
                                        <i class="fas fa-search me-1"></i>Filter
                                    </button>
                                    <a href="applications.php" class="btn btn-outline-secondary me-2">Clear</a>
                                    <button type="button" class="btn btn-success" onclick="exportApplications()">
                                        <i class="fas fa-file-excel me-1"></i>Export Excel
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Applications List -->
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="card-title mb-0">Applications (<?php echo count($applications); ?>)</h5>
                            
                            <!-- Bulk Actions Toolbar -->
                            <div id="bulkActionsToolbar" class="d-none">
                                <form method="POST" id="bulkActionForm">
                                    <div class="d-flex align-items-center gap-2">
                                        <span class="text-muted small" id="selectedCount">0 selected</span>
                                        <select name="bulk_action" class="form-select form-select-sm" style="width: auto;" required>
                                            <option value="">Choose action...</option>
                                            <option value="longlist" title="Move applied candidates to longlisted status">Longlist Selected</option>
                                            <option value="shortlist" title="Move longlisted candidates to shortlisted status">Shortlist Selected</option>
                                            <option value="reject" title="Reject selected applications">Reject Selected</option>
                                            <option value="interview" title="Mark shortlisted candidates as interviewed">Mark as Interviewed</option>
                                        </select>
                                        <button type="submit" class="btn btn-primary btn-sm" onclick="return confirm('Are you sure you want to perform this bulk action?')">
                                            <i class="fas fa-check me-1"></i>Apply
                                        </button>
                                        <button type="button" class="btn btn-success btn-sm" onclick="downloadSelectedApplications()" title="Download selected applications as ZIP">
                                            <i class="fas fa-download me-1"></i>ZIP
                                        </button>
                                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearSelection()">
                                            <i class="fas fa-times me-1"></i>Clear
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <?php if (empty($applications)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">No applications found.</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th width="50">
                                                    <input type="checkbox" id="selectAll" class="form-check-input" onchange="toggleSelectAll()">
                                                </th>
                                                <th>Candidate</th>
                                                <th>Nationality</th>
                                                <th>Type</th>
                                                <th>Job Position</th>
                                                <th>Applied Date</th>
                                                <th class="sortable-header" onclick="sortBy('survey_score')">
                                                    Survey Score
                                                    <?php if ($sort_by === 'survey_score'): ?>
                                                        <i class="fas fa-sort-<?php echo $sort_order === 'ASC' ? 'up' : 'down'; ?> ms-1"></i>
                                                    <?php else: ?>
                                                        <i class="fas fa-sort ms-1 text-muted"></i>
                                                    <?php endif; ?>
                                                </th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($applications as $app): ?>
                                                <tr data-app-id="<?php echo $app['id']; ?>" data-status="<?php echo $app['status']; ?>" data-deadline="<?php echo $app['deadline']; ?>">
                                                    <td>
                                                        <input type="checkbox" name="selected_applications[]" value="<?php echo $app['id']; ?>" 
                                                               class="form-check-input application-checkbox" onchange="updateBulkActions()">
                                                    </td>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="me-3">
                                                                <?php if ($app['profile_picture']): ?>
                                                                    <img src="<?php echo UPLOAD_URL . 'profiles/' . $app['profile_picture']; ?>" 
                                                                         alt="Profile" class="rounded-circle" style="width: 40px; height: 40px; object-fit: cover;">
                                                                <?php else: ?>
                                                                    <div class="rounded-circle bg-light d-flex align-items-center justify-content-center" 
                                                                         style="width: 40px; height: 40px;">
                                                                        <i class="fas fa-user text-muted"></i>
                                                                    </div>
                                                                <?php endif; ?>
                                                            </div>
                                                            <div>
                                                                <h6 class="mb-0"><?php echo htmlspecialchars($app['first_name'] . ' ' . $app['last_name']); ?></h6>
                                                                <small class="text-muted"><?php echo htmlspecialchars($app['email']); ?></small>
                                                                <?php if ($app['resume_title']): ?>
                                                                    <br><small class="text-info">
                                                                        <i class="fas fa-file-alt me-1"></i><?php echo htmlspecialchars($app['resume_title']); ?>
                                                                    </small>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="text-center">
                                                            <?php if ($app['nationality'] === 'south_african'): ?>
                                                                <span class="badge bg-success">
                                                                    <i class="fas fa-flag me-1"></i>South African
                                                                </span>
                                                            <?php else: ?>
                                                                <span class="badge bg-info">
                                                                    <i class="fas fa-globe me-1"></i>Foreign
                                                                </span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="text-center">
                                                            <?php if ($app['candidate_type'] === 'internal'): ?>
                                                                <span class="badge bg-warning text-dark">
                                                                    <i class="fas fa-user-tie me-1"></i>Internal
                                                                </span>
                                                            <?php else: ?>
                                                                <span class="badge bg-primary">
                                                                    <i class="fas fa-user me-1"></i>External
                                                                </span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-0"><?php echo htmlspecialchars($app['job_title']); ?></h6>
                                                            <small class="text-muted"><?php echo htmlspecialchars($app['location']); ?></small>
                                                        </div>
                                                    </td>
                                                    <td><?php echo formatDate($app['applied_at']); ?></td>
                                                    <td class="text-center">
                                                        <div class="survey-score-display">
                                                            <span class="survey-score-value">
                                                                <?php echo $app['survey_score']; ?>%
                                                            </span>
                                                            <div class="survey-score-bar">
                                                                <div class="survey-score-fill" style="width: <?php echo $app['survey_score']; ?>%"></div>
                                                            </div>
                                                            <small class="text-muted">
                                                                <?php 
                                                                if ($app['survey_score'] >= 80) {
                                                                    echo '<span class="text-success">Excellent</span>';
                                                                } elseif ($app['survey_score'] >= 60) {
                                                                    echo '<span class="text-warning">Good</span>';
                                                                } elseif ($app['survey_score'] >= 40) {
                                                                    echo '<span class="text-info">Average</span>';
                                                                } elseif ($app['survey_score'] > 0) {
                                                                    echo '<span class="text-danger">Poor</span>';
                                                                } else {
                                                                    echo '<span class="text-muted">No Response</span>';
                                                                }
                                                                ?>
                                                            </small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="badge status-<?php echo $app['status']; ?>">
                                                            <?php echo ucfirst($app['status']); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <a href="view-application.php?id=<?php echo $app['id']; ?>" 
                                                               class="btn btn-outline-primary" title="View Details">
                                                                <i class="fas fa-eye"></i>
                                                            </a>
                                                            
                                                            <button type="button" class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" 
                                                                    data-bs-toggle="dropdown">
                                                                <span class="visually-hidden">Toggle Dropdown</span>
                                                            </button>
                                                            
                                                            <ul class="dropdown-menu">
                                                                <?php if ($app['status'] === 'applied'): ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="application_id" value="<?php echo $app['id']; ?>">
                                                                            <input type="hidden" name="action" value="longlist">
                                                                            <button type="submit" class="dropdown-item text-secondary">
                                                                                <i class="fas fa-list me-2"></i>Longlist
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if ($app['status'] === 'longlisted'): ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="application_id" value="<?php echo $app['id']; ?>">
                                                                            <input type="hidden" name="action" value="shortlist">
                                                                            <button type="submit" class="dropdown-item text-warning">
                                                                                <i class="fas fa-star me-2"></i>Shortlist
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if (in_array($app['status'], ['longlisted', 'shortlisted'])): ?>
                                                                    <li>
                                                                        <a href="schedule-interview.php?application_id=<?php echo $app['id']; ?>" class="dropdown-item text-info">
                                                                            <i class="fas fa-calendar-plus me-2"></i>Schedule Interview
                                                                        </a>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if ($app['status'] === 'shortlisted'): ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="application_id" value="<?php echo $app['id']; ?>">
                                                                            <input type="hidden" name="action" value="interview">
                                                                            <button type="submit" class="dropdown-item text-info">
                                                                                <i class="fas fa-user-tie me-2"></i>Mark Interviewed
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if ($app['status'] === 'interviewed'): ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="application_id" value="<?php echo $app['id']; ?>">
                                                                            <input type="hidden" name="action" value="hire">
                                                                            <button type="submit" class="dropdown-item text-success">
                                                                                <i class="fas fa-check me-2"></i>Hire
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if (!in_array($app['status'], ['hired', 'rejected'])): ?>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <li>
                                                                        <form method="POST" class="d-inline" 
                                                                              onsubmit="return confirm('Are you sure you want to reject this application?')">
                                                                            <input type="hidden" name="application_id" value="<?php echo $app['id']; ?>">
                                                                            <input type="hidden" name="action" value="reject">
                                                                            <button type="submit" class="dropdown-item text-danger">
                                                                                <i class="fas fa-times me-2"></i>Reject
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <li><hr class="dropdown-divider"></li>
                                                                <li>
                                                                    <form method="POST" action="download_applications_zip.php" target="_blank" class="d-inline">
                                                                        <input type="hidden" name="selected_applications[]" value="<?php echo $app['id']; ?>">
                                                                        <button type="submit" class="dropdown-item text-info">
                                                                            <i class="fas fa-download me-2"></i>Download ZIP
                                                                        </button>
                                                                    </form>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- Hidden Export Form -->
    <form id="exportForm" method="POST" action="export_applications.php" style="display: none;">
        <input type="hidden" name="job_id" id="export_job_id">
        <input type="hidden" name="status" id="export_status">
        <input type="hidden" name="date_from" id="export_date_from">
        <input type="hidden" name="date_to" id="export_date_to">
    </form>

    <!-- Export Modal -->
    <div class="modal fade" id="exportModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-file-excel me-2 text-success"></i>
                        Export Applications to Excel
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="exportOptionsForm">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="export_job_filter" class="form-label">Filter by Job</label>
                                <select class="form-select" id="export_job_filter" name="job_id">
                                    <option value="">All Jobs</option>
                                    <?php foreach ($company_jobs as $job): ?>
                                        <option value="<?php echo $job['id']; ?>">
                                            <?php echo htmlspecialchars($job['title']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="export_status_filter" class="form-label">Filter by Status</label>
                                <select class="form-select" id="export_status_filter" name="status">
                                    <option value="">All Statuses</option>
                                    <option value="applied">Applied</option>
                                    <option value="longlisted">Longlisted</option>
                                    <option value="shortlisted">Shortlisted</option>
                                    <option value="interviewed">Interviewed</option>
                                    <option value="hired">Hired</option>
                                    <option value="rejected">Rejected</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="export_date_from_filter" class="form-label">From Date</label>
                                <input type="date" class="form-control" id="export_date_from_filter" name="date_from">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="export_date_to_filter" class="form-label">To Date</label>
                                <input type="date" class="form-control" id="export_date_to_filter" name="date_to">
                            </div>
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>Export will include:</strong> Candidate details, job information, application status, applied date, and cover letter preview.<br>
                            <small><strong>Note:</strong> The file will be generated in native Excel (.xlsx) format with professional formatting and styling.</small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" onclick="confirmExport()">
                        <i class="fas fa-download me-1"></i>Download Excel
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Bulk actions functionality
        function toggleSelectAll() {
            const selectAllCheckbox = document.getElementById('selectAll');
            const applicationCheckboxes = document.querySelectorAll('.application-checkbox');
            
            applicationCheckboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });
            
            updateBulkActions();
        }
        
        function updateBulkActions() {
            const checkedBoxes = document.querySelectorAll('.application-checkbox:checked');
            const bulkToolbar = document.getElementById('bulkActionsToolbar');
            const selectedCount = document.getElementById('selectedCount');
            const selectAllCheckbox = document.getElementById('selectAll');
            const totalCheckboxes = document.querySelectorAll('.application-checkbox');
            
            // Update selected count
            selectedCount.textContent = checkedBoxes.length + ' selected';
            
            // Show/hide bulk actions toolbar with animation
            if (checkedBoxes.length > 0) {
                if (bulkToolbar.classList.contains('d-none')) {
                    bulkToolbar.classList.remove('d-none');
                    bulkToolbar.classList.add('fade-in');
                }
            } else {
                bulkToolbar.classList.add('d-none');
                bulkToolbar.classList.remove('fade-in');
            }
            
            // Update select all checkbox state
            if (checkedBoxes.length === totalCheckboxes.length) {
                selectAllCheckbox.checked = true;
                selectAllCheckbox.indeterminate = false;
            } else if (checkedBoxes.length > 0) {
                selectAllCheckbox.checked = false;
                selectAllCheckbox.indeterminate = true;
            } else {
                selectAllCheckbox.checked = false;
                selectAllCheckbox.indeterminate = false;
            }
            
            // Add hidden inputs for selected applications to bulk form
            const bulkForm = document.getElementById('bulkActionForm');
            // Remove existing hidden inputs
            const existingInputs = bulkForm.querySelectorAll('input[name="selected_applications[]"]');
            existingInputs.forEach(input => input.remove());
            
            // Add new hidden inputs for selected applications
            checkedBoxes.forEach(checkbox => {
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'selected_applications[]';
                hiddenInput.value = checkbox.value;
                bulkForm.appendChild(hiddenInput);
            });
        }
        
        function clearSelection() {
            document.getElementById('selectAll').checked = false;
            document.querySelectorAll('.application-checkbox').forEach(checkbox => {
                checkbox.checked = false;
            });
            updateBulkActions();
        }
        
        function downloadSelectedApplications() {
            const checkedBoxes = document.querySelectorAll('.application-checkbox:checked');
            
            if (checkedBoxes.length === 0) {
                alert('Please select at least one application to download.');
                return;
            }
            
            if (confirm(`Download ${checkedBoxes.length} application(s) as ZIP file with all attachments?`)) {
                // Create and submit download form
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = 'download_applications_zip.php';
                form.target = '_blank';
                
                checkedBoxes.forEach(checkbox => {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'selected_applications[]';
                    input.value = checkbox.value;
                    form.appendChild(input);
                });
                
                document.body.appendChild(form);
                form.submit();
                document.body.removeChild(form);
                
                // Show success message
                setTimeout(function() {
                    const alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-success alert-dismissible fade show position-fixed';
                    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; width: 350px;';
                    alertDiv.innerHTML = `
                        <i class="fas fa-download me-2"></i>
                        <strong>ZIP Download Started!</strong> Your file will download shortly.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    `;
                    document.body.appendChild(alertDiv);
                    
                    // Auto-remove after 5 seconds
                    setTimeout(function() {
                        if (alertDiv.parentNode) {
                            alertDiv.remove();
                        }
                    }, 5000);
                }, 500);
            }
        }
        
        // Initialize bulk actions on page load
        document.addEventListener('DOMContentLoaded', function() {
            updateBulkActions();
        });
        function exportApplications() {
            // Set current filter values in modal
            document.getElementById('export_job_filter').value = '<?php echo $job_filter; ?>';
            document.getElementById('export_status_filter').value = '<?php echo $status_filter; ?>';
            
            // Show export modal
            new bootstrap.Modal(document.getElementById('exportModal')).show();
        }
        
        function confirmExport() {
            // Get values from modal form
            const jobId = document.getElementById('export_job_filter').value;
            const status = document.getElementById('export_status_filter').value;
            const dateFrom = document.getElementById('export_date_from_filter').value;
            const dateTo = document.getElementById('export_date_to_filter').value;
            
            // Set values in hidden form
            document.getElementById('export_job_id').value = jobId;
            document.getElementById('export_status').value = status;
            document.getElementById('export_date_from').value = dateFrom;
            document.getElementById('export_date_to').value = dateTo;
            
            // Submit export form
            document.getElementById('exportForm').submit();
            
            // Hide modal
            bootstrap.Modal.getInstance(document.getElementById('exportModal')).hide();
            
            // Show success message
            setTimeout(function() {
                const alertDiv = document.createElement('div');
                alertDiv.className = 'alert alert-success alert-dismissible fade show position-fixed';
                alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; width: 350px;';
                alertDiv.innerHTML = `
                    <i class="fas fa-check-circle me-2"></i>
                    <strong>Excel Export Started!</strong> Your file will download shortly.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                document.body.appendChild(alertDiv);
                
                // Auto-remove after 5 seconds
                setTimeout(function() {
                    alertDiv.remove();
                }, 5000);
            }, 500);
        }
        
        // Set current date as default max date
        document.getElementById('export_date_to_filter').value = new Date().toISOString().split('T')[0];
        
        // Survey score sorting functionality
        let currentSortColumn = '';
        let currentSortDirection = 'asc';
        
        function sortBy(column) {
            const table = document.querySelector('.table tbody');
            const rows = Array.from(table.querySelectorAll('tr'));
            
            // Toggle sort direction if clicking on same column
            if (currentSortColumn === column) {
                currentSortDirection = currentSortDirection === 'asc' ? 'desc' : 'asc';
            } else {
                currentSortDirection = 'asc';
                currentSortColumn = column;
            }
            
            // Sort rows based on column
            rows.sort((a, b) => {
                let aVal, bVal;
                
                if (column === 'survey_score') {
                    // Get survey score from progress bar data
                    const aScore = a.querySelector('[data-score]');
                    const bScore = b.querySelector('[data-score]');
                    aVal = aScore ? parseFloat(aScore.getAttribute('data-score')) : -1;
                    bVal = bScore ? parseFloat(bScore.getAttribute('data-score')) : -1;
                } else if (column === 'name') {
                    aVal = a.cells[1].textContent.trim().toLowerCase();
                    bVal = b.cells[1].textContent.trim().toLowerCase();
                } else if (column === 'position') {
                    aVal = a.cells[2].textContent.trim().toLowerCase();
                    bVal = b.cells[2].textContent.trim().toLowerCase();
                } else if (column === 'applied_at') {
                    aVal = new Date(a.cells[3].textContent.trim());
                    bVal = new Date(b.cells[3].textContent.trim());
                }
                
                if (currentSortDirection === 'asc') {
                    return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
                } else {
                    return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
                }
            });
            
            // Update table with sorted rows
            rows.forEach(row => table.appendChild(row));
            
            // Update sort indicators
            updateSortIndicators(column, currentSortDirection);
        }
        
        function updateSortIndicators(activeColumn, direction) {
            // Remove all existing sort indicators
            document.querySelectorAll('.sort-indicator').forEach(indicator => {
                indicator.innerHTML = '<i class="fas fa-sort text-muted"></i>';
            });
            
            // Add sort indicator to active column
            const activeIndicator = document.querySelector(`[onclick="sortBy('${activeColumn}')"] .sort-indicator`);
            if (activeIndicator) {
                const icon = direction === 'asc' ? 'fa-sort-up' : 'fa-sort-down';
                activeIndicator.innerHTML = `<i class="fas ${icon} text-primary"></i>`;
            }
        }
    </script>
</body>
</html>