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

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

// Fungsi Format Tanggal Portugal
function formatTanggalPortugal($tanggal) {
    if (empty($tanggal) || $tanggal == '0000-00-00') return '-';
    $bulan_pt = [
        1 => 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
        'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'
    ];
    $ts = strtotime($tanggal);
    return date('d', $ts) . '/' . $bulan_pt[(int)date('m', $ts)] . '/' . date('Y', $ts);
}

// Fungsi Button Preview PDF
function btnFilePreview($file) {
    if (empty($file)) return "<span class='text-muted'>-</span>";
    $url = "../assets/uploads/" . rawurlencode($file);
    return "<button type='button' onclick=\"previewPDF('{$url}')\" class='btn-file'><i class='fas fa-file-pdf'></i></button>";
}

// Data
$data_didaftarkan = $koneksi->query("SELECT jv_documents.*, users.full_name FROM jv_documents LEFT JOIN users ON jv_documents.uploaded_by_id = users.id_user WHERE jv_documents.status = 'diaudit' ORDER BY jv_documents.tgl_terima ASC");
$data_dikembalikan = $koneksi->query("SELECT jv_documents.*, users.full_name FROM jv_documents LEFT JOIN users ON jv_documents.uploaded_by_id = users.id_user WHERE jv_documents.status = 'dikembalikan' ORDER BY jv_documents.tgl_terima ASC");
?>

<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <title>Finance Verification</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        * { margin:0; padding:0; box-sizing:border-box; }
        body { background:#ecfdf5; font-family:'Segoe UI',sans-serif; color:#1f2937; padding:25px; }
        
        /* Header & Dashboard Button */
        .page-header { 
            background:linear-gradient(135deg,#047857,#10b981); 
            border-radius:20px; padding:30px; color:white; margin-bottom:25px;
            display: flex; justify-content: space-between; align-items: center;
        }
        .btn-dashboard {
            background-color: #d1fae5; color: #065f46; padding: 12px 20px;
            border-radius: 12px; text-decoration: none; font-weight: 700;
            display: flex; align-items: center; gap: 10px; border: 1px solid #a7f3d0;
        }

        /* Search Box One Row */
        .search-box { 
            background: white; padding: 15px 20px; border-radius: 15px; margin-bottom: 25px; 
            display: flex; align-items: center; gap: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.05);
        }
        .search-input { flex: 2; padding: 12px; border: 1px solid #d1fae5; border-radius: 10px; outline: none; }
        .date-input { width: 160px; padding: 11px; border: 1px solid #d1fae5; border-radius: 10px; }
        
        .card { background:white; border-radius:18px; overflow:hidden; margin-bottom:30px; box-shadow:0 4px 12px rgba(0,0,0,0.05); }
        .card-header { padding:15px 25px; font-weight:bold; color:white; }
        .header-green { background:#047857; }
        .header-red { background:#b91c1c; }
        
        table { width:100%; border-collapse:collapse; min-width:1000px; }
        th { background:#f8fafc; padding:15px; font-size:12px; text-transform: uppercase; color:#64748b; border-bottom:2px solid #edf2f7; }
        td { padding:15px; border-bottom:1px solid #f1f5f9; font-size:13px; text-align:center; }

        /* Buttons */
        .btn { padding:10px 16px; border-radius:10px; border:none; cursor:pointer; font-weight:600; font-size:12px; }
        .btn-verifikasi {
    background: #10b981;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
    margin: auto;
    width: fit-content;
    padding: 10px 18px;
}
        
.btn-verifikasi:hover {
    background: #059669;
}
        .btn-search { background:#047857; color:white; padding: 12px 20px; }
        .btn-reset { background:#64748b; color:white; }
        .btn-file { background:#ecfdf5; color:#047857; border:1px solid #a7f3d0; padding:8px; border-radius:8px; cursor:pointer; }
        
        .pdf-preview-container { width: 100%; height: 550px; border: none; }
    </style>
</head>
<body>

<?php if(isset($_SESSION['success'])): ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'Susesu Fo Fila',
    text: '<?= $_SESSION['success']; ?>',
    confirmButtonColor: '#10b981'
});
</script>
<?php unset($_SESSION['success']); ?>
<?php endif; ?>

<div class="page-header">
    <div>
        <h1><i class="fas fa-coins"></i> Finance Document Verification</h1>
        <p>Sistema Profissional Verifikasaun Dokumentu Finance</p>
    </div>
    <a href="../dashboard.php" class="btn-dashboard">
        <i class="fas fa-th-large"></i> Dashboard
    </a>
</div>

<!-- SEARCH SECTION -->
<div class="search-box">
    <i class="fas fa-search" style="color: #10b981;"></i>
    <input type="text" id="keyword" class="search-input" placeholder="Buka No Pedido, Diresaun, ka Assuntu...">
    <label style="font-weight:600; font-size:13px;">Hosi:</label>
    <input type="text" id="date_from" class="date-input datepicker" placeholder="dd/mm/yyyy">
    <label style="font-weight:600; font-size:13px;">To'o:</label>
    <input type="text" id="date_to" class="date-input datepicker" placeholder="dd/mm/yyyy">
    <button type="button" onclick="filterData()" class="btn btn-search">Search</button>
    <button type="button" onclick="resetFilter()" class="btn btn-reset">Reset</button>
</div>

<!-- TABEL DIDAFTARKAN -->
<div class="card">
    <div class="card-header header-green">📄 Documentos Review</div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>No</th>
                    <th>Data Simu Pedido</th>
                    <th>No Pedido</th>
                    <th>Diresaun</th>
                    <th>Assuntu</th>
                    <th>Montante</th>
                    <th>Asaun</>
				</tr>
            </thead>
            <tbody id="tableReview">
                <?php $no=1; while($row = $data_didaftarkan->fetch_assoc()): ?>
                <tr class="data-row" data-date="<?= $row['tgl_terima'] ?>">
                    <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; max-width:300px;"><?= htmlspecialchars($row['descripsi']) ?></td>
                    <td style="font-weight:bold; color:#047857;">$<?= number_format($row['total_adiantamento'], 2) ?></td>
                    
                    <td>
<a href="arsipkonfirmasidok.php?id=<?= $row['id_jv'] ?>" class="btn btn-verifikasi" style="text-decoration:none;">
    <i class="fas fa-shield-check"></i> Verifikasaun
</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>



<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/pt.js"></script>

<script>
// Inisialisasi Flatpickr
flatpickr(".datepicker", {
    dateFormat: "Y-m-d",
    altInput: true,
    altFormat: "d/m/Y",
    locale: "pt"
});

// Fungsi Filter (Tombol Search)
function filterData() {
    const keyword = document.getElementById('keyword').value.toLowerCase();
    const fromDate = document.getElementById('date_from').value;
    const toDate = document.getElementById('date_to').value;
    const rows = document.querySelectorAll('.data-row');

    rows.forEach(row => {
        const rowText = row.innerText.toLowerCase();
        const rowDate = row.getAttribute('data-date');
        
        let matchKeyword = rowText.includes(keyword);
        let matchDate = true;

        if (fromDate && toDate) {
            matchDate = (rowDate >= fromDate && rowDate <= toDate);
        } else if (fromDate) {
            matchDate = (rowDate >= fromDate);
        } else if (toDate) {
            matchDate = (rowDate <= toDate);
        }

        row.style.display = (matchKeyword && matchDate) ? "" : "none";
    });
}

// Fungsi Reset (Tombol Reset)
function resetFilter() {
    document.getElementById('keyword').value = "";
    
    // Pastikan instance flatpickr ada sebelum clear
    const fpHosi = document.getElementById('date_from')._flatpickr;
    const fpToo = document.getElementById('date_to')._flatpickr;
    
    if (fpHosi) fpHosi.clear();
    if (fpToo) fpToo.clear();

    document.querySelectorAll('.data-row').forEach(row => {
        row.style.display = "";
    });
}

// Tombol Verifikasaun Tunggal
function verifikasiDokumen(id) {
    Swal.fire({
        title: 'Verifikasaun Dokumentu',
        text: "Ita boot hakarak halo saida ba dokumentu ida ne'e?",
        icon: 'question',
        showCancelButton: true,
        showDenyButton: true,
        confirmButtonText: '<i class="fas fa-check"></i> Teruskan',
        denyButtonText: '<i class="fas fa-undo"></i> Kembalikan',
        cancelButtonText: 'Kansela',
        confirmButtonColor: '#10b981',
        denyButtonColor: '#ef4444'
    }).then((result) => {
        if (result.isConfirmed) {
            // Proses Teruskan
            window.location.href = `verifikasi.php?action=teruskan&id=${id}`;
        } else if (result.isDenied) {
            // Proses Kembalikan dengan Alasan
            Swal.fire({
                title: 'Alasan dikembalikan',
                input: 'textarea',
                inputPlaceholder: 'Hatama alasan...',
                showCancelButton: true,
                confirmButtonText: 'Envia'
            }).then((alasanText) => {
                if (alasanText.isConfirmed && alasanText.value) {
                    window.location.href = `verifikasi.php?action=kembalikan&id=${id}&alasan=${encodeURIComponent(alasanText.value)}`;
                }
            });
        }
    });
}
</script>
</body>
</html>