<?php
/* ============================================================================
 *  staff/download_doc.php — force-download a staff member's own document.
 *  Sends Content-Disposition: attachment so the phone saves the file instead
 *  of opening it. Path is looked up from the logged-in user (not the URL).
 *  Usage: download_doc.php?d=contract   or   download_doc.php?d=cv
 * ==========================================================================*/
session_start();
if (!isset($_SESSION["user_id"]) || empty($_SESSION["company_id"])) {
    http_response_code(403); exit('Forbidden');
}
require_once '../config/database.php';

$userId    = (int)$_SESSION["user_id"];
$companyId = (int)$_SESSION["company_id"];
$which     = ($_GET['d'] ?? '') === 'cv' ? 'cv' : 'contract';
$col       = $which === 'cv' ? 'cv_file' : 'contract_file';

$st = $pdo->prepare("SELECT $col AS f FROM company_staff WHERE user_id=? AND company_id=? LIMIT 1");
$st->execute([$userId, $companyId]);
$path = $st->fetchColumn();
if (!$path) { http_response_code(404); exit('No file'); }

/* resolve safely inside uploads/staff (block path traversal) */
$abs     = realpath(__DIR__ . '/../' . $path);
$baseDir = realpath(__DIR__ . '/../uploads/staff');
if (!$abs || !$baseDir || strpos($abs, $baseDir) !== 0 || !is_file($abs)) {
    http_response_code(404); exit('File not found');
}

$ext      = strtolower(pathinfo($abs, PATHINFO_EXTENSION));
$niceName = ($which === 'cv' ? 'CV' : 'Contract') . ($ext ? '.' . $ext : '');

if (ob_get_level()) { ob_end_clean(); }
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $niceName . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($abs));
header('Cache-Control: no-store, must-revalidate');
header('Pragma: public');
readfile($abs);
exit;