<?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_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_type = 'application/pdf'; // Most certificates are PDFs
}

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

// Set headers for inline viewing
if (strpos($file_type, 'pdf') !== false) {
    header('Content-Type: application/pdf');
} else if (strpos($file_type, 'image') !== false) {
    header('Content-Type: ' . $file_type);
} else {
    // For other file types, force download instead
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
}

header('Content-Length: ' . filesize($file_path));
header('Cache-Control: public, max-age=3600'); // Cache for 1 hour

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