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

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

$database = new Database();
$db = $database->getConnection();
$company_id = $_SESSION['company_id'];

// Get selected applications
$selected_applications = isset($_POST['selected_applications']) ? $_POST['selected_applications'] : [];

if (empty($selected_applications)) {
    die('No applications selected for download.');
}

// Validate and sanitize application IDs
$selected_applications = array_map('intval', $selected_applications);
$selected_applications = array_filter($selected_applications, function($id) { return $id > 0; });

if (empty($selected_applications)) {
    die('Invalid application IDs provided.');
}

// Validate applications belong to this company
$placeholders = str_repeat('?,', count($selected_applications) - 1) . '?';
$params = array_merge($selected_applications, [$company_id]);

$stmt = $db->prepare("
    SELECT ja.*, j.title as job_title, j.description as job_description,
           c.first_name, c.last_name, c.email, c.phone, c.address,
           c.date_of_birth, c.gender, c.profile_picture,
           r.title as resume_title, r.summary, r.skills, r.file_path as resume_file
    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 ja.id IN ($placeholders) AND j.company_id = ?
    ORDER BY ja.applied_at DESC
");

$stmt->execute($params);
$applications = $stmt->fetchAll();

if (empty($applications)) {
    die('No valid applications found for download.');
}

// Create ZIP file directly in output
$zip_filename = 'Applications_' . date('Y-m-d_H-i-s') . '.zip';

// Set headers for download
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zip_filename . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');

// Create ZIP in memory
$zip = new ZipArchive();
$temp_file = tempnam(sys_get_temp_dir(), 'recruitment_zip_');

if ($zip->open($temp_file, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
    die('Cannot create ZIP file. Error: ' . $zip->getStatusString());
}

$application_count = 0;
$files_added = 0;

foreach ($applications as $app) {
    $application_count++;
    
    // Sanitize folder name - remove special characters
    $candidate_name = preg_replace('/[^a-zA-Z0-9_-]/', '_', $app['first_name'] . '_' . $app['last_name']);
    $job_title = preg_replace('/[^a-zA-Z0-9_-]/', '_', substr($app['job_title'], 0, 30));
    
    // Create folder for this application
    $app_folder = sprintf('%02d_%s_%s/', $application_count, $candidate_name, $job_title);
    
    // Prepare comprehensive candidate data for PDF generation
    $pdfCandidateData = [
        'first_name' => $app['first_name'],
        'last_name' => $app['last_name'],
        'email' => $app['email'],
        'phone' => $app['phone'],
        'address' => $app['address'],
        'date_of_birth' => $app['date_of_birth'],
        'gender' => $app['gender'],
        'profile_picture' => $app['profile_picture'],
        'summary' => $app['summary'],
        'skills' => $app['skills'],
        'cover_letter' => $app['cover_letter'],
        'status' => $app['status'],
        'applied_at' => $app['applied_at'],
        'work_experience' => [],
        'education' => [],
        'certificates' => [],
        'documents' => []
    ];
    
    // Create application summary text file
    $summary_content = "APPLICATION SUMMARY\n";
    $summary_content .= "==================\n\n";
    $summary_content .= "Candidate: " . $app['first_name'] . " " . $app['last_name'] . "\n";
    $summary_content .= "Email: " . $app['email'] . "\n";
    $summary_content .= "Phone: " . ($app['phone'] ?: 'Not provided') . "\n";
    $summary_content .= "Address: " . ($app['address'] ?: 'Not provided') . "\n";
    $summary_content .= "Date of Birth: " . ($app['date_of_birth'] ?: 'Not provided') . "\n";
    $summary_content .= "Gender: " . ($app['gender'] ?: 'Not provided') . "\n";
    $summary_content .= "\nJOB INFORMATION\n";
    $summary_content .= "===============\n";
    $summary_content .= "Position: " . $app['job_title'] . "\n";
    $summary_content .= "Application Status: " . ucfirst($app['status']) . "\n";
    $summary_content .= "Applied Date: " . date('Y-m-d H:i:s', strtotime($app['applied_at'])) . "\n";
    $summary_content .= "\nCOVER LETTER\n";
    $summary_content .= "============\n";
    $summary_content .= ($app['cover_letter'] ?: 'No cover letter provided') . "\n";
    
    if ($app['resume_title']) {
        $summary_content .= "\nRESUME INFORMATION\n";
        $summary_content .= "==================\n";
        $summary_content .= "Resume Title: " . $app['resume_title'] . "\n";
        $summary_content .= "Summary: " . ($app['summary'] ?: 'Not provided') . "\n";
        $summary_content .= "Skills: " . ($app['skills'] ?: 'Not provided') . "\n";
    }
    
    // Add application summary to zip
    if ($zip->addFromString($app_folder . 'Application_Summary.txt', $summary_content)) {
        $files_added++;
    }
    
    // Add profile picture if exists
    if ($app['profile_picture']) {
        $profile_path = UPLOAD_PATH . 'profiles/' . $app['profile_picture'];
        if (file_exists($profile_path) && is_readable($profile_path)) {
            $extension = pathinfo($app['profile_picture'], PATHINFO_EXTENSION);
            if ($zip->addFile($profile_path, $app_folder . 'Profile_Photo.' . $extension)) {
                $files_added++;
            }
        }
    }
    
    // Add resume file if exists
    if ($app['resume_file']) {
        $resume_path = UPLOAD_PATH . 'resumes/' . $app['resume_file'];
        if (file_exists($resume_path) && is_readable($resume_path)) {
            $extension = pathinfo($app['resume_file'], PATHINFO_EXTENSION);
            if ($zip->addFile($resume_path, $app_folder . 'Resume.' . $extension)) {
                $files_added++;
            }
        }
    }
    
    // Get work experience
    try {
        $stmt_exp = $db->prepare("
            SELECT * FROM work_experience 
            WHERE candidate_id = ? 
            ORDER BY start_date DESC
        ");
        $stmt_exp->execute([$app['candidate_id']]);
        $experiences = $stmt_exp->fetchAll();
        
        if ($experiences) {
            // Add to PDF data
            $pdfCandidateData['work_experience'] = $experiences;
            
            $exp_content = "WORK EXPERIENCE\n";
            $exp_content .= "===============\n\n";
            
            foreach ($experiences as $exp) {
                $exp_content .= "Company: " . $exp['company_name'] . "\n";
                $exp_content .= "Position: " . $exp['position'] . "\n";
                $exp_content .= "Period: " . $exp['start_date'] . " - " . 
                              ($exp['is_current'] ? 'Present' : ($exp['end_date'] ?: 'Not specified')) . "\n";
                $exp_content .= "Description: " . ($exp['description'] ?: 'Not provided') . "\n\n";
            }
            
            if ($zip->addFromString($app_folder . 'Work_Experience.txt', $exp_content)) {
                $files_added++;
            }
        }
    } catch (Exception $e) {
        // Continue if work experience table doesn't exist or has issues
    }
    
    // Get education
    try {
        $stmt_edu = $db->prepare("
            SELECT * FROM education 
            WHERE candidate_id = ? 
            ORDER BY start_date DESC
        ");
        $stmt_edu->execute([$app['candidate_id']]);
        $education = $stmt_edu->fetchAll();
        
        if ($education) {
            // Add to PDF data
            $pdfCandidateData['education'] = $education;
            
            $edu_content = "EDUCATION\n";
            $edu_content .= "=========\n\n";
            
            foreach ($education as $edu) {
                $edu_content .= "Institution: " . $edu['institution'] . "\n";
                $edu_content .= "Degree: " . ($edu['degree'] ?: 'Not specified') . "\n";
                $edu_content .= "Field of Study: " . ($edu['field_of_study'] ?: 'Not specified') . "\n";
                $edu_content .= "Period: " . ($edu['start_date'] ?: 'Not specified') . " - " . ($edu['end_date'] ?: 'Not specified') . "\n";
                $edu_content .= "Grade: " . ($edu['grade'] ?: 'Not provided') . "\n";
                $edu_content .= "Description: " . ($edu['description'] ?: 'Not provided') . "\n\n";
            }
            
            if ($zip->addFromString($app_folder . 'Education.txt', $edu_content)) {
                $files_added++;
            }
        }
    } catch (Exception $e) {
        // Continue if education table doesn't exist or has issues
    }
    
    // Get candidate documents (all attachments)
    try {
        $stmt_docs = $db->prepare("
            SELECT * FROM candidate_documents 
            WHERE candidate_id = ? 
            ORDER BY document_type, created_at DESC
        ");
        $stmt_docs->execute([$app['candidate_id']]);
        $documents = $stmt_docs->fetchAll();
        
        if ($documents) {
            // Add to PDF data
            $pdfCandidateData['documents'] = $documents;
            
            $doc_content = "CANDIDATE DOCUMENTS\n";
            $doc_content .= "===================\n\n";
            
            // Group documents by type
            $doc_types = [];
            foreach ($documents as $doc) {
                $doc_types[$doc['document_type']][] = $doc;
            }
            
            foreach ($doc_types as $type => $type_docs) {
                $doc_content .= strtoupper($type) . ":\n";
                $doc_content .= str_repeat('-', strlen($type) + 1) . "\n";
                
                foreach ($type_docs as $doc) {
                    $doc_content .= "Title: " . $doc['title'] . "\n";
                    $doc_content .= "File: " . $doc['file_path'] . "\n";
                    $doc_content .= "Size: " . number_format($doc['file_size'] / 1024, 2) . " KB\n";
                    $doc_content .= "Type: " . $doc['file_type'] . "\n";
                    $doc_content .= "Description: " . ($doc['description'] ?: 'Not provided') . "\n";
                    $doc_content .= "Uploaded: " . date('Y-m-d H:i:s', strtotime($doc['created_at'])) . "\n";
                    
                    // Add the actual document file to ZIP
                    if (!empty($doc['file_path'])) {
                        $doc_path = UPLOAD_PATH . 'documents/' . $doc['file_path'];
                        if (file_exists($doc_path) && is_readable($doc_path)) {
                            $extension = pathinfo($doc['file_path'], PATHINFO_EXTENSION);
                            $safe_filename = preg_replace('/[^a-zA-Z0-9_.-]/', '_', $doc['title']);
                            if ($zip->addFile($doc_path, $app_folder . 'Documents/' . ucfirst($doc['document_type']) . '_' . $safe_filename . '.' . $extension)) {
                                $files_added++;
                            }
                        }
                    }
                    $doc_content .= "\n";
                }
                $doc_content .= "\n";
            }
            
            if ($zip->addFromString($app_folder . 'Documents_List.txt', $doc_content)) {
                $files_added++;
            }
        }
    } catch (Exception $e) {
        // Continue if candidate_documents table doesn't exist
    }
    
    // Get certificates with files
    try {
        $stmt_cert = $db->prepare("
            SELECT * FROM certificates 
            WHERE candidate_id = ? 
            ORDER BY issue_date DESC
        ");
        $stmt_cert->execute([$app['candidate_id']]);
        $certificates = $stmt_cert->fetchAll();
        
        if ($certificates) {
            // Add to PDF data
            $pdfCandidateData['certificates'] = $certificates;
            
            $cert_content = "CERTIFICATES\n";
            $cert_content .= "============\n\n";
            
            foreach ($certificates as $cert) {
                $cert_content .= "Certificate: " . $cert['title'] . "\n";
                $cert_content .= "Issuer: " . ($cert['issuing_organization'] ?: 'Not specified') . "\n";
                $cert_content .= "Issue Date: " . ($cert['issue_date'] ? date('Y-m-d', strtotime($cert['issue_date'])) : 'Not specified') . "\n";
                $cert_content .= "Expiry Date: " . ($cert['expiry_date'] ? date('Y-m-d', strtotime($cert['expiry_date'])) : 'No expiry') . "\n";
                $cert_content .= "Credential ID: " . ($cert['credential_id'] ?: 'Not provided') . "\n";
                $cert_content .= "Credential URL: " . ($cert['credential_url'] ?: 'Not provided') . "\n";
                $cert_content .= "Description: " . ($cert['description'] ?: 'Not provided') . "\n";
                
                // Add certificate file if exists
                if (!empty($cert['file_path'])) {
                    $cert_path = UPLOAD_PATH . 'certificates/' . $cert['file_path'];
                    if (file_exists($cert_path) && is_readable($cert_path)) {
                        $extension = pathinfo($cert['file_path'], PATHINFO_EXTENSION);
                        $safe_filename = preg_replace('/[^a-zA-Z0-9_.-]/', '_', $cert['title']);
                        if ($zip->addFile($cert_path, $app_folder . 'Certificates/' . $safe_filename . '.' . $extension)) {
                            $files_added++;
                        }
                    }
                }
                $cert_content .= "\n";
            }
            
            if ($zip->addFromString($app_folder . 'Certificates_List.txt', $cert_content)) {
                $files_added++;
            }
        }
    } catch (Exception $e) {
        // Continue if certificates table doesn't exist or has issues
    }
    
    // Get any additional uploaded files from the uploads directory
    $candidate_folder = UPLOAD_PATH . 'candidates/' . $app['candidate_id'] . '/';
    if (is_dir($candidate_folder)) {
        $additional_files = scandir($candidate_folder);
        foreach ($additional_files as $file) {
            if ($file != '.' && $file != '..' && is_file($candidate_folder . $file)) {
                if ($zip->addFile($candidate_folder . $file, $app_folder . 'Additional_Files/' . $file)) {
                    $files_added++;
                }
            }
        }
    }
    
    // Generate comprehensive PDF resume
    try {
        $pdfContent = generateCandidateResumePDF($pdfCandidateData, $app['job_title']);
        if ($pdfContent !== false) {
            $resumeFilename = 'Complete_Resume_' . $candidate_name . '.pdf';
            if ($zip->addFromString($app_folder . $resumeFilename, $pdfContent)) {
                $files_added++;
            }
        }
    } catch (Exception $e) {
        // Continue if PDF generation fails
        error_log("PDF generation failed for candidate {$app['candidate_id']}: " . $e->getMessage());
    }
}

// Add summary file for all applications
$total_summary = "BULK APPLICATION DOWNLOAD SUMMARY\n";
$total_summary .= "==================================\n\n";
$total_summary .= "Company: " . $_SESSION['company_name'] . "\n";
$total_summary .= "Downloaded by: " . ($_SESSION['user_email'] ?? $_SESSION['company_name']) . "\n";
$total_summary .= "Download Date: " . date('Y-m-d H:i:s') . "\n";
$total_summary .= "Total Applications: " . count($applications) . "\n";
$total_summary .= "Total Files Added: " . $files_added . "\n\n";
$total_summary .= "PACKAGE CONTENTS:\n";
$total_summary .= "=================\n";
$total_summary .= "✓ Comprehensive PDF resumes (professionally formatted)\n";
$total_summary .= "✓ Application summaries (candidate details)\n";
$total_summary .= "✓ Profile photos (when available)\n";
$total_summary .= "✓ Resume/CV files\n";
$total_summary .= "✓ Work experience details\n";
$total_summary .= "✓ Education records\n";
$total_summary .= "✓ All candidate documents (CV, certificates, transcripts, other)\n";
$total_summary .= "✓ Professional certificates with files\n";
$total_summary .= "✓ Additional uploaded attachments\n\n";
$total_summary .= "PDF RESUME FEATURES:\n";
$total_summary .= "===================\n";
$total_summary .= "• Professional layout with candidate photo\n";
$total_summary .= "• Complete contact information\n";
$total_summary .= "• Application status and job details\n";
$total_summary .= "• Work experience timeline\n";
$total_summary .= "• Education background\n";
$total_summary .= "• Professional certifications\n";
$total_summary .= "• Skills and competencies\n";
$total_summary .= "• Cover letter content\n";
$total_summary .= "• Document inventory\n\n";
$total_summary .= "APPLICATIONS INCLUDED:\n";
$total_summary .= "======================\n";

foreach ($applications as $i => $app) {
    $total_summary .= ($i + 1) . ". " . $app['first_name'] . " " . $app['last_name'] . 
                     " - " . $app['job_title'] . " (" . ucfirst($app['status']) . ")\n";
}

if ($zip->addFromString('Download_Summary.txt', $total_summary)) {
    $files_added++;
}

// Close the ZIP file
$zip->close();

// Check if ZIP file was created successfully
if (!file_exists($temp_file) || filesize($temp_file) == 0) {
    unlink($temp_file);
    die('Error: ZIP file creation failed or resulted in empty file.');
}

// Set content length header
header('Content-Length: ' . filesize($temp_file));

// Output the file
readfile($temp_file);

// Clean up
unlink($temp_file);
exit;
?>