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

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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

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, '.', ',');
}

// PERBAIKAN: Fungsi convertTanggal sekarang mendukung format dd/NamaBulan/yyyy
function convertTanggal($tgl) {
    if (empty(trim($tgl))) return null;
    
    $bulan_pt = [
        'Janeiro'=>'01', 'Fevereiro'=>'02', 'Março'=>'03', 'Abril'=>'04', 
        'Maio'=>'05', 'Junho'=>'06', 'Julho'=>'07', 'Agosto'=>'08', 
        'Setembro'=>'09', 'Outubro'=>'10', 'Novembro'=>'11', 'Dezembro'=>'12'
    ];

    $exp = explode('/', trim($tgl));
    if (count($exp) === 3) {
        $hari = str_pad($exp[0], 2, '0', STR_PAD_LEFT);
        // Cek jika bagian bulan berupa teks atau angka
        $bulan = isset($bulan_pt[$exp[1]]) ? $bulan_pt[$exp[1]] : str_pad($exp[1], 2, '0', STR_PAD_LEFT);
        $tahun = $exp[2];
        
        return $tahun . '-' . $bulan . '-' . $hari;
    }
    return null;
}

if (isset($_POST['submit_arsip'])) {
    $id_post          = (int)$_POST['id_jv'];
    $nomor_apt        = trim($_POST['nomor_apt'] ?? '');
    $tanggal_its      = convertTanggal($_POST['tanggal_its'] ?? '');
    $nomor_prt2       = trim($_POST['nomor_prt2'] ?? '');
    $tanggal_prt2     = convertTanggal($_POST['tanggal_prt2'] ?? '');
    $deskripsi2       = trim($_POST['deskripsi2'] ?? '');
    $tipo_pagamento   = trim($_POST['tipo_pagamento'] ?? '');
    $total_relatorio2 = trim($_POST['total_relatorio2'] ?? '');
    
    // Data tambahan input arsip dari form bawaan
    $tgl_arsip        = convertTanggal($_POST['tgl_arsip'] ?? '');
    $nomor_arsip      = trim($_POST['nomor_arsip'] ?? '');
    $no_bantex        = trim($_POST['no_bantex'] ?? '');
    $nomor_box        = trim($_POST['nomor_box'] ?? '');
    $cabinet          = trim($_POST['cabinet'] ?? '');

    // PERBAIKAN: Menambahkan kolom-kolom arsip ke query UPDATE agar data tersimpan
   $stmt = $koneksi->prepare("
    UPDATE jv_documents
    SET
        tgl_arsip=?,
        nomor_arsip=?,
        no_bantex=?,
        nomor_box=?,
        cabinet=?,
        status='arsip'
    WHERE id_jv=?
");
    
    $stmt->bind_param(
    "sssssi",
    $tgl_arsip,
    $nomor_arsip,
    $no_bantex,
    $nomor_box,
    $cabinet,
    $id_post
);
    $stmt->execute();
    $stmt->close();
    header("Location: dataarsipkonfirmasi.php?success=1");
    exit;
}

$query = $koneksi->query("SELECT * FROM jv_documents WHERE id_jv = $id");
if (!$query) die("Query error: " . $koneksi->error);
$data = $query->fetch_assoc();
if (!$data) die("Dadus la hetan.");
?>
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="UTF-8">
<title>Konfirma & Rejistu — Finance System</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

body {
    font-family: 'Segoe UI', sans-serif;
    background: #044919;
    color: #1f2937;
    padding: 28px 20px;
    min-height: 100vh;
}

.page {
    width: 90%;
    max-width: 1200px;
    margin: 0 auto;
    background: #ffffff;
    border-radius: 18px;
    border: 1px solid #bbebd2;
    box-shadow: 0 8px 32px rgba(6,78,59,.07);
    overflow: hidden;
}

.pg-header {
    background: #187e14;
    padding: 18px 30px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.pg-header .icon-wrap {
    width: 38px; height: 38px;
    background: rgba(167,243,208,.15);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
}
.pg-header .icon-wrap i { font-size: 18px; color: #e4f0e4; }
.pg-header h1 { font-size: 17px; font-weight: 600; color: #fff; }
.pg-header .badge {
    margin-left: auto;
    background: rgba(232, 245, 239, 0.15);
    color: #03ff18;
    font-size: 16px;
    font-weight: 600;
    padding: 4px 12px;
    border-radius: 20px;
    letter-spacing: .04em;
}

.content { padding: 30px; }

.sec-label {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 10px;
    font-weight: 700;
    color: #059669;
    text-transform: uppercase;
    letter-spacing: .1em;
    margin-bottom: 16px;
}
.sec-label::after {
    content: '';
    flex: 1;
    height: 1px;
    background: #d1fae5;
}
.sec-label i { font-size: 13px; }

.info-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-bottom: 28px;
}
.info-card {
    background: #f0fdf4;
    border: 1px solid #d1fae5;
    border-radius: 10px;
    padding: 13px 16px;
}
.info-card.span3 { grid-column: span 3; }
.info-card .lbl {
    font-size: 10px;
    font-weight: 700;
    color: #059669;
    text-transform: uppercase;
    letter-spacing: .08em;
    margin-bottom: 5px;
}
.info-card .val {
    font-size: 14px;
    font-weight: 600;
    color: #1f2937;
    line-height: 1.4;
}
.info-card .val.amount {
    font-size: 20px;
    color: #047857;
    font-variant-numeric: tabular-nums;
}
.info-card .val.desc {
    font-size: 13px;
    font-weight: 400;
    color: #374151;
    line-height: 1.65;
}

.divider {
    border: none;
    border-top: 2px solid #f0fdf4;
    margin: 0 0 28px;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 18px;
}
.form-group { display: flex; flex-direction: column; gap: 6px; }
.form-group.span2 { grid-column: span 2; }

.form-group label {
    font-size: 10px;
    font-weight: 700;
    color: #059669;
    text-transform: uppercase;
    letter-spacing: .08em;
}
.form-group input {
    height: 42px;
    padding: 0 13px;
    border: 1px solid #c8d6cd;
    border-radius: 10px;
    font-size: 14px;
    font-family: 'Segoe UI', sans-serif;
    color: #1f2937;
    background: #ffffff;
    outline: none;
    width: 100%;
    transition: border-color .15s, box-shadow .15s;
}
.form-group input:focus {
    border-color: #34d399;
    box-shadow: 0 0 0 3px rgba(52,211,153,.12);
}

.date-wrap { position: relative; }
.date-wrap .cal-ico {
    position: absolute;
    right: 12px; top: 13px;
    font-size: 16px;
    color: #059669;
    pointer-events: none;
}
.dpicker {
    position: absolute;
    top: calc(100% + 5px);
    left: 0;
    z-index: 300;
    background: #fff;
    border: 1px solid #d1fae5;
    border-radius: 14px;
    padding: 14px;
    box-shadow: 0 10px 28px rgba(0,0,0,.09);
    display: none;
    min-width: 248px;
}
.dp-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}
.dp-head .dp-title { font-size: 13px; font-weight: 600; color: #064e3b; }
.dp-nav {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 20px;
    color: #059669;
    padding: 2px 7px;
    border-radius: 7px;
    line-height: 1;
}
.dp-nav:hover { background: #f0fdf4; }
.dp-days {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 2px;
    text-align: center;
}
.dp-dname { font-size: 10px; color: #10b981; font-weight: 700; padding: 3px 0; }
.dp-d {
    font-size: 12px;
    padding: 6px 3px;
    border-radius: 6px;
    cursor: pointer;
    color: #374151;
}
.dp-d:hover { background: #f0fdf4; color: #047857; }
.dp-d.today { border: 1px solid #34d399; color: #047857; font-weight: 600; }

.pg-footer {
    background: #f8fafc;
    border-top: 1px solid #e2e8f0;
    padding: 22px 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.btn {
    min-width: 168px;
    height: 46px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 9px;
    border-radius: 11px;
    font-weight: 700;
    font-size: 14px;
    cursor: pointer;
    text-decoration: none;
    border: none;
    transition: opacity .15s, transform .1s;
    font-family: 'Segoe UI', sans-serif;
}
.btn:hover { opacity: .88; transform: translateY(-2px); }
.btn-cancel { background: #ef4444; color: #fff; }
.btn-submit { background: #047857; color: #fff; }

@media (max-width: 820px) {
    .info-grid { grid-template-columns: repeat(2, 1fr); }
    .info-card.span3 { grid-column: span 2; }
    .form-grid { grid-template-columns: 1fr; }
    .form-group.span2 { grid-column: span 1; }
}
</style>
</head>
<body>

<div class="page">
    <!-- HEADER -->
    <div class="pg-header">
        <div class="icon-wrap"><i class="fas fa-file-signature"></i></div>
        <h1>Konfirma &amp; Rejistu Dokumentu</h1>
        <span class="badge">Sistema Verifikasaun Pagamento</span>
    </div>

    <form action="" method="POST">
        <div class="content">
            <input type="hidden" name="id_jv" value="<?= $id ?>">

            <!-- READ ONLY INFO -->
            <div class="sec-label">
                <i class="fas fa-info-circle"></i> Informasaun Dokumentu
            </div>

            <div class="info-grid">
                <div class="info-card">
                    <div class="lbl">No Pedido</div>
                    <div class="val"><?= htmlspecialchars($data['nomor_prt'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Data Simu Pedido</div>
                    <div class="val"><?= formatTanggalPortugal($data['tgl_terima'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Diresaun</div>
                    <div class="val"><?= htmlspecialchars($data['direksi'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">No CPV/PR</div>
                    <div class="val"><?= htmlspecialchars($data['nomor_cpv'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Data Kria CPV/PR</div>
                    <div class="val"><?= formatTanggalPortugal($data['tgl_cpv'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Vendor</div>
                    <div class="val"><?= htmlspecialchars($data['vendor_name'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">No OBL/PO</div>
                    <div class="val"><?= htmlspecialchars($data['nomor_obl'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Data Kria OBL/PO</div>
                    <div class="val"><?= formatTanggalPortugal($data['tanggal_obl'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Montante</div>
                    <div class="val amount"><?= formatUSD($data['total_adiantamento'] ?? 0) ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">No ITS/APT</div>
                    <div class="val"><?= htmlspecialchars($data['nomor_apt'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Data Kria ITS/APT</div>
                    <div class="val"><?= formatTanggalPortugal($data['tanggal_its'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Tipo Pagamento</div>
                    <div class="val"><?= htmlspecialchars($data['tipo_pagamento'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">No PRT</div>
                    <div class="val"><?= htmlspecialchars($data['nomor_prt2'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Data Kria PRT</div>
                    <div class="val"><?= formatTanggalPortugal($data['tanggal_prt2'] ?? '') ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Montante Relatóriu</div>
                    <div class="val amount"><?= formatUSD($data['total_relatorio2'] ?? 0) ?></div>
                </div>
                <div class="info-card span3">
                    <div class="lbl">Assuntu</div>
                    <div class="val desc"><?= nl2br(htmlspecialchars($data['deskripsi2'] ?? '')) ?></div>
                </div>
            </div>

            <div class="divider"></div>

            <!-- INPUT FORM -->
            <div class="sec-label">
                <i class="fas fa-archive"></i> Input Arkivu Dokumentu
            </div>

            <div class="form-grid">
                <div class="form-group">
                    <label>Data Arkivu</label>
                    <div class="date-wrap">
                        <input type="text" id="inp_arsip" name="tgl_arsip" placeholder="dd/MMM/yyyy" readonly required autocomplete="off">
                        <i class="fas fa-calendar-alt cal-ico"></i>
                        <div id="picker_arsip" class="dpicker"></div>
                    </div>
                </div>

                <div class="form-group">
                    <label>No Arkivu</label>
                    <input type="text" name="nomor_arsip" placeholder="Preeche No Arkivu..." autocomplete="off" required>
                </div>

                <div class="form-group">
                    <label>No Bantex</label>
                    <input type="text" name="no_bantex" placeholder="Preeche No Bantex..." autocomplete="off">
                </div>

                <div class="form-group">
                    <label>No Box</label>
                    <input type="text" name="nomor_box" placeholder="Preeche No Box..." autocomplete="off">
                </div>

                <div class="form-group span2">
                    <label>No Cabinet</label>
                    <input type="text" name="cabinet" placeholder="Preeche Cabinet / Lokalizasaun Arkivu..." autocomplete="off">
                </div>
            </div>
        </div>
<!-- HIDDEN DATA KONFIRMASAUN -->
<input type="hidden" name="nomor_apt" value="<?= htmlspecialchars($data['nomor_apt'] ?? '') ?>">

<input type="hidden" name="tanggal_its"
       value="<?= !empty($data['tanggal_its'])
            ? formatTanggalPortugal($data['tanggal_its'])
            : '' ?>">

<input type="hidden" name="nomor_prt2" value="<?= htmlspecialchars($data['nomor_prt2'] ?? '') ?>">

<input type="hidden" name="tanggal_prt2"
       value="<?= !empty($data['tanggal_prt2'])
            ? formatTanggalPortugal($data['tanggal_prt2'])
            : '' ?>">

<input type="hidden" name="tipo_pagamento"
       value="<?= htmlspecialchars($data['tipo_pagamento'] ?? '') ?>">

<input type="hidden" name="deskripsi2"
       value="<?= htmlspecialchars($data['deskripsi2'] ?? '') ?>">

<input type="hidden" name="total_relatorio2"
       value="<?= htmlspecialchars($data['total_relatorio2'] ?? '') ?>">

        <!-- FOOTER BUTTONS -->
        <div class="pg-footer">
            <a href="arsipkonfirmasidok.php?id=<?= $id ?>" class="btn btn-cancel"><i class="fas fa-times"></i> Kansela</a>
            <button type="submit" name="submit_arsip" class="btn btn-submit"><i class="fas fa-save"></i> Submete &amp; Arkiva</button>
        </div>
    </form>
</div>

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

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

function makePicker(pickerId, inputId) {
    const pk  = document.getElementById(pickerId);
    const inp = document.getElementById(inputId);

    if (!pk || !inp) return;

    let cur = new Date();

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

        let h = `
        <div class="dp-head">
            <button type="button" class="dp-nav" data-a="prev">&#8249;</button>
            <span class="dp-title">${MESES[m]} ${y}</span>
            <button type="button" class="dp-nav" data-a="next">&#8250;</button>
        </div>
        <div class="dp-days">`;

        DIAS.forEach(d => {
            h += `<div class="dp-dname">${d}</div>`;
        });

        for (let i = 0; i < fd; i++) {
            h += `<div></div>`;
        }

        for (let d = 1; d <= td; d++) {
            const isToday = today.getDate() === d && today.getMonth() === m && today.getFullYear() === y;
            h += `<div class="dp-d ${isToday ? 'today' : ''}" data-d="${d}">${d}</div>`;
        }

        h += `</div>`;
        pk.innerHTML = h;

        pk.querySelectorAll('.dp-nav').forEach(btn => {
            btn.addEventListener('click', function(e){
                e.stopPropagation();
                if (this.dataset.a === 'prev') {
                    cur = new Date(y, m - 1, 1);
                } else {
                    cur = new Date(y, m + 1, 1);
                }
                render();
            });
        });

        pk.querySelectorAll('.dp-d').forEach(el => {
            el.addEventListener('click', function(e){
                e.stopPropagation();
                const day   = pad(parseInt(this.dataset.d));
                const month = MESES[m];
                const year  = y;

                inp.value = `${day}/${month}/${year}`;
                pk.style.display = 'none';
            });
        });
    }

    inp.addEventListener('click', function(e){
        e.stopPropagation();
        render();
        pk.style.display = 'block';
    });

    pk.addEventListener('click', function(e){
        e.stopPropagation();
    });

    document.addEventListener('click', function(){
        pk.style.display = 'none';
    });
}

// PERBAIKAN: Memasukkan pemanggilan fungsi di dalam tag <script> dengan benar
document.addEventListener("DOMContentLoaded", function() {
    makePicker('picker_arsip', 'inp_arsip');
});
</script>
</body>
</html>