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

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

// =====================================
// HANDLE SUBMIT (ubah status)
// =====================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submit') {
    $id_jv = (int)($_POST['id_jv'] ?? 0);
    if ($id_jv > 0) {
        $stmt = $koneksi->prepare("UPDATE jv_documents SET status = 'disubmit' WHERE id_jv = ?");
        $stmt->bind_param("i", $id_jv);
        $stmt->execute();
        $stmt->close();
        $_SESSION['alert_success'] = 'Dokumentu ho ID ' . $id_jv . ' susesu disubmit!';
    }
    header("Location: daftar_dokumen.php?" . http_build_query(array_filter([
        'search'    => $_GET['search']    ?? '',
        'date_from' => $_GET['date_from'] ?? '',
        'date_to'   => $_GET['date_to']   ?? '',
    ])));
    exit;
}

// =====================================
// HANDLE APAGA (hapus data)
// =====================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'apaga') {
    $id_jv = (int)($_POST['id_jv'] ?? 0);
    if ($id_jv > 0) {
        $stmt = $koneksi->prepare("DELETE FROM jv_documents WHERE id_jv = ?");
        $stmt->bind_param("i", $id_jv);
        $stmt->execute();
        $stmt->close();
        $_SESSION['alert_delete'] = 'Dokumentu susesu apagadu!';
    }
    header("Location: daftar_dokumen.php?" . http_build_query(array_filter([
        'search'    => $_GET['search']    ?? '',
        'date_from' => $_GET['date_from'] ?? '',
        'date_to'   => $_GET['date_to']   ?? '',
    ])));
    exit;
}

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

// --- WHERE untuk tabel DIDAFTARKAN ---
$where_didaftarkan = "WHERE jv_documents.status = 'didaftarkan'";

// --- WHERE untuk tabel FO FILA (dikembalikan) ---
$where_fofila = "WHERE jv_documents.status = 'dikembalikan'";

if (!empty($search)) {
    $search_safe = $koneksi->real_escape_string($search);
    $cond = " 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%'
    )";
    $where_didaftarkan .= $cond;
    $where_fofila      .= $cond;
}

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

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

// =====================================
// QUERY — DIDAFTARKAN
// =====================================
$query_didaftarkan = "
    SELECT jv_documents.*, users.full_name
    FROM jv_documents
    LEFT JOIN users ON jv_documents.uploaded_by_id = users.id_user
    $where_didaftarkan
    ORDER BY jv_documents.tgl_terima ASC
";
$data_didaftarkan = $koneksi->query($query_didaftarkan);

// =====================================
// QUERY — FO FILA (DIKEMBALIKAN)
// =====================================
$query_fofila = "
    SELECT jv_documents.*, users.full_name
    FROM jv_documents
    LEFT JOIN users ON jv_documents.uploaded_by_id = users.id_user
    $where_fofila
    ORDER BY jv_documents.tgl_terima ASC
";
$data_fofila = $koneksi->query($query_fofila);

// =====================================
// 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);
    return date('d',$time).'/'.$bulan[(int)date('m',$time)].'/'.date('Y',$time);
}

// =====================================
// BUTTON PREVIEW
// =====================================
function btnPreview($file)
{
    if (empty($file)) return "<span class='text-muted'>-</span>";
    $url = "../assets/uploads/" . rawurlencode($file);
    return "
        <button type='button' onclick=\"openPdfPreview('$url')\" class='btn-preview'>
            <i class='fas fa-file-pdf'></i> Preview
        </button>
    ";
}

// =====================================
// AMBIL ALERT DARI SESSION
// =====================================
$alert_success = $_SESSION['alert_success'] ?? null;
$alert_delete  = $_SESSION['alert_delete']  ?? null;
unset($_SESSION['alert_success'], $_SESSION['alert_delete']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dokumentos Registo</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/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;
}

/* Sembunyikan elemen AdminLTE */
.main-header, .main-sidebar, .main-footer, #sidebar-overlay { display: none !important; }
.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: 0 !important;
    background: var(--bg);
    min-height: 100vh;
    width: 100% !important;
}

body {
    margin: 0; padding: 0;
    background: var(--bg);
    font-family: Arial, sans-serif;
}

.main-container { padding: 30px; min-height: 100vh; }

/* HEADER */
.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; }
.page-title   { font-size: 20px; font-weight: 700; }
.page-subtitle{ font-size: 13px; opacity: .8; margin-top: 4px; }
.btn-dashboard {
    background: white; color: var(--emerald-dark);
    padding: 12px 18px; border-radius: 10px;
    text-decoration: none; font-weight: 700; transition: .2s;
}

/* ALERT */
.alert-box {
    padding: 14px 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    font-weight: 600;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 10px;
    animation: fadeIn .4s ease;
}
.alert-success { background: #d1fae5; color: #065f46; border: 1px solid #6ee7b7; }
.alert-danger  { background: #fee2e2; color: #991b1b; border: 1px solid #fca5a5; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(-8px); } to { opacity: 1; transform: translateY(0); } }

/* CARD */
.card-finance {
    background: white; border-radius: 18px;
    box-shadow: 0 5px 20px rgba(0,0,0,.05);
    overflow: hidden; margin-bottom: 30px;
}

.card {
    background: white; border-radius: 18px;
    box-shadow: 0 5px 20px rgba(0,0,0,.05);
    overflow: hidden; margin-bottom: 30px;
}
.card-header {
    padding: 16px 20px;
    font-weight: 700; font-size: 15px;
    border-bottom: 1px solid #eee;
}
.header-red { background: #fef2f2; color: #b91c1c; border-bottom-color: #fecaca; }

/* 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; margin-top: 8px; }
.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; text-align: left; }
.finance-table td   {
    padding: 14px; border-bottom: 1px solid #ecfdf5;
    font-size: 13px; word-wrap: break-word; white-space: normal;
}

/* tabel fo fila: header merah */
.table-fofila thead { background: #b91c1c; color: white; }
.table-fofila td    { border-bottom: 1px solid #fee2e2; }

/* ACTION BUTTONS */
.btn-action-group {
    display: flex;
    gap: 6px;
    align-items: center;
}

.btn-edit {
    background: #eff6ff;
    color: #1d4ed8;
    border: 1px solid #bfdbfe;
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 700;
    cursor: pointer;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    transition: background .2s;
}
.btn-edit:hover { background: #dbeafe; }

.btn-submit {
    background: #f0fdf4;
    color: #15803d;
    border: 1px solid #bbf7d0;
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 700;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    transition: background .2s;
}
.btn-submit:hover { background: #dcfce7; }

.btn-apaga {
    background: #fff1f2;
    color: #be123c;
    border: 1px solid #fecdd3;
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 700;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    transition: background .2s;
}
.btn-apaga:hover { background: #ffe4e6; }

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

.badge-status {
    background: #d1fae5; color: #065f46;
    padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700;
}
.badge-fofila {
    background: #fee2e2; color: #b91c1c;
    padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700;
}

.text-muted { color: #9ca3af; }

/* MODAL 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; font-size: 16px;
}

/* CONFIRM MODAL */
#confirmModal {
    display: none; position: fixed; z-index: 10000;
    left: 0; top: 0; width: 100%; height: 100%;
    background: rgba(0,0,0,0.5);
    backdrop-filter: blur(4px);
}
.confirm-box {
    background: white;
    border-radius: 18px;
    padding: 30px;
    width: 400px;
    max-width: 90%;
    margin: 15% auto;
    text-align: center;
    box-shadow: 0 20px 60px rgba(0,0,0,0.2);
    animation: fadeIn .3s ease;
}
.confirm-box h3 { margin: 0 0 10px; font-size: 18px; color: #111; }
.confirm-box p  { color: #6b7280; font-size: 14px; margin-bottom: 24px; }
.confirm-actions { display: flex; gap: 10px; justify-content: center; }
.btn-confirm-yes {
    background: #ef4444; color: white;
    border: none; padding: 10px 24px; border-radius: 10px;
    font-weight: 700; cursor: pointer; font-size: 14px;
}
.btn-confirm-no {
    background: #f3f4f6; color: #374151;
    border: none; padding: 10px 24px; border-radius: 10px;
    font-weight: 700; cursor: pointer; font-size: 14px;
}
</style>
</head>
<body>
<div class="main-container">

    <!-- HEADER -->
    <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">MSSI - Sistema Informasaun Transaksaun Pagamento</div>
            </div>
            <a href="../dashboard.php" class="btn-dashboard"><i class="fas fa-arrow-left"></i> Dashboard</a>
        </div>
    </div>

    <!-- ALERT SUKSES SUBMIT -->
    <?php if ($alert_success): ?>
    <div class="alert-box alert-success">
        <i class="fas fa-check-circle"></i>
        <?= htmlspecialchars($alert_success) ?>
    </div>
    <?php endif; ?>

    <!-- ALERT SUKSES HAPUS -->
    <?php if ($alert_delete): ?>
    <div class="alert-box alert-danger">
        <i class="fas fa-trash-alt"></i>
        <?= htmlspecialchars($alert_delete) ?>
    </div>
    <?php endif; ?>

    <!-- ==============================
         TABEL 1: DIDAFTARKAN
    ============================== -->
    <div class="card-finance">
        <!-- Filter -->
        <div class="filter-box">
            <form method="GET" id="filterForm">
                <label><strong>Search</strong></label>
                <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>
                    <button type="button" onclick="window.location.href='daftar_dokumen.php'" class="btn-reset">Reset</button>
                </div>
            </form>
        </div>

        <!-- Tabel -->
        <div style="overflow-x:auto;">
            <table class="finance-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>Dokumentu</th>
                        <th>Anexo</th>
                        <th>Naran</th>
                        <th>Status</th>
                        <th>Asaun</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($data_didaftarkan && $data_didaftarkan->num_rows > 0): $no = 1; ?>
                    <?php while ($row = $data_didaftarkan->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>$ <?= 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">rejistu</span></td>
                        <td>
                            <div class="btn-action-group">
                                <!-- Tombol Edit -->
                                <a href="editdok.php?id=<?= $row['id_jv'] ?>" class="btn-edit">
    <i class="fas fa-edit"></i> Edita
</a>
                                <!-- Tombol Submit -->
                                <button type="button"
                                    class="btn-submit"
                                    onclick="confirmSubmit(<?= $row['id_jv'] ?>, '<?= htmlspecialchars($row['nomor_prt'], ENT_QUOTES) ?>')">
                                    <i class="fas fa-paper-plane"></i> Rejistu
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="11" style="text-align:center; padding:30px;">Dadus la iha</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div><!-- /card-finance -->

    <!-- ==============================
         TABEL 2: FO FILA (DIKEMBALIKAN)
    ============================== -->
    <div class="card">
        <div class="card-header header-red">
            <i class="fas fa-times-circle"></i> Dokumentu Fo Fila (Dikembalikan)
        </div>
        <div style="overflow-x:auto;">
            <table class="finance-table table-fofila">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Razaun</th>
                        <th>Data Simu Pedido</th>
                        <th>No Pedido</th>
                        <th>Diresaun</th>
                        <th>Assuntu</th>
                        <th>Montante</th>
                        <th>Dokumentu</th>
                        <th>Anexo</th>
                        <th>Naran</th>
                        <th>Asaun</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($data_fofila && $data_fofila->num_rows > 0): $no = 1; ?>
                    <?php while ($row = $data_fofila->fetch_assoc()): ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td style="color:#b91c1c; font-style:italic;">
                            <?= htmlspecialchars($row['alasan_dikembalikan'] ?? '-') ?>
                        </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 style="font-weight:bold; color:#047857;">
                            $ <?= 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>
                            <div class="btn-action-group">
                                <!-- Tombol Edit -->
                                <a href="edit.php?id=<?= $row['id_jv'] ?>" class="btn-edit">
                                    <i class="fas fa-edit"></i> Edita
                                </a>
                                <!-- Tombol Apaga -->
                                <button type="button"
                                    class="btn-apaga"
                                    onclick="confirmApaga(<?= $row['id_jv'] ?>, '<?= htmlspecialchars($row['nomor_prt'], ENT_QUOTES) ?>')">
                                    <i class="fas fa-trash-alt"></i> Apaga
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="11" style="text-align:center; padding:30px;">Dadus la iha</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div><!-- /card fo fila -->

</div><!-- /main-container -->

<!-- MODAL PREVIEW PDF -->
<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>

<!-- FORM SUBMIT (hidden) -->
<form id="formSubmit" method="POST" style="display:none;">
    <input type="hidden" name="action" value="submit">
    <input type="hidden" name="id_jv" id="submitId">
</form>

<!-- FORM APAGA (hidden) -->
<form id="formApaga" method="POST" style="display:none;">
    <input type="hidden" name="action" value="apaga">
    <input type="hidden" name="id_jv" id="apagaId">
</form>

<!-- CONFIRM MODAL SUBMIT -->
<div id="confirmModal">
    <div class="confirm-box">
        <div style="font-size:40px; margin-bottom:10px;">📤</div>
        <h3>Konfirma Submete</h3>
        <p id="confirmSubmitMsg">Ita-boot hakarak submete dokumentu ida ne'e?</p>
        <div class="confirm-actions">
            <button class="btn-confirm-no" onclick="closeConfirm()">Kansela</button>
            <button class="btn-confirm-yes" style="background:#15803d;" onclick="doSubmit()">
                <i class="fas fa-paper-plane"></i> Submete
            </button>
        </div>
    </div>
</div>

<!-- CONFIRM MODAL APAGA -->
<div id="confirmApagaModal">
    <div class="confirm-box" style="display:none;" id="confirmApagaBox">
        <div style="font-size:40px; margin-bottom:10px;">🗑️</div>
        <h3>Konfirma Apaga</h3>
        <p id="confirmApagaMsg">Ita-boot hakarak apaga dokumentu ida ne'e? Asaun ne'e la bele desfaz!</p>
        <div class="confirm-actions">
            <button class="btn-confirm-no" onclick="closeApagaConfirm()">Kansela</button>
            <button class="btn-confirm-yes" onclick="doApaga()">
                <i class="fas fa-trash-alt"></i> Apaga
            </button>
        </div>
    </div>
</div>

<!-- CONFIRM APAGA MODAL (standalone) -->
<div id="modalApagaOverlay" style="
    display:none; position:fixed; z-index:10000;
    left:0; top:0; width:100%; height:100%;
    background:rgba(0,0,0,0.5); backdrop-filter:blur(4px);">
    <div style="
        background:white; border-radius:18px; padding:30px;
        width:400px; max-width:90%; margin:15% auto;
        text-align:center; box-shadow:0 20px 60px rgba(0,0,0,.2);
        animation: fadeIn .3s ease;">
        <div style="font-size:40px; margin-bottom:10px;">🗑️</div>
        <h3 style="margin:0 0 10px; font-size:18px; color:#111;">Konfirma Apaga</h3>
        <p id="msgApaga" style="color:#6b7280; font-size:14px; margin-bottom:24px;"></p>
        <div style="display:flex; gap:10px; justify-content:center;">
            <button class="btn-confirm-no" onclick="closeApaga()">Kansela</button>
            <button class="btn-confirm-yes" onclick="doApaga()">
                <i class="fas fa-trash-alt"></i> Apaga
            </button>
        </div>
    </div>
</div>

<!-- CONFIRM SUBMIT MODAL (standalone) -->
<div id="modalSubmitOverlay" style="
    display:none; position:fixed; z-index:10000;
    left:0; top:0; width:100%; height:100%;
    background:rgba(0,0,0,0.5); backdrop-filter:blur(4px);">
    <div style="
        background:white; border-radius:18px; padding:30px;
        width:400px; max-width:90%; margin:15% auto;
        text-align:center; box-shadow:0 20px 60px rgba(0,0,0,.2);
        animation: fadeIn .3s ease;">
        <div style="font-size:40px; margin-bottom:10px;">📤</div>
        <h3 style="margin:0 0 10px; font-size:18px; color:#111;">Konfirma Submete</h3>
        <p id="msgSubmit" style="color:#6b7280; font-size:14px; margin-bottom:24px;"></p>
        <div style="display:flex; gap:10px; justify-content:center;">
            <button class="btn-confirm-no" onclick="closeSubmit()">Kansela</button>
            <button class="btn-confirm-yes" style="background:#15803d;" onclick="doSubmit()">
                <i class="fas fa-paper-plane"></i> Submete
            </button>
        </div>
    </div>
</div>

<script>
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" });

// ---- PDF Preview ----
function openPdfPreview(url) {
    document.getElementById('pdfFrame').src = url;
    document.getElementById('pdfModal').style.display = "block";
    document.body.style.overflow = "hidden";
}
function closePdfPreview() {
    document.getElementById('pdfModal').style.display = "none";
    document.getElementById('pdfFrame').src = "";
    document.body.style.overflow = "auto";
}
window.onclick = function(event) {
    if (event.target == document.getElementById('pdfModal')) closePdfPreview();
    if (event.target == document.getElementById('modalSubmitOverlay')) closeSubmit();
    if (event.target == document.getElementById('modalApagaOverlay')) closeApaga();
}

// ---- SUBMIT ----
var pendingSubmitId = null;
function confirmSubmit(id, nomor) {
    pendingSubmitId = id;
    document.getElementById('msgSubmit').textContent =
        'Ita-boot hakarak submete dokumentu "' + nomor + '"?';
    document.getElementById('modalSubmitOverlay').style.display = 'block';
}
function closeSubmit() {
    document.getElementById('modalSubmitOverlay').style.display = 'none';
    pendingSubmitId = null;
}
function doSubmit() {
    if (!pendingSubmitId) return;
    document.getElementById('submitId').value = pendingSubmitId;
    document.getElementById('formSubmit').submit();
}

// ---- APAGA ----
var pendingApagaId = null;
function confirmApaga(id, nomor) {
    pendingApagaId = id;
    document.getElementById('msgApaga').textContent =
        'Ita-boot hakarak apaga dokumentu "' + nomor + '"? Asaun ne\'e la bele desfaz!';
    document.getElementById('modalApagaOverlay').style.display = 'block';
}
function closeApaga() {
    document.getElementById('modalApagaOverlay').style.display = 'none';
    pendingApagaId = null;
}
function doApaga() {
    if (!pendingApagaId) return;
    document.getElementById('apagaId').value = pendingApagaId;
    document.getElementById('formApaga').submit();
}

// Auto-hide alerts setelah 4 detik
setTimeout(function() {
    var alerts = document.querySelectorAll('.alert-box');
    alerts.forEach(function(el) {
        el.style.transition = 'opacity .5s';
        el.style.opacity = '0';
        setTimeout(function(){ el.style.display = 'none'; }, 500);
    });
}, 4000);
</script>
</body>
</html>