<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if attachment ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "Invalid attachment ID.";
    header('Location: my_tickets.php');
    exit();
}

$attachment_id = intval($_GET['id']);
$user_id = $_SESSION['user_id'];

// Get user role
$sql = "SELECT role_id FROM users WHERE user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$is_admin = in_array($user['role_id'], [1, 2, 3]); // Adjust role IDs as needed

// Fetch attachment details
$sql = "SELECT a.*, m.ticket_id, t.user_id AS ticket_user_id
        FROM ticket_attachments a
        JOIN ticket_messages m ON a.message_id = m.id
        JOIN support_tickets t ON m.ticket_id = t.id
        WHERE a.id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $attachment_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Attachment not found.";
    header('Location: my_tickets.php');
    exit();
}

$attachment = $result->fetch_assoc();

// Security check: only allow owner of ticket or admins to download
$has_access = ($attachment['ticket_user_id'] == $user_id) || $is_admin;
if (!$has_access) {
    $_SESSION['error_message'] = "You don't have permission to download this file.";
    header('Location: my_tickets.php');
    exit();
}

// Get the file path
$file_path = $attachment['file_path'];

// Check if file exists
if (!file_exists($file_path)) {
    $_SESSION['error_message'] = "File does not exist on the server.";
    header('Location: my_tickets.php');
    exit();
}

// Set headers for download
header('Content-Description: File Transfer');
header('Content-Type: ' . $attachment['file_type']);
header('Content-Disposition: attachment; filename="' . basename($attachment['file_name']) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));

// Clear output buffer
ob_clean();
flush();

// Read file and output
readfile($file_path);
exit;
?>