<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

require_login($conn);

function payment_slip_error_response(int $statusCode, string $message): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    http_response_code($statusCode);
    header('Content-Type: text/plain; charset=UTF-8');
    echo $message;
    exit();
}

function payment_slip_stream_filename(string $absolutePath, string $storedFileName): string
{
    $fileName = trim($storedFileName);
    if ($fileName === '') {
        $fileName = basename($absolutePath);
    }

    $fileName = preg_replace('/[^A-Za-z0-9._-]+/', '-', $fileName);
    $fileName = trim((string) $fileName, '.-');

    if ($fileName !== '') {
        return $fileName;
    }

    $extension = strtolower((string) pathinfo($absolutePath, PATHINFO_EXTENSION));

    return $extension !== '' ? 'payment-slip.' . $extension : 'payment-slip';
}

function payment_slip_stream_mime_type(string $absolutePath, string $storedMimeType): string
{
    $mimeType = trim($storedMimeType);
    if ($mimeType !== '') {
        return $mimeType;
    }

    return match (strtolower((string) pathinfo($absolutePath, PATHINFO_EXTENSION))) {
        'jpg', 'jpeg' => 'image/jpeg',
        'gif' => 'image/gif',
        'png' => 'image/png',
        'pdf' => 'application/pdf',
        'webp' => 'image/webp',
        default => 'application/octet-stream',
    };
}

$paymentId = filter_input(INPUT_GET, 'payment_id', FILTER_VALIDATE_INT) ?: 0;
$downloadRequested = isset($_GET['download']) && (string) ($_GET['download'] ?? '') !== '0';

if ($paymentId <= 0) {
    payment_slip_error_response(404, 'Payment slip not found.');
}

$paymentStmt = db_prepare($conn, "
    SELECT
        p.payment_id,
        p.order_id,
        p.slip_file_path,
        p.slip_file_name,
        p.slip_mime_type,
        o.branch_name,
        o.order_source
    FROM payments p
    INNER JOIN orders o ON o.order_id = p.order_id
    WHERE p.payment_id = ?
    LIMIT 1
");
$paymentStmt->bind_param('i', $paymentId);
$paymentStmt->execute();
$paymentRow = $paymentStmt->get_result()->fetch_assoc() ?: null;
$paymentStmt->close();

if (!$paymentRow) {
    payment_slip_error_response(404, 'Payment slip not found.');
}

$orderSource = (string) ($paymentRow['order_source'] ?? 'booking');
$canViewSlip = can_access($conn, 'bill_management')
    || ($orderSource === 'quick_service' && can_access($conn, 'quick_service'))
    || ($orderSource !== 'quick_service' && (can_access($conn, 'queue') || can_access($conn, 'booking')));

if (!$canViewSlip) {
    payment_slip_error_response(403, 'Access denied.');
}

$branchName = (string) ($paymentRow['branch_name'] ?? '');
if (!auth_can_access_branch($conn, $branchName)) {
    payment_slip_error_response(403, 'Access denied.');
}

$slipPublicPath = trim((string) ($paymentRow['slip_file_path'] ?? ''));
if ($slipPublicPath === '') {
    payment_slip_error_response(404, 'Payment slip not found.');
}

$absolutePath = storage_upload_absolute_path_from_public($slipPublicPath, 'payment_slips');
if ($absolutePath === null) {
    payment_slip_error_response(404, 'Payment slip not found.');
}

$streamFileName = payment_slip_stream_filename($absolutePath, (string) ($paymentRow['slip_file_name'] ?? ''));
$mimeType = payment_slip_stream_mime_type($absolutePath, (string) ($paymentRow['slip_mime_type'] ?? ''));
$fileSize = filesize($absolutePath);
$disposition = $downloadRequested ? 'attachment' : 'inline';

while (ob_get_level() > 0) {
    ob_end_clean();
}

header('Content-Type: ' . $mimeType);
header('X-Content-Type-Options: nosniff');
header('Cache-Control: private, no-store, max-age=0');
header('Content-Disposition: ' . $disposition . '; filename="' . addcslashes($streamFileName, "\\\"") . '"');

if ($fileSize !== false) {
    header('Content-Length: ' . (string) $fileSize);
}

readfile($absolutePath);
exit();
