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

// Set timezone to Malaysia (UTC+8)
date_default_timezone_set('Asia/Kuala_Lumpur');

// DAPATKAN ROLE UNTUK SIDEBAR CONSISTENCY
$role = $_SESSION['role'] ?? 'user';
$user_department = currentUserDepartment($conn);

if (!currentUserCan($conn, 'folder', 'read') || !currentUserCan($conn, 'document', 'read')) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk mencetak laporan ini.'); window.close();</script>";
    exit();
}

if (!isset($_GET['folder_id'])) {
    echo "<script>alert('ID fail tidak sah.'); window.close();</script>";
    exit();
}

$folder_id_raw = $_GET['folder_id'];
$folder_id = intval($folder_id_raw);

if ($folder_id <= 0) {
    echo "<script>alert('ID fail tidak sah.'); window.close();</script>";
    exit();
}

// Maklumat folder
$folder_sql = mysqli_prepare($conn, "SELECT * FROM folders WHERE id = ? AND deleted_at IS NULL");
mysqli_stmt_bind_param($folder_sql, "i", $folder_id);
mysqli_stmt_execute($folder_sql);
$folder = mysqli_fetch_assoc(mysqli_stmt_get_result($folder_sql));

if (!$folder) {
    echo "<script>alert('Fail tidak dijumpai.'); window.close();</script>";
    exit();
}

if ($role !== 'superadmin' && !isSameDepartmentDb($conn, $folder['department'] ?? '', $user_department)) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk mencetak laporan fail ini.'); window.close();</script>";
    exit();
}

// Semua surat dalam fail (tanpa pagination)
$doc_sql = mysqli_prepare($conn, "SELECT d.*
    FROM documents d
    LEFT JOIN letter_drafts ld ON ld.document_id = d.id AND ld.deleted_at IS NULL
    WHERE d.folder_id = ?
      AND d.deleted_at IS NULL
      AND (
          ld.id IS NULL
          OR ld.approval_status = 'lulus'
      )
    ORDER BY d.doc_date ASC");
mysqli_stmt_bind_param($doc_sql, "i", $folder_id);
mysqli_stmt_execute($doc_sql);
$documents = mysqli_fetch_all(mysqli_stmt_get_result($doc_sql), MYSQLI_ASSOC);
$draft_letter_map = getLetterDraftMapByDocumentIds($conn, array_column($documents, 'id'));
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Fail - <?php echo htmlspecialchars($folder['folder_name']); ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            font-size: 12px;
            line-height: 1.4;
            color: #000;
            background: #fff;
            padding: 20px;
        }
        .report-header {
            text-align: center;
            margin-bottom: 20px;
            border-bottom: 2px solid #000;
            padding-bottom: 15px;
        }
        .report-header h1 {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .report-header h2 {
            font-size: 14px;
            font-weight: normal;
            margin-bottom: 5px;
        }
        .report-header .folder-info {
            font-size: 12px;
            margin-top: 10px;
        }
        .report-header .folder-info span {
            margin: 0 10px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        table th {
            background: #f0f0f0;
            border: 1px solid #000;
            padding: 8px;
            text-align: center;
            font-weight: bold;
            font-size: 11px;
        }
        table td {
            border: 1px solid #000;
            padding: 6px 8px;
            vertical-align: top;
        }
        table th:first-child, table td:first-child {
            width: 50px;
            text-align: center;
        }
        table th:nth-child(2), table td:nth-child(2) {
            width: 40%;
        }
        table th:nth-child(3), table td:nth-child(3) {
            width: 30%;
        }
        table th:nth-child(4), table td:nth-child(4) {
            width: 25%;
            text-align: center;
        }
        .print-button {
            position: fixed;
            top: 10px;
            right: 10px;
            padding: 10px 20px;
            background: #0077b6;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            z-index: 1000;
        }
        .print-button:hover {
            background: #005f99;
        }
        .no-data {
            text-align: center;
            padding: 30px;
            font-style: italic;
        }
        @page {
            size: A4 portrait;
            margin: 15mm;
        }
        @media print {
            .print-button {
                display: none;
            }
            body {
                padding: 0;
            }
            table {
                page-break-inside: auto;
            }
            tr {
                page-break-inside: avoid;
                page-break-after: auto;
            }
            thead {
                display: table-header-group;
            }
        }
    </style>
</head>
<body>
    <button class="print-button" onclick="window.print()">
        <i class="fas fa-print"></i> Cetak
    </button>

    <div class="report-header">
        <h1>LAPORAN FAIL</h1>
        <h2><?php echo htmlspecialchars($folder['folder_name']); ?></h2>
        <div class="folder-info">
            <span><strong>Kod Fail:</strong> <?php echo htmlspecialchars($folder['folder_code']); ?></span>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th>Bil</th>
                <th>Perkara</th>
                <th>Kepada</th>
                <th>Tarikh</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($documents)): ?>
                <tr>
                    <td colspan="4" class="no-data">Tiada surat dalam fail ini.</td>
                </tr>
            <?php else: ?>
                <?php foreach ($documents as $index => $doc): 
                    $linked_draft = $draft_letter_map[(int) ($doc['id'] ?? 0)] ?? null;
                    $subject_words = preg_split('/\s+/', trim((string) ($doc['subject'] ?? '')), -1, PREG_SPLIT_NO_EMPTY);
                    $subject_display = count($subject_words) > 8
                        ? implode(' ', array_slice($subject_words, 0, 8)) . '...'
                        : implode(' ', $subject_words);
                    $to_person = strcasecmp(trim((string) (($linked_draft['doc_type'] ?? '') ?: ($doc['doc_type'] ?? ''))), 'Surat Rasmi') === 0 
                        ? 'Seperti tertulis dalam surat.' 
                        : ($doc['to_person'] ?? '');
                ?>
                <tr>
                    <td><?php echo $index + 1; ?></td>
                    <td><?php echo htmlspecialchars($subject_display); ?></td>
                    <td><?php echo htmlspecialchars($to_person); ?></td>
                    <td><?php echo date('d/m/Y', strtotime($doc['doc_date'])); ?></td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

    <div style="margin-top: 30px; text-align: right; font-size: 11px;">
        <p><strong>Jumlah Surat:</strong> <?php echo count($documents); ?></p>
        <p><strong>Tarikh Cetak:</strong> <?php echo date('d/m/Y H:i'); ?></p>
    </div>

    <script>
        // Auto print on load (optional - comment out if not desired)
        // window.onload = function() {
        //     window.print();
        // };
    </script>
</body>
</html>
