<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

require_once '../config/database.php';

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'];
$receipt_id = intval($_GET['id'] ?? 0);

// Verify access
if ($role == 'driver') {
    $sql = "SELECT * FROM receipts WHERE id = ?  AND driver_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ii', $receipt_id, $user_id);
} else {
    $sql = "SELECT * FROM receipts WHERE id = ? ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $receipt_id);
}

$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $receipt = $result->fetch_assoc();
    $file_path = UPLOAD_DIR . $receipt['file_path'];
    
    if (file_exists($file_path)) {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $receipt['original_filename'] . '"');
        header('Content-Length: ' . filesize($file_path));
        readfile($file_path);
        exit();
    }
}

header('Location: dashboard.php');
exit();
?>