<?php
// api/club_document_download.php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/club_common.php';

try {
    rvu_ensure_club_tables($pdo);
    $user = rvu_club_require_user($pdo);
    $documentId = (int)($_GET['id'] ?? 0);
    if ($documentId <= 0) rvu_club_json(['detail' => 'A valid document id is required.'], 422);

    $stmt = $pdo->prepare("SELECT d.*, c.created_by, c.campus, c.status
                          FROM campus_club_documents d
                          INNER JOIN campus_clubs c ON c.id = d.club_id
                          WHERE d.id = ?");
    $stmt->execute([$documentId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) rvu_club_json(['detail' => 'Club document not found.'], 404);
    rvu_club_require_view($user, $row);

    $root = realpath(__DIR__ . '/..');
    $relative = str_replace(['\\', '..'], ['/', ''], (string)$row['file_path']);
    $full = $root ? $root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relative) : '';
    if ($full === '' || !is_file($full)) rvu_club_json(['detail' => 'The stored club document is missing.'], 404);

    $name = basename((string)$row['original_name']);
    header('Content-Type: ' . ((string)$row['mime_type'] ?: 'application/octet-stream'));
    header('Content-Length: ' . filesize($full));
    header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($name));
    header('Cache-Control: private, max-age=0, must-revalidate');
    readfile($full);
    exit;
} catch (Throwable $e) {
    rvu_club_json(['detail' => 'Club download server error: ' . $e->getMessage()], 500);
}
