<?php
require_once '../config/config.php';
// Include scoring functions if they exist
if (file_exists('../includes/scoring_functions.php')) {
    require_once '../includes/scoring_functions.php';
}
requireLogin('company');

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

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

// Handle status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $application_id = (int)$_POST['application_id'];
    $action = $_POST['action'];
    
    // Enhanced logging for individual status updates
    
    // 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 application status changes with workflow requirements
        switch ($action) {
            case 'longlist':
                $new_status = 'longlisted';
                break;
            case 'shortlist':
                // Shortlisting requires longlisting first
                if ($application['status'] !== 'longlisted') {
                    $message = 'Candidates must be longlisted before they can be shortlisted.';
                } else {
                    $new_status = 'shortlisted';
                }
                break;
            case 'reject':
                $new_status = 'rejected';
                break;
            case 'interview':
                $new_status = '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);
                $notification_sent = $notificationSystem->notifyApplicationStatusChange($application_id, $old_status, $new_status);
                
                if ($notification_sent) {
                    $message = 'Application status updated successfully! Candidate has been notified.';
                } else {
                    $message = 'Application status updated successfully! (Note: Notification system may have encountered issues)';
                }
            } catch (PDOException $e) {
                $message = 'Error updating application status.';
            }
        }
    }
}

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    $bulk_action = $_POST['bulk_action'];
    $selected_applications = $_POST['selected_applications'] ?? [];
    
    // Enhanced logging for debugging
    
    if (!empty($selected_applications) && !empty($bulk_action)) {
        // Handle ZIP download separately to prevent status changes
        if ($bulk_action === 'download_zip') {
            // Log download action to prevent any status changes
            error_log("Document download initiated for applications: " . implode(',', $selected_applications) . " by company " . $company_id);
            
            $application_ids = implode(',', array_map('intval', $selected_applications));
            
            // Ensure clean redirect without any status processing
            if (headers_sent()) {
                echo '<script>window.location.href = "bulk_download.php?applications=' . $application_ids . '";</script>';
                exit;
            } else {
                header("Location: bulk_download.php?applications={$application_ids}");
                exit;
            }
        }
        
        // Only process status changes if this is NOT a download action
        if ($bulk_action !== 'download_zip') {
            $processed_count = 0;
            $error_count = 0;
            $workflow_errors = [];
            
            foreach ($selected_applications as $application_id) {
            $application_id = (int)$application_id;
            
            // Verify the application belongs to this company
            $stmt = $db->prepare("
                SELECT ja.*, j.title as job_title 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 = '';
                $workflow_error = false;
                
                switch ($bulk_action) {
                    case 'longlist':
                        $new_status = 'longlisted';
                        break;
                    case 'shortlist':
                        // Shortlisting requires longlisting first
                        if ($application['status'] !== 'longlisted') {
                            $workflow_errors[] = "Application #{$application_id} must be longlisted first";
                            $workflow_error = true;
                        } else {
                            $new_status = 'shortlisted';
                        }
                        break;
                    case 'reject':
                        $new_status = 'rejected';
                        break;
                    case 'interview':
                        $new_status = 'interviewed';
                        break;
                    case 'hire':
                        $new_status = 'hired';
                        break;
                }
                
                if (!$workflow_error && $new_status && $bulk_action !== 'download_zip') {
                    try {
                        $old_status = $application['status'];
                        
                        // Additional safety check - never update status if download action somehow reaches here
                        if ($bulk_action === 'download_zip') {
                            error_log("WARNING: Download action reached status update section - blocked");
                            continue;
                        }
                        
                        $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);
                        
                        $processed_count++;
                    } catch (PDOException $e) {
                        $error_count++;
                    }
                }
            } else {
                $error_count++;
            }
        }
        } // Close the if ($bulk_action !== 'download_zip') block
        
            // Set success/error messages
            if ($processed_count > 0) {
            $action_label = ucfirst(str_replace('_', ' ', $bulk_action));
            $message = "Successfully updated {$processed_count} application(s) to {$action_label}.";
            if ($error_count > 0) {
                $message .= " {$error_count} application(s) could not be updated.";
            }
        } else {
            $message = "No applications were updated.";
        }
        
        if (!empty($workflow_errors)) {
            $message .= "\n\nWorkflow errors:\n" . implode("\n", $workflow_errors);
        }
    } else {
        $message = 'Please select applications and choose an action.';
    }
}

// Get filter parameters
$job_filter = isset($_GET['job']) ? (int)$_GET['job'] : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$score_filter = isset($_GET['score_range']) ? $_GET['score_range'] : '';
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

// 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 ($score_filter) {
    switch ($score_filter) {
        case 'excellent':
            $where_conditions[] = "ja.total_score >= 85";
            break;
        case 'good':
            $where_conditions[] = "ja.total_score >= 70 AND ja.total_score < 85";
            break;
        case 'average':
            $where_conditions[] = "ja.total_score >= 50 AND ja.total_score < 70";
            break;
        case 'below_average':
            $where_conditions[] = "ja.total_score >= 30 AND ja.total_score < 50";
            break;
        case 'poor':
            $where_conditions[] = "ja.total_score > 0 AND ja.total_score < 30";
            break;
        case 'no_score':
            $where_conditions[] = "(ja.total_score IS NULL OR ja.total_score = 0)";
            break;
    }
}

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 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,
           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.total_score DESC, ja.applied_at DESC
");
$stmt->execute($params);
$applications = $stmt->fetchAll();

// 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>
        .bulk-actions-bar {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-bottom: 1px solid #dee2e6;
            transition: all 0.3s ease;
        }
        
        .table-primary {
            background-color: rgba(13, 110, 253, 0.1) !important;
        }
        
        .application-checkbox:checked + * {
            background-color: rgba(13, 110, 253, 0.05);
        }
        
        .bulk-action-counter {
            font-weight: 600;
            color: #0d6efd;
        }
        
        #selectAll:indeterminate {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }
        
        .status-applied { background-color: #e3f2fd; color: #1976d2; }
        .status-longlisted { background-color: #f3e5f5; color: #7b1fa2; }
        .status-shortlisted { background-color: #e8f5e8; color: #388e3c; }
        .status-interviewed { background-color: #fff3e0; color: #f57c00; }
        .status-hired { background-color: #e0f2f1; color: #00695c; }
        .status-rejected { background-color: #ffebee; color: #d32f2f; }
    </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="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-2">
                                    <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="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="excellent" <?php echo $score_filter === 'excellent' ? 'selected' : ''; ?>>🌟 Excellent (85%+)</option>
                                        <option value="good" <?php echo $score_filter === 'good' ? 'selected' : ''; ?>>👍 Good (70-84%)</option>
                                        <option value="average" <?php echo $score_filter === 'average' ? 'selected' : ''; ?>>📊 Average (50-69%)</option>
                                        <option value="below_average" <?php echo $score_filter === 'below_average' ? 'selected' : ''; ?>>⚠️ Below Avg (30-49%)</option>
                                        <option value="poor" <?php echo $score_filter === 'poor' ? 'selected' : ''; ?>>❌ Poor (<30%)</option>
                                        <option value="no_score" <?php echo $score_filter === 'no_score' ? 'selected' : ''; ?>>➖ No Score</option>
                                    </select>
                                </div>
                                <div class="col-md-2 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">
                            <h5 class="card-title mb-0">Applications (<?php echo count($applications); ?>)</h5>
                        </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: ?>
                                <!-- Bulk Actions Form -->
                                <form method="POST" id="bulkActionsForm">
                                    <div class="d-flex justify-content-between align-items-center p-3 bulk-actions-bar">
                                        <div class="d-flex align-items-center">
                                            <span class="me-3">
                                                <span id="selectedCount" class="bulk-action-counter">0</span> 
                                                <span class="text-muted">selected</span>
                                            </span>
                                            <select class="form-select form-select-sm me-2" name="bulk_action" id="bulkAction" style="width: auto;" disabled>
                                                <option value="">Choose Action...</option>
                                                <optgroup label="Status Changes">
                                                    <option value="longlist">📝 Longlist</option>
                                                    <option value="shortlist">⭐ Shortlist</option>
                                                    <option value="interview">👥 Interview</option>
                                                    <option value="hire">✅ Hire</option>
                                                    <option value="reject">❌ Reject</option>
                                                </optgroup>
                                                <optgroup label="Export Actions">
                                                    <option value="download_zip">📦 Download as ZIP</option>
                                                </optgroup>
                                            </select>
                                            <button type="submit" class="btn btn-primary btn-sm me-2" id="applyBulkAction" disabled>
                                                <i class="fas fa-check me-1"></i>Apply
                                            </button>
                                        </div>
                                        <div class="text-muted small">
                                            <i class="fas fa-info-circle me-1"></i>
                                            Select applications to enable bulk actions
                                        </div>
                                    </div>
                                    
                                    <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th width="30">
                                                    <input type="checkbox" class="form-check-input" id="selectAll" title="Select all applications">
                                                </th>
                                                <th>Candidate</th>
                                                <th>Job Position</th>
                                                <th>Survey Score</th>
                                                <th>Applied Date</th>
                                                <th>Closing Date</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($applications as $app): ?>
                                                <tr>
                                                    <td>
                                                        <input type="checkbox" class="form-check-input application-checkbox" 
                                                               name="selected_applications[]" value="<?php echo $app['id']; ?>">
                                                    </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>
                                                            <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 
                                                        // Check if this job has survey questions
                                                        $stmt = $db->prepare("SELECT COUNT(*) as question_count FROM job_survey_questions WHERE job_id = ?");
                                                        $stmt->execute([$app['job_id']]);
                                                        $survey_info = $stmt->fetch();
                                                        $has_survey = $survey_info['question_count'] > 0;
                                                        ?>
                                                        
                                                        <?php if ($has_survey && $app['total_score'] > 0): ?>
                                                            <?php 
                                                                $score_category = function_exists('getScoreCategory') ? getScoreCategory($app['total_score']) : null;
                                                                $badge_class = $score_category ? $score_category['class'] : 'secondary';
                                                                $icon = $score_category ? $score_category['icon'] : 'chart-bar';
                                                            ?>
                                                            <div>
                                                                <span class="badge bg-<?php echo $badge_class; ?> mb-1">
                                                                    <i class="fas fa-<?php echo $icon; ?> me-1"></i><?php echo number_format($app['total_score'], 1); ?>%
                                                                </span>
                                                                <?php if ($score_category): ?>
                                                                    <br><small class="text-muted"><?php echo $score_category['category']; ?> (Weighted)</small>
                                                                <?php endif; ?>
                                                            </div>
                                                        <?php elseif ($has_survey): ?>
                                                            <span class="badge bg-light text-dark">
                                                                <i class="fas fa-minus me-1"></i>No Score
                                                            </span>
                                                            <br><small class="text-muted">Survey not completed</small>
                                                        <?php else: ?>
                                                            <span class="text-muted">—</span>
                                                            <br><small class="text-muted">No survey</small>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?php echo formatDate($app['applied_at']); ?></td>
                                                    <td>
                                                        <?php if ($app['deadline']): ?>
                                                            <small class="text-<?php echo (strtotime($app['deadline']) < time()) ? 'danger' : 'info'; ?>">
                                                                <i class="fas fa-calendar-alt me-1"></i>
                                                                <?php echo formatDate($app['deadline']); ?>
                                                            </small>
                                                        <?php else: ?>
                                                            <small class="text-muted">Not specified</small>
                                                        <?php endif; ?>
                                                    </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>
                                                                        <a href="#" class="dropdown-item text-primary" onclick="submitStatusUpdate(<?php echo $app['id']; ?>, 'longlist'); return false;">
                                                                            <i class="fas fa-list me-2"></i>Longlist
                                                                        </a>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if ($app['status'] === 'longlisted'): ?>
                                                                    <li>
                                                                        <a href="#" class="dropdown-item text-warning" onclick="submitStatusUpdate(<?php echo $app['id']; ?>, 'shortlist'); return false;">
                                                                            <i class="fas fa-star me-2"></i>Shortlist
                                                                        </a>
                                                                    </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'] === 'interviewed'): ?>
                                                                    <li>
                                                                        <a href="#" class="dropdown-item text-success" onclick="submitStatusUpdate(<?php echo $app['id']; ?>, 'hire'); return false;">
                                                                            <i class="fas fa-check me-2"></i>Hire
                                                                        </a>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if (!in_array($app['status'], ['hired', 'rejected'])): ?>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <li>
                                                                        <a href="#" class="dropdown-item text-danger" onclick="if(confirm('Are you sure you want to reject this application?')) submitStatusUpdate(<?php echo $app['id']; ?>, 'reject'); return false;">
                                                                            <i class="fas fa-times me-2"></i>Reject
                                                                        </a>
                                                                    </li>
                                                                <?php endif; ?>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                </form>
                            <?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>

    <!-- Hidden Status Update Form -->
    <form id="statusUpdateForm" method="POST" style="display: none;">
        <input type="hidden" name="application_id" id="status_application_id">
        <input type="hidden" name="action" id="status_action">
    </form>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Function to handle individual status updates outside the bulk form
        function submitStatusUpdate(applicationId, action) {
            document.getElementById('status_application_id').value = applicationId;
            document.getElementById('status_action').value = action;
            document.getElementById('statusUpdateForm').submit();
        }
        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];
        
        // Bulk Actions JavaScript
        document.addEventListener('DOMContentLoaded', function() {
            const selectAllCheckbox = document.getElementById('selectAll');
            const applicationCheckboxes = document.querySelectorAll('.application-checkbox');
            const selectedCountSpan = document.getElementById('selectedCount');
            const bulkActionSelect = document.getElementById('bulkAction');
            const applyBulkActionButton = document.getElementById('applyBulkAction');
            const bulkActionsForm = document.getElementById('bulkActionsForm');
            
            // Select All functionality
            selectAllCheckbox.addEventListener('change', function() {
                applicationCheckboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
                updateBulkActionControls();
            });
            
            // Individual checkbox functionality
            applicationCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    updateSelectAllState();
                    updateBulkActionControls();
                });
            });
            
            function updateSelectAllState() {
                const checkedCheckboxes = document.querySelectorAll('.application-checkbox:checked');
                const totalCheckboxes = applicationCheckboxes.length;
                
                if (checkedCheckboxes.length === 0) {
                    selectAllCheckbox.indeterminate = false;
                    selectAllCheckbox.checked = false;
                } else if (checkedCheckboxes.length === totalCheckboxes) {
                    selectAllCheckbox.indeterminate = false;
                    selectAllCheckbox.checked = true;
                } else {
                    selectAllCheckbox.indeterminate = true;
                    selectAllCheckbox.checked = false;
                }
            }
            
            function updateBulkActionControls() {
                const checkedCheckboxes = document.querySelectorAll('.application-checkbox:checked');
                const selectedCount = checkedCheckboxes.length;
                
                selectedCountSpan.textContent = selectedCount;
                
                if (selectedCount > 0) {
                    bulkActionSelect.disabled = false;
                    bulkActionSelect.parentElement.querySelector('.text-muted').textContent = 
                        `${selectedCount} application${selectedCount > 1 ? 's' : ''} selected - choose an action`;
                } else {
                    bulkActionSelect.disabled = true;
                    bulkActionSelect.value = '';
                    applyBulkActionButton.disabled = true;
                    bulkActionSelect.parentElement.querySelector('.text-muted').textContent = 
                        'Select applications to enable bulk actions';
                }
            }
            
            // Enable Apply button when action is selected
            bulkActionSelect.addEventListener('change', function() {
                const selectedCount = document.querySelectorAll('.application-checkbox:checked').length;
                applyBulkActionButton.disabled = !this.value || selectedCount === 0;
            });
            
            // Confirm bulk action before submission
            bulkActionsForm.addEventListener('submit', function(e) {
                const selectedCheckboxes = document.querySelectorAll('.application-checkbox:checked');
                const selectedAction = bulkActionSelect.value;
                
                if (selectedCheckboxes.length === 0 || !selectedAction) {
                    e.preventDefault();
                    alert('Please select applications and choose an action.');
                    return;
                }
                
                // Handle download action differently - no confirmation needed, just show progress
                if (selectedAction === 'download_zip') {
                    showDownloadProgress(selectedCheckboxes.length);
                    return; // Let form submit normally
                }
                
                const actionLabels = {
                    'longlist': 'longlist',
                    'shortlist': 'shortlist', 
                    'interview': 'set for interview',
                    'hire': 'hire',
                    'reject': 'reject',
                    'download_zip': 'download'
                };
                
                const actionLabel = actionLabels[selectedAction] || selectedAction;
                const confirmMessage = `Are you sure you want to ${actionLabel} ${selectedCheckboxes.length} selected application${selectedCheckboxes.length > 1 ? 's' : ''}?`;
                
                if (!confirm(confirmMessage)) {
                    e.preventDefault();
                }
            });
            
            // Show download progress
            function showDownloadProgress(count) {
                // Create progress modal
                const progressModal = document.createElement('div');
                progressModal.className = 'modal fade';
                progressModal.id = 'downloadProgressModal';
                progressModal.innerHTML = `
                    <div class="modal-dialog modal-sm">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h6 class="modal-title">
                                    <i class="fas fa-download me-2"></i>Preparing Download
                                </h6>
                            </div>
                            <div class="modal-body text-center">
                                <div class="spinner-border text-primary mb-3" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mb-0">Preparing ${count} application${count > 1 ? 's' : ''} for download...</p>
                                <small class="text-muted">This may take a few moments for large files</small>
                            </div>
                        </div>
                    </div>
                `;
                
                document.body.appendChild(progressModal);
                const modal = new bootstrap.Modal(progressModal);
                modal.show();
                
                // Auto-close modal after 5 seconds (download should start before then)
                setTimeout(() => {
                    modal.hide();
                    setTimeout(() => progressModal.remove(), 300);
                }, 5000);
            }
            
            // Add visual feedback for row selection
            applicationCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    const row = this.closest('tr');
                    if (this.checked) {
                        row.classList.add('table-primary');
                    } else {
                        row.classList.remove('table-primary');
                    }
                });
            });
        });
    </script>
</body>
</html>