<?php
session_start();
include "../config.php";

// =====================================
// CEK LOGIN
// =====================================
if (!isset($_SESSION['id_user']) || $_SESSION['role'] != 'admin') {
    header("Location: ../index.php");
    exit;
}

// =====================================
// FILTER
// =====================================
$search    = $_GET['search'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to   = $_GET['date_to'] ?? '';

$where = "WHERE jv_documents.status = 'didaftarkan'";

if (!empty($search)) {
    $search_safe = $koneksi->real_escape_string($search);
    $where .= " AND (
        jv_documents.nomor_prt LIKE '%$search_safe%' OR
        jv_documents.direksi LIKE '%$search_safe%' OR
        jv_documents.descripsi LIKE '%$search_safe%' OR
        jv_documents.total_adiantamento LIKE '%$search_safe%' OR
        users.full_name LIKE '%$search_safe%'
    )";
}

if (!empty($date_from)) {
    $where .= " AND jv_documents.tgl_terima >= '$date_from'";
}

if (!empty($date_to)) {
    $where .= " AND jv_documents.tgl_terima <= '$date_to'";
}

// =====================================
// QUERY
// =====================================
$query = "
SELECT 
    jv_documents.*,
    users.full_name
FROM jv_documents
LEFT JOIN users 
ON jv_documents.uploaded_by_id = users.id_user
$where
ORDER BY jv_documents.created_at DESC
";

$data = $koneksi->query($query);

// =====================================
// FORMAT TANGGAL PORTUGIS
// =====================================
function formatTanggalPortugal($tanggal)
{
    if (!$tanggal || $tanggal == '0000-00-00') {
        return '-';
    }
    $bulan = [
        1 => 'Janeiru', 2 => 'Fevereiru', 3 => 'Marsu', 4 => 'Abril',
        5 => 'Maiu', 6 => 'Juñu', 7 => 'Jullu', 8 => 'Agostu',
        9 => 'Setembru', 10 => 'Outubru', 11 => 'Novembru', 12 => 'Dezembru'
    ];
    $time = strtotime($tanggal);
    $hari  = date('d', $time);
    $bulanIndex = (int)date('m', $time);
    $tahun = date('Y', $time);
    return $hari . '/' . $bulan[$bulanIndex] . '/' . $tahun;
}

// =====================================
// BUTTON FILE PDF PREVIEW (Updated for Float)
// =====================================
function btnPreview($file)
{
    if (empty($file)) {
        return "<span class='text-muted'>-</span>";
    }
    $url = "../assets/uploads/" . rawurlencode($file);
    // Menggunakan onclick untuk memicu modal float
    return "
        <button type='button' 
                onclick=\"openPdfPreview('$url')\" 
                class='btn-preview'>
            <i class='fas fa-file-pdf'></i> Preview
        </button>
    ";
}
?>

<?php include "../header.php"; ?>
<!-- Script Pemaksa Tampilan Full Width (Diletakkan SEBELUM CSS agar tidak berkedip) -->
<script>
    // Menghapus class yang memaksa margin sidebar dari AdminLTE secara instan
    document.body.classList.remove('sidebar-mini', 'sidebar-open', 'layout-fixed');
    document.body.classList.add('layout-top-nav');
</script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://npmcdn.com/flatpickr/dist/l10n/pt.js"></script>


<style>
:root {
    --emerald-dark: #064e3b;
    --emerald: #047857;
    --emerald-light: #10b981;
    --bg: #f0fdf4;
    --white: #ffffff;
}

/* 1. SEMBUNYIKAN SEMUA ELEMEN BAWAAN TEMPLATE */
.main-header, 
.main-sidebar, 
.main-footer,
#sidebar-overlay { 
    display: none !important; 
}

/* 2. PAKSA WRAPPER UNTUK PENUH DAN MENGHAPUS MARGIN KIRI */
.content-wrapper,
body:not(.sidebar-mini-md):not(.sidebar-mini-xs):not(.layout-top-nav) .content-wrapper {
    margin-left: 0 !important;
    margin-top: 0 !important;
    padding: 30px !important;
    background: var(--bg);
    min-height: 100vh;
    width: 100% !important;
}

/* Memastikan elemen navigasi atas AdminLTE tidak muncul */
.layout-top-nav .wrapper .main-header {
    display: none !important;
}

/* Menghilangkan padding tambahan jika menggunakan AdminLTE */
body:not(.sidebar-mini-md):not(.sidebar-mini-xs):not(.layout-top-nav) .content-wrapper, 
body:not(.sidebar-mini-md):not(.sidebar-mini-xs):not(.layout-top-nav) .main-footer, 
body:not(.sidebar-mini-md):not(.sidebar-mini-xs):not(.layout-top-nav) .main-header {
    margin-left: 0 !important;
}

/* HEADER & CARDS (Sama seperti kode Anda) */
.page-header{
    background:linear-gradient(135deg,var(--emerald-dark),var(--emerald));
    border-radius:18px; padding:30px; color:white; margin-bottom:25px;
    box-shadow:0 10px 30px rgba(0,0,0,.08);
}
.header-flex{ display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:15px; }
.btn-dashboard{ background:white; color:var(--emerald-dark); padding:12px 18px; border-radius:10px; text-decoration:none; font-weight:700; transition:.2s; }
.card-finance{ background:white; border-radius:18px; box-shadow:0 5px 20px rgba(0,0,0,.05); overflow:hidden; }

/* FILTER */
.filter-box{ padding:20px; border-bottom:1px solid #eee; background:#f8fffb; }
.filter-grid{ display:grid; grid-template-columns:2fr 1fr 1fr auto auto; gap:12px; }
.btn-filter{ background:var(--emerald); color:white; border:none; padding:0 22px; border-radius:10px; font-weight:700; cursor:pointer; }
.btn-reset{ background:#ef4444; color:white; padding:11px 18px; border:none; border-radius:10px; font-weight:700; cursor:pointer; }

/* TABLE */
.finance-table{ width:100%; border-collapse:collapse; }
.finance-table thead{ background:var(--emerald-dark); color:white; }
.finance-table th{ padding:14px; font-size:11px; text-transform:uppercase; }
.finance-table td{ padding:14px; border-bottom:1px solid #ecfdf5; font-size: 13px; }

/* BUTTON PREVIEW */
.btn-preview{ 
    border:1px solid #a7f3d0; background:#ecfdf5; color:#065f46; 
    padding:7px 12px; border-radius:8px; font-size:12px; font-weight:700; cursor:pointer;
}

/* =========================
MODAL FLOAT PREVIEW
========================= */
#pdfModal {
    display: none;
    position: fixed;
    z-index: 9999;
    left: 0; top: 0;
    width: 100%; height: 100%;
    background-color: rgba(0,0,0,0.7);
    backdrop-filter: blur(5px);
}
.modal-content-pdf {
    position: relative;
    background-color: #fefefe;
    margin: 2% auto;
    padding: 0;
    width: 80%;
    height: 85vh;
    border-radius: 12px;
    box-shadow: 0 5px 30px rgba(0,0,0,0.3);
}
.close-modal {
    position: absolute;
    right: -15px; top: -15px;
    background: #ef4444;
    color: white;
    width: 35px; height: 35px;
    border-radius: 50%;
    text-align: center; line-height: 35px;
    cursor: pointer; font-weight: bold;
}
.finance-table td {
    max-width: 300px; /* Batasi lebar maksimal */
    word-wrap: break-word; /* Pecah kata jika terlalu panjang */
    white-space: normal; /* Izinkan teks turun ke bawah */
}
</style>

<div class="content-wrapper">
    <div class="page-header">
        <div class="header-flex">
            <div>
                <div class="page-title"><i class="fas fa-folder-open"></i> Dokumentos Registo Ba Review</div>
                <div class="page-subtitle">Sistema Arkivu Finanseiru - Emerald Financial Report</div>
            </div>
            <a href="../dashboard.php" class="btn-dashboard"><i class="fas fa-arrow-left"></i> Dashboard</a>
        </div>
    </div>

    <div class="card-finance">
        <div class="filter-box">
            <form method="GET" id="filterForm">
                <div class="filter-grid">
                    <input type="text" name="search" class="form-control" placeholder="Buka dokumentu..." value="<?= htmlspecialchars($search) ?>">
                    <input type="text" id="date_from" name="date_from" class="form-control" placeholder="Data Hosi" value="<?= htmlspecialchars($date_from) ?>">
                    <input type="text" id="date_to" name="date_to" class="form-control" placeholder="Data To'o" value="<?= htmlspecialchars($date_to) ?>">
                    
                    <button type="submit" class="btn-filter"><i class="fas fa-search"></i> Buka</button>
                    
                    <!-- PERBAIKAN TOMBOL RESET -->
                    <button type="button" onclick="window.location.href='daftar_dokumen.php'" class="btn-reset">Reset</button>
                </div>
            </form>
        </div>

        <div class="table-wrap">
            <table class="finance-table">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Data Simu</th>
                        <th>No Pedido</th>
                        <th>Diresaun</th>
                        <th>Assuntu</th>
                        <th>Montante</th>
                        <th>Dokumentu</th>
                        <th>Anexo</th>
                        <th>Naran</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($data->num_rows > 0): $no = 1; ?>
                    <?php while($row = $data->fetch_assoc()): ?>
                        <tr>
                            <td><?= $no++ ?></td>
                            <td><?= formatTanggalPortugal($row['tgl_terima']) ?></td>
                            <td><strong><?= htmlspecialchars($row['nomor_prt']) ?></strong></td>
                            <td><?= htmlspecialchars($row['direksi']) ?></td>
                            <td style="text-align:left;min-width:250px;"><?= htmlspecialchars($row['descripsi']) ?></td>
                            <td class="money">$ <?= number_format($row['total_adiantamento'],2) ?></td>
                            <td><?= btnPreview($row['file_nota']) ?></td>
                            <td><?= btnPreview($row['lampiran1']) ?></td>
                            <td><?= htmlspecialchars($row['full_name']) ?></td>
                            <td><span class="badge-status">Didaftarkan</span></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="10" style="text-align:center;padding:30px;">Dadus la iha</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- MODAL UNTUK PREVIEW FLOAT -->
<div id="pdfModal">
    <div class="modal-content-pdf">
        <span class="close-modal" onclick="closePdfPreview()">&times;</span>
        <iframe id="pdfFrame" src="" width="100%" height="100%" style="border:none; border-radius:12px;"></iframe>
    </div>
</div>

<script>
// Filter Datepicker
flatpickr("#date_from", { locale:"pt", altInput:true, altFormat:"d/F/Y", dateFormat:"Y-m-d" });
flatpickr("#date_to", { locale:"pt", altInput:true, altFormat:"d/F/Y", dateFormat:"Y-m-d" });

// PERBAIKAN PREVIEW FLOAT
function openPdfPreview(url) {
    document.getElementById('pdfFrame').src = url;
    document.getElementById('pdfModal').style.display = "block";
    document.body.style.overflow = "hidden"; // Stop scrolling background
}

function closePdfPreview() {
    document.getElementById('pdfModal').style.display = "none";
    document.getElementById('pdfFrame').src = "";
    document.body.style.overflow = "auto";
}

// Close modal when clicking outside of it
window.onclick = function(event) {
    let modal = document.getElementById('pdfModal');
    if (event.target == modal) {
        closePdfPreview();
    }
}
</script>

<?php include "../footer.php"; ?>