<?php
session_start();
include('../../../includes/config.php');

if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    die('Unauthorized');
}

$user_id = $_SESSION['user_id'];
$message_id = isset($_GET['message_id']) ? (int)$_GET['message_id'] : 0;

if (!$message_id) {
    http_response_code(400);
    die('Invalid request');
}

// Fetch attachment info and verify access
$query = "SELECT attachment, sender_id, receiver_id FROM messages WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $message_id);
$stmt->execute();
$result = $stmt->get_result();
$message = $result->fetch_assoc();

if (!$message) {
    http_response_code(404);
    die('Message not found');
}

// Check if the logged-in user is sender or receiver
if ($user_id !== (int)$message['sender_id'] && $user_id !== (int)$message['receiver_id']) {
    http_response_code(403);
    die('You do not have permission to download this attachment.');
}

$attachment = $message['attachment'];
if (empty($attachment)) {
    http_response_code(404);
    die('No attachment found');
}

// Secure file path - adjust based on your actual uploads folder path
$file_path = realpath(__DIR__ . '/../../../uploads/messages/' . $attachment);

// Check if file exists and is within the allowed directory (avoid path traversal)
$allowed_dir = realpath(__DIR__ . '/../../../uploads/messages/');
if (!$file_path || strpos($file_path, $allowed_dir) !== 0 || !is_file($file_path)) {
    http_response_code(404);
    die('File not found or access denied.');
}

// Serve file for download with appropriate headers
$filename = basename($file_path);
$filesize = filesize($file_path);
$mime_type = mime_content_type($file_path);

header('Content-Description: File Transfer');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . $filesize);
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Expires: 0');

readfile($file_path);
exit;
