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

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

function formatTanggalPortugal($tanggal)
{
    if (empty($tanggal) || $tanggal == '0000-00-00') return '-';

    $bulan = [
        1  => 'Janeiro', 'Fevereiro', 'Março',     'Abril',
               'Maio',   'Junho',     'Julho',      'Agosto',
               'Setembro','Outubro',  'Novembro',   'Dezembro'
    ];

    $ts = strtotime($tanggal);
    return date('d', $ts) . '/' . $bulan[(int)date('m', $ts)] . '/' . date('Y', $ts);
}

function formatUSD($nominal)
{
    return '$ ' . number_format((float)$nominal, 2, '.', ',');
}

/* ── FILTER ── */
$search = $_GET['search'] ?? '';
$date1  = $_GET['date1']  ?? '';   // yyyy-MM-dd (nilai DB)
$date2  = $_GET['date2']  ?? '';

$where = "WHERE status = 'review'";

if (!empty($search)) {
    $s = $koneksi->real_escape_string($search);
    $where .= " AND (
        nomor_prt   LIKE '%$s%' OR
        direksi     LIKE '%$s%' OR
        descripsi   LIKE '%$s%' OR
        nomor_cpv    LIKE '%$s%' OR
        nomor_obl   LIKE '%$s%' OR
        vendor_name LIKE '%$s%'
    )";
}

if (!empty($date1) && !empty($date2)) {
    $where .= " AND DATE(tgl_terima) BETWEEN '$date1' AND '$date2'";
}

$query = $koneksi->query("
    SELECT * FROM jv_documents
    $where
    ORDER BY tgl_terima ASC
");

/* Hitung total baris & montante untuk summary cards */
$total_rows    = 0;
$total_amount  = 0;
$rows_data     = [];

while ($r = $query->fetch_assoc()) {
    $rows_data[]   = $r;
    $total_rows++;
    $total_amount += (float)$r['total_adiantamento'];
}
?>
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arsipu Konfirmasaun — Finance System</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
/* ── RESET & BASE ── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

:root {
    --em-900: #022c22;
    --em-800: #064e3b;
    --em-700: #065f46;
    --em-600: #047857;
    --em-500: #059669;
    --em-400: #10b981;
    --em-300: #34d399;
    --em-200: #6ee7b7;
    --em-100: #a7f3d0;
    --em-50:  #d1fae5;
    --em-25:  #ecfdf5;
    --gray-900: #111827;
    --gray-700: #374151;
    --gray-500: #6b7280;
    --gray-300: #d1d5db;
    --gray-100: #f3f4f6;
    --white: #ffffff;
    --red: #ef4444;
    --red-dark: #dc2626;
}

html, body {
    height: 100%;
    font-family: 'Segoe UI', system-ui, sans-serif;
    background: var(--em-25);
    color: var(--gray-900);
}

/* ── FULL PAGE LAYOUT ── */
.page {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

/* ── TOP BAR ── */
.topbar {
    background: var(--em-800);
    color: var(--white);
    padding: 0 32px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: sticky;
    top: 0;
    z-index: 100;
    box-shadow: 0 2px 12px rgba(0,0,0,0.18);
    flex-shrink: 0;
}

.topbar-left {
    display: flex;
    align-items: center;
    gap: 14px;
}

.topbar-logo {
    width: 34px; height: 34px;
    background: var(--em-500);
    border-radius: 8px;
    display: flex; align-items: center; justify-content: center;
    font-size: 16px;
}

.topbar-title {
    font-size: 16px;
    font-weight: 700;
    letter-spacing: 0.3px;
}

.topbar-subtitle {
    font-size: 11px;
    color: var(--em-200);
    margin-top: 1px;
}

.topbar-right {
    display: flex;
    align-items: center;
    gap: 10px;
}

.btn-dashboard {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 18px;
    background: var(--em-500);
    color: var(--white);
    border: none;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    transition: background 0.2s, transform 0.15s;
}
.btn-dashboard:hover {
    background: var(--em-400);
    transform: translateY(-1px);
}

/* ── MAIN ── */
.main {
    flex: 1;
    padding: 28px 32px 40px;
    max-width: 1600px;
    width: 100%;
    margin: 0 auto;
}

/* ── PAGE HEADING ── */
.page-heading {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    margin-bottom: 24px;
}

.page-heading h1 {
    font-size: 24px;
    font-weight: 800;
    color: var(--em-800);
}

.page-heading .breadcrumb {
    font-size: 12px;
    color: var(--gray-500);
    margin-top: 4px;
}

.badge-live {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: var(--em-50);
    border: 1px solid var(--em-200);
    color: var(--em-700);
    font-size: 12px;
    font-weight: 600;
    padding: 5px 12px;
    border-radius: 20px;
}

.badge-live::before {
    content: '';
    width: 7px; height: 7px;
    background: var(--em-400);
    border-radius: 50%;
    animation: pulse 1.5s infinite;
}

@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.3; }
}

/* ── SUMMARY CARDS ── */
.summary-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 24px;
}

.sum-card {
    background: var(--white);
    border: 1px solid var(--em-50);
    border-radius: 14px;
    padding: 18px 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    box-shadow: 0 2px 8px rgba(6,78,59,0.06);
}

.sum-icon {
    width: 44px; height: 44px;
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    flex-shrink: 0;
}

.sum-icon.green  { background: var(--em-50);  color: var(--em-600); }
.sum-icon.teal   { background: #e0f2fe;        color: #0369a1; }
.sum-icon.amber  { background: #fefce8;        color: #a16207; }

.sum-label { font-size: 11px; font-weight: 600; color: var(--gray-500); text-transform: uppercase; letter-spacing: 0.8px; margin-bottom: 4px; }
.sum-value { font-size: 22px; font-weight: 800; color: var(--em-800); line-height: 1; }
.sum-value.usd  { color: var(--em-500); }

/* ── FILTER PANEL ── */
.filter-panel {
    background: var(--white);
    border: 1px solid var(--em-50);
    border-radius: 14px;
    padding: 18px 22px;
    margin-bottom: 22px;
    box-shadow: 0 2px 8px rgba(6,78,59,0.05);
}

.filter-panel form {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-end;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.filter-group label {
    font-size: 10px;
    font-weight: 700;
    color: var(--em-600);
    text-transform: uppercase;
    letter-spacing: 0.8px;
}

.filter-group input[type="text"],
.filter-group .date-display {
    height: 40px;
    padding: 0 12px;
    border: 1px solid var(--em-50);
    border-radius: 9px;
    font-size: 13px;
    color: var(--gray-900);
    background: var(--white);
    outline: none;
    transition: border 0.2s, box-shadow 0.2s;
}

.filter-group input[type="text"]:focus {
    border-color: var(--em-400);
    box-shadow: 0 0 0 3px rgba(16,185,129,0.12);
}

.filter-group input[type="text"]::placeholder { color: var(--em-200); }

.filter-group.search-group { flex: 1; min-width: 200px; }

/* Date wrapper */
.date-field-wrap { position: relative; }
.date-display {
    min-width: 160px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px;
    border: 1px solid var(--em-50);
    border-radius: 9px;
    font-size: 13px;
    color: var(--gray-900);
    background: var(--white);
    user-select: none;
    transition: border 0.2s, box-shadow 0.2s;
}
.date-display:hover { border-color: var(--em-300); }
.date-display .ph { color: var(--em-200); }
.date-display .cal-ic { color: var(--em-300); font-size: 13px; }

/* hidden iso input */
input.date-iso { display: none; }

/* Date picker dropdown */
.dp-dropdown {
    position: absolute;
    top: calc(100% + 6px);
    left: 0;
    background: var(--white);
    border: 1px solid var(--em-50);
    border-radius: 14px;
    padding: 16px;
    z-index: 500;
    min-width: 268px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.12);
    display: none;
}
.dp-dropdown.open { display: block; }

.dp-hd { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
.dp-nav-btn {
    background: var(--em-25); border: none; cursor: pointer;
    padding: 4px 10px; border-radius: 7px; color: var(--em-600); font-size: 16px;
}
.dp-nav-btn:hover { background: var(--em-50); }
.dp-month-title { font-size: 13px; font-weight: 700; color: var(--em-800); }

.dp-grid { display: grid; grid-template-columns: repeat(7,1fr); gap: 2px; text-align: center; }
.dp-dn { font-size: 9px; font-weight: 700; color: var(--em-200); padding: 3px 0; }
.dp-d {
    font-size: 12px; padding: 5px 2px; border-radius: 6px;
    cursor: pointer; color: var(--gray-700);
}
.dp-d:hover { background: var(--em-25); }
.dp-d.sel { background: var(--em-500); color: var(--white); font-weight: 700; }
.dp-d.tod { border: 1px solid var(--em-400); color: var(--em-600); }
.dp-d.emp { pointer-events: none; }

/* Filter buttons */
.btn-filter {
    height: 40px;
    display: inline-flex; align-items: center; gap: 8px;
    padding: 0 18px; border-radius: 9px;
    font-size: 13px; font-weight: 600;
    border: none; cursor: pointer;
    text-decoration: none; transition: all 0.2s;
}
.btn-filter.search { background: var(--em-500); color: var(--white); }
.btn-filter.search:hover { background: var(--em-600); }
.btn-filter.reset  { background: var(--em-25); color: var(--em-700); border: 1px solid var(--em-100); }
.btn-filter.reset:hover { background: var(--em-50); }

/* ── TABLE ── */
.table-card {
    background: var(--white);
    border: 1px solid var(--em-50);
    border-radius: 14px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(6,78,59,0.05);
}

.table-card-header {
    padding: 16px 22px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid var(--em-25);
}

.table-card-header .ttl {
    font-size: 14px;
    font-weight: 700;
    color: var(--em-800);
}

.table-card-header .count-badge {
    background: var(--em-50);
    color: var(--em-700);
    font-size: 12px;
    font-weight: 700;
    padding: 3px 10px;
    border-radius: 20px;
}

.table-wrap { overflow-x: auto; }

table { width: 100%; border-collapse: collapse; font-size: 13px; }

thead tr { background: var(--em-800); }

th {
    padding: 13px 14px;
    text-align: left;
    color: var(--white);
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.7px;
    white-space: nowrap;
}

td {
    padding: 12px 14px;
    border-bottom: 1px solid var(--em-25);
    vertical-align: top;
    color: var(--gray-700);
}

tbody tr:last-child td { border-bottom: none; }

tbody tr:hover { background: var(--em-25); }

tbody tr:nth-child(even) { background: #f9fefb; }
tbody tr:nth-child(even):hover { background: var(--em-25); }

/* Column widths */
.col-no    { width: 44px; text-align: center; font-weight: 700; color: var(--gray-500); }
.col-pedido { white-space: nowrap; font-weight: 700; color: var(--em-700); }
.col-date  { white-space: nowrap; }
.col-dir   { white-space: nowrap; max-width: 140px; }
.col-assuntu { min-width: 240px; line-height: 1.6; font-size: 12px; }
.col-amount { white-space: nowrap; font-weight: 800; color: var(--em-500); font-size: 14px; }
.col-cpv   { white-space: nowrap; font-family: monospace; font-size: 12px; color: var(--gray-700); }
.col-vendor { min-width: 160px; font-size: 12px; }

/* Empty state */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: var(--gray-500);
}
.empty-state i { font-size: 40px; color: var(--em-100); margin-bottom: 12px; display: block; }
.empty-state p { font-size: 14px; }

/* ── FOOTER ── */
.page-footer {
    text-align: center;
    font-size: 11px;
    color: var(--gray-500);
    padding: 20px 32px;
    border-top: 1px solid var(--em-50);
    margin-top: 8px;
}
</style>
</head>
<body>

<div class="page">

<!-- TOP BAR -->
<div class="topbar">
    <div class="topbar-left">
        <div class="topbar-logo"><i class="fas fa-leaf"></i></div>
        <div>
            <div class="topbar-title">Finance System</div>
            <div class="topbar-subtitle">Arsipu Konfirmasaun</div>
        </div>
    </div>
    <div class="topbar-right">
        <a href="../dashboard.php" class="btn-dashboard">
            <i class="fas fa-chart-pie"></i> Dashboard
        </a>
    </div>
</div>

<!-- MAIN -->
<div class="main">

    <!-- Page Heading -->
    <div class="page-heading">
        <div>
            <h1><i class="fas fa-folder-open" style="color:var(--em-400);margin-right:10px;font-size:22px"></i>Arkivu Konfirmasaun</h1>
            <div class="breadcrumb">Finance &rsaquo; Dokumentu &rsaquo; Arkivu Konfirmasaun</div>
        </div>
        <span class="badge-live">Rekord aktiva</span>
    </div>

    <!-- Summary Cards -->
    <div class="summary-grid">
        <div class="sum-card">
            <div class="sum-icon green"><i class="fas fa-file-invoice"></i></div>
            <div>
                <div class="sum-label">Total Dokumentu</div>
                <div class="sum-value"><?= $total_rows ?></div>
            </div>
        </div>
        <div class="sum-card">
            <div class="sum-icon teal"><i class="fas fa-dollar-sign"></i></div>
            <div>
                <div class="sum-label">Total Montante</div>
                <div class="sum-value usd"><?= formatUSD($total_amount) ?></div>
            </div>
        </div>
        <div class="sum-card">
            <div class="sum-icon amber"><i class="fas fa-clock"></i></div>
            <div>
                <div class="sum-label">Status</div>
                <div class="sum-value" style="font-size:15px;color:var(--em-700)">Em Revisaun</div>
            </div>
        </div>
    </div>

    <!-- Filter Panel -->
    <div class="filter-panel">
        <form method="GET" id="filterForm">

            <!-- Search -->
            <div class="filter-group search-group">
                <label><i class="fas fa-search" style="margin-right:4px"></i>Buka Dokumentu</label>
                <input type="text" name="search"
                       placeholder="No pedido, diresaun, vendor..."
                       value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
            </div>

            <!-- Date From -->
            <div class="filter-group">
                <label><i class="fas fa-calendar-day" style="margin-right:4px"></i>Data Hosi</label>
                <div class="date-field-wrap">
                    <div class="date-display" id="disp_date1">
                        <span class="ph" id="lbl_date1"><?= !empty($date1) ? formatTanggalPortugal($date1) : 'dd/MM/yyyy' ?></span>
                        <i class="fas fa-calendar-alt cal-ic"></i>
                    </div>
                    <input type="hidden" name="date1" id="iso_date1" value="<?= htmlspecialchars($date1) ?>">
                    <div class="dp-dropdown" id="dp1"></div>
                </div>
            </div>

            <!-- Date To -->
            <div class="filter-group">
                <label><i class="fas fa-calendar-check" style="margin-right:4px"></i>To'o</label>
                <div class="date-field-wrap">
                    <div class="date-display" id="disp_date2">
                        <span class="ph" id="lbl_date2"><?= !empty($date2) ? formatTanggalPortugal($date2) : 'dd/MM/yyyy' ?></span>
                        <i class="fas fa-calendar-alt cal-ic"></i>
                    </div>
                    <input type="hidden" name="date2" id="iso_date2" value="<?= htmlspecialchars($date2) ?>">
                    <div class="dp-dropdown" id="dp2"></div>
                </div>
            </div>

            <!-- Buttons -->
            <div class="filter-group" style="justify-content:flex-end">
                <label style="visibility:hidden">_</label>
                <div style="display:flex;gap:8px">
                    <button type="submit" class="btn-filter search">
                        <i class="fas fa-search"></i> Buka
                    </button>
                    <a href="arsipkonfirmasi.php" class="btn-filter reset">
                        <i class="fas fa-rotate-left"></i> Reset
                    </a>
                </div>
            </div>

        </form>
    </div>

    <!-- Table Card -->
    <div class="table-card">
        <div class="table-card-header">
            <span class="ttl"><i class="fas fa-table" style="margin-right:8px;color:var(--em-400)"></i>Lista Dokumentu Konfirmadu</span>
            <span class="count-badge"><?= $total_rows ?> rekord</span>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th class="col-no">No</th>
                        <th>No Pedido</th>
                        <th>Data Simu</th>
                        <th>Diresaun</th>
                        <th>Assuntu</th>
                        <th>Montante</th>
                        <th>No CPV/PR</th>
                        <th>Data Kria CPV</th>
                        <th>No OBL/PO</th>
                        <th>Data Kria OBL</th>
                        <th>Vendor</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($rows_data)): ?>
                    <tr>
                        <td colspan="11">
                            <div class="empty-state">
                                <i class="fas fa-folder-open"></i>
                                <p>Dadus seidauk iha. Halo filtru seluk ka verifika status dokumentu.</p>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php $no = 1; foreach ($rows_data as $row): ?>
                    <tr>
                        <td class="col-no"><?= $no++ ?></td>
                        <td class="col-pedido"><?= htmlspecialchars($row['nomor_prt']) ?></td>
                        <td class="col-date"><?= formatTanggalPortugal($row['tgl_terima']) ?></td>
                        <td class="col-dir"><?= htmlspecialchars($row['direksi']) ?></td>
                        <td class="col-assuntu"><?= nl2br(htmlspecialchars($row['descripsi'])) ?></td>
                        <td class="col-amount"><?= formatUSD($row['total_adiantamento']) ?></td>
                        <td class="col-cpv"><?= htmlspecialchars($row['nomor_cpv']) ?></td>
                        <td class="col-date"><?= formatTanggalPortugal($row['tgl_cpv']) ?></td>
                        <td class="col-cpv"><?= htmlspecialchars($row['nomor_obl']) ?></td>
                        <td class="col-date"><?= formatTanggalPortugal($row['tanggal_obl']) ?></td>
                        <td class="col-vendor"><?= htmlspecialchars($row['vendor_name']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

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

<div class="page-footer">
    Finance System &copy; <?= date('Y') ?> &mdash; Arsipu Konfirmasaun
</div>

</div><!-- /page -->

<script>
const MESES_PT = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho',
                  'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
const DIAS_PT  = ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'];

function pad(n) { return String(n).padStart(2,'0'); }

function isoToDisplay(iso) {
    if (!iso) return null;
    const [y, m, d] = iso.split('-');
    return `${d}/${MESES_PT[parseInt(m)-1]}/${y}`;
}

const pickerState = {};

function buildPicker(dropId, isoInputId, labelId) {
    const drop     = document.getElementById(dropId);
    const isoInput = document.getElementById(isoInputId);
    const label    = document.getElementById(labelId);

    // Init current month from existing value
    let initIso = isoInput.value;
    let cur = initIso ? new Date(initIso + 'T00:00:00') : new Date();
    let selected = initIso ? new Date(initIso + 'T00:00:00') : null;

    function render() {
        const y = cur.getFullYear(), m = cur.getMonth();
        const firstDay  = new Date(y, m, 1).getDay();
        const totalDays = new Date(y, m+1, 0).getDate();
        const today = new Date();

        let html = `<div class="dp-hd">
            <button type="button" class="dp-nav-btn" onclick="pickerState['${dropId}'].prev()">&#8249;</button>
            <span class="dp-month-title">${MESES_PT[m]} ${y}</span>
            <button type="button" class="dp-nav-btn" onclick="pickerState['${dropId}'].next()">&#8250;</button>
        </div><div class="dp-grid">`;

        DIAS_PT.forEach(d => html += `<div class="dp-dn">${d}</div>`);

        for (let i = 0; i < firstDay; i++)
            html += `<div class="dp-d emp"></div>`;

        for (let d = 1; d <= totalDays; d++) {
            const isToday = today.getDate()===d && today.getMonth()===m && today.getFullYear()===y;
            const isSel   = selected && selected.getDate()===d && selected.getMonth()===m && selected.getFullYear()===y;
            let cls = 'dp-d';
            if (isSel)        cls += ' sel';
            else if (isToday) cls += ' tod';
            html += `<div class="${cls}" onclick="pickerState['${dropId}'].pick(${y},${m},${d})">${d}</div>`;
        }
        html += '</div>';
        drop.innerHTML = html;
    }

    function pick(y, m, d) {
        selected = new Date(y, m, d);
        const iso = `${y}-${pad(m+1)}-${pad(d)}`;
        isoInput.value = iso;
        label.textContent = `${pad(d)}/${MESES_PT[m]}/${y}`;
        label.style.color = '';
        close();
    }

    function prev()   { cur = new Date(cur.getFullYear(), cur.getMonth()-1, 1); render(); }
    function next()   { cur = new Date(cur.getFullYear(), cur.getMonth()+1, 1); render(); }
    function open()   { drop.classList.add('open'); render(); }
    function close()  { drop.classList.remove('open'); }
    function toggle() { drop.classList.contains('open') ? close() : open(); }

    // Cegah klik dalam dropdown menutup picker
    drop.addEventListener('click', e => e.stopPropagation());

    return { prev, next, pick, open, close, toggle, dropEl: drop };
}

pickerState['dp1'] = buildPicker('dp1', 'iso_date1', 'lbl_date1');
pickerState['dp2'] = buildPicker('dp2', 'iso_date2', 'lbl_date2');

// Pasang trigger via JS (bukan onclick HTML) agar stopPropagation bisa bekerja
document.getElementById('disp_date1').addEventListener('click', function(e) {
    e.stopPropagation();
    pickerState['dp2'].close();
    pickerState['dp1'].toggle();
});

document.getElementById('disp_date2').addEventListener('click', function(e) {
    e.stopPropagation();
    pickerState['dp1'].close();
    pickerState['dp2'].toggle();
});

// Klik di luar → tutup semua
document.addEventListener('click', () => {
    Object.values(pickerState).forEach(p => p.close());
});
</script>

</body>
</html>
