<?php
/* ============================================================================
 *  company/drive_file.php — streams a job image stored in Google Drive.
 *  Used as the <img src> for job attachments. Logged-in company users only,
 *  who have at least view access to the Job Management module.
 *  Usage: drive_file.php?id=<driveFileId>
 * ==========================================================================*/
session_start();
require_once '../config/database.php';
require_once '../config/modules.php';
require_once '../config/module_access.php';

if (!isset($_SESSION['user_id']) || empty($_SESSION['company_id'])) {
    http_response_code(403); exit('Forbidden');
}
$companyId = (int)$_SESSION['company_id'];
$userId    = (int)$_SESSION['user_id'];
$role      = $_SESSION['role'] ?? '';
$enabled   = company_enabled_modules($pdo, $companyId);
if (!module_on($enabled, 'jobs') || !mod_can_view($pdo, $companyId, $userId, $role, 'jobs')) {
    http_response_code(403); exit('Forbidden');
}

require_once __DIR__ . '/gdrive_lib.php';

$id = preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['id'] ?? '');
if ($id === '') { http_response_code(400); exit('Bad request'); }

$r = gd_download($id);
if (empty($r['ok'])) { http_response_code(404); exit('Not found'); }

header('Content-Type: ' . $r['mime']);
header('Content-Length: ' . strlen($r['body']));
header('Cache-Control: private, max-age=86400');
echo $r['body'];