<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

function userCanAccessAttachmentViaDraft($conn, $draft_id, $document_id, $current_user_id) {
    $draft_id = (int) $draft_id;
    $document_id = (int) $document_id;
    $current_user_id = (int) $current_user_id;

    if ($draft_id <= 0 || $document_id <= 0 || $current_user_id <= 0) {
        return false;
    }

    $stmt = mysqli_prepare($conn, "SELECT ld.id
        FROM letter_drafts ld
        LEFT JOIN letter_approval_recipients lar
            ON lar.draft_id = ld.id AND lar.user_id = ?
        WHERE ld.id = ?
          AND ld.document_id = ?
          AND ld.deleted_at IS NULL
          AND (
              ld.created_by = ?
              OR ld.support_user_id = ?
              OR ld.department_officer_user_id = ?
              OR lar.user_id IS NOT NULL
          )
        LIMIT 1");

    if (!$stmt) {
        return false;
    }

    mysqli_stmt_bind_param(
        $stmt,
        "iiiiii",
        $current_user_id,
        $draft_id,
        $document_id,
        $current_user_id,
        $current_user_id,
        $current_user_id
    );
    mysqli_stmt_execute($stmt);
    return (bool) mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
}

$attachment_id = isset($_GET['attachment_id']) ? (int) $_GET['attachment_id'] : 0;
$draft_id = isset($_GET['draft_id']) ? (int) $_GET['draft_id'] : 0;
if ($attachment_id <= 0) {
    http_response_code(400);
    exit('Lampiran tidak sah.');
}

$stmt = mysqli_prepare($conn, "SELECT a.file_path, a.original_name, d.id AS document_id, d.deleted_at AS document_deleted_at, f.deleted_at AS folder_deleted_at, f.department,
        ld.id AS draft_id, ld.status AS draft_status, ld.approval_status AS draft_approval_status, ld.created_by AS draft_created_by
    FROM document_attachments a
    INNER JOIN documents d ON d.id = a.document_id
    LEFT JOIN folders f ON f.id = d.folder_id
    LEFT JOIN letter_drafts ld ON ld.document_id = d.id AND ld.deleted_at IS NULL
    WHERE a.id = ?
    LIMIT 1");

if (!$stmt) {
    http_response_code(500);
    exit('Gagal memproses permintaan.');
}

mysqli_stmt_bind_param($stmt, "i", $attachment_id);
mysqli_stmt_execute($stmt);
$attachment = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

if (!$attachment) {
    http_response_code(404);
    exit('Lampiran tidak dijumpai.');
}

$has_document_download_access = currentUserCan($conn, 'document', 'read') && currentUserCan($conn, 'document', 'download');
$is_private_draft_attachment = !empty($attachment['draft_id'])
    && (($attachment['draft_status'] ?? '') === 'draf' || ($attachment['draft_approval_status'] ?? '') === 'draft');
if ($is_private_draft_attachment
    && (int) ($attachment['draft_created_by'] ?? 0) !== (int) ($_SESSION['user_id'] ?? 0)
    && ($_SESSION['role'] ?? 'user') !== 'superadmin') {
    http_response_code(403);
    exit('Akses ditolak.');
}
$has_draft_attachment_access = userCanAccessAttachmentViaDraft(
    $conn,
    $draft_id,
    (int) ($attachment['document_id'] ?? 0),
    (int) ($_SESSION['user_id'] ?? 0)
);

if (!$has_document_download_access && !$has_draft_attachment_access) {
    http_response_code(403);
    exit('Akses ditolak.');
}

if (!$has_draft_attachment_access && ($_SESSION['role'] ?? 'user') !== 'superadmin') {
    $user_department = currentUserDepartment($conn);
    if (!isSameDepartmentDb($conn, $attachment['department'] ?? '', $user_department)) {
        http_response_code(403);
        exit('Akses ditolak.');
    }
}

$is_deleted_record = !empty($attachment['document_deleted_at']) || !empty($attachment['folder_deleted_at']);
if ($is_deleted_record && !currentUserCan($conn, 'deleted_item', 'read')) {
    http_response_code(403);
    exit('Akses data dipadam tidak dibenarkan.');
}

$file_path = $attachment['file_path'] ?? '';
$full_file_path = $file_path !== '' && preg_match('/^[A-Za-z]:[\\\\\\/]/', $file_path)
    ? $file_path
    : __DIR__ . '/' . $file_path;
if ($file_path === '' || !file_exists($full_file_path)) {
    http_response_code(404);
    exit('Fail tidak dijumpai.');
}

$filename = $attachment['original_name'] ?: basename($file_path);
$mime_type = mime_content_type($full_file_path);
if ($mime_type === false) {
    $mime_type = 'application/octet-stream';
}

logActivity(
    $conn,
    (int) ($_SESSION['user_id'] ?? 0),
    'download_document_attachment',
    'Download lampiran: ' . $filename . ' (Lampiran ID: ' . $attachment_id . ', Dokumen ID: ' . (int) ($attachment['document_id'] ?? 0) . ')'
);

header('Content-Description: File Transfer');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: inline; filename="' . rawurlencode($filename) . '"');
header('Content-Length: ' . filesize($full_file_path));
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
readfile($full_file_path);
exit();
