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

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

$company_id = $_SESSION['company_id'];
$document_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$document_type = isset($_GET['type']) ? $_GET['type'] : '';

if (!$document_id || !in_array($document_type, ['document', 'certificate'])) {
    die('Invalid request');
}

if ($document_type === 'document') {
    // Get document from candidate_documents table
    $stmt = $db->prepare("
        SELECT cd.*, c.first_name, c.last_name
        FROM candidate_documents cd
        JOIN candidates c ON cd.candidate_id = c.id
        JOIN job_applications ja ON c.id = ja.candidate_id
        JOIN jobs j ON ja.job_id = j.id
        WHERE cd.id = ? AND j.company_id = ? AND cd.is_public = 1
        GROUP BY cd.id
    ");
    $stmt->execute([$document_id, $company_id]);
    $document = $stmt->fetch();
    
    if (!$document) {
        die('Document not found or access denied');
    }
    
    $file_path = UPLOAD_PATH . 'documents/' . $document['file_path'];
    $file_name = $document['title'] . '_' . $document['first_name'] . '_' . $document['last_name'];
    $file_type = $document['file_type'];
    
} else if ($document_type === 'certificate') {
    // Get certificate from certificates table
    $stmt = $db->prepare("
        SELECT cert.*, c.first_name, c.last_name
        FROM certificates cert
        JOIN candidates c ON cert.candidate_id = c.id
        JOIN job_applications ja ON c.id = ja.candidate_id
        JOIN jobs j ON ja.job_id = j.id
        WHERE cert.id = ? AND j.company_id = ?
        GROUP BY cert.id
    ");
    $stmt->execute([$document_id, $company_id]);
    $document = $stmt->fetch();
    
    if (!$document || !$document['file_path']) {
        die('Certificate not found or access denied');
    }
    
    $file_path = UPLOAD_PATH . 'certificates/' . $document['file_path'];
    $file_name = $document['title'] . '_' . $document['first_name'] . '_' . $document['last_name'];
    $file_type = 'application/pdf'; // Most certificates are PDFs
}

// Check if file exists
if (!file_exists($file_path)) {
    die('File not found on server');
}

// Get file extension
$path_info = pathinfo($file_path);
$extension = isset($path_info['extension']) ? $path_info['extension'] : 'pdf';

// Clean filename for download
$clean_filename = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $file_name) . '.' . $extension;

// Set headers for file download
header('Content-Type: ' . ($file_type ?: 'application/octet-stream'));
header('Content-Disposition: attachment; filename="' . $clean_filename . '"');
header('Content-Length: ' . filesize($file_path));
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');

// Output file
readfile($file_path);
exit;
?>