<?php
/**
 * Storage Access Handler - Serves company-specific files
 */

require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/../src/FileManager.php';

// Parse the request URI
$requestUri = $_SERVER['REQUEST_URI'];
$requestUri = str_replace('/storage/', '', $requestUri);
$parts = explode('/', $requestUri);

if (count($parts) < 2) {
    http_response_code(404);
    exit;
}

// Extract company_id and file path
$companyId = (int) $parts[0];
if ($companyId <= 0) {
    http_response_code(404);
    exit;
}

$filePath = implode('/', array_slice($parts, 1));
$fullPath = __DIR__ . '/../storage/companies/' . $companyId . '/' . $filePath;

// Security checks
if (!file_exists($fullPath) || !is_file($fullPath)) {
    http_response_code(404);
    exit;
}

// Check if user has access to this company's files
if (AuthManager::isAuthenticated()) {
    $userCompany = TenantManager::getCurrentCompanyId();
    if ($userCompany != $companyId) {
        // User doesn't have access to this company's files
        http_response_code(403);
        exit;
    }
} else {
    // For public files (like PDFs for clients), allow access with token
    // You can implement token-based access here if needed
    http_response_code(401);
    exit;
}

// Determine file type and set appropriate headers
$extension = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
$mimeTypes = [
    'pdf' => 'application/pdf',
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'png' => 'image/png',
    'gif' => 'image/gif',
    'svg' => 'image/svg+xml',
    'txt' => 'text/plain',
    'csv' => 'text/csv',
    'doc' => 'application/msword',
    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'xls' => 'application/vnd.ms-excel',
    'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
];

$mimeType = $mimeTypes[$extension] ?? 'application/octet-stream';

// Set headers
header('Content-Type: ' . $mimeType);
header('Content-Length: ' . filesize($fullPath));
header('Cache-Control: public, max-age=31536000'); // Cache for 1 year
header('Content-Disposition: inline; filename="' . basename($fullPath) . '"');

// Serve the file
readfile($fullPath);
exit;
