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

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

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

/* ── FUNGSI ── */
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, '.', ',');
}

function convertTanggal($tgl)
{
    if (empty(trim($tgl))) return null;

    $bulan = [
        '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  = $exp[0];
        $mesPT = $exp[1];
        $tahun = $exp[2];
        $mes   = $bulan[$mesPT] ?? '01';
        return $tahun . '-' . $mes . '-' . $hari;
    }

    return null;
}

/* ── PROSES POST ── */
if (isset($_POST['submit_arsip'])) {

    $id_post      = (int)$_POST['id_jv'];
    $nomor_cpv    = trim($_POST['nomor_cpv']    ?? '');
    $tgl_cpv      = convertTanggal($_POST['tgl_cpv']      ?? '');
    $nomor_obl    = trim($_POST['nomor_obl']    ?? '');
    $tanggal_obl  = convertTanggal($_POST['tanggal_obl']  ?? '');
    $vendor_name  = trim($_POST['vendor_name']  ?? '');

    /* ── Ambil data existing untuk fallback path lampiran ── */
    $existing = $koneksi->query("SELECT lampiran2, lampiran3 FROM jv_documents WHERE id_jv = $id_post");
    $existingData = $existing ? $existing->fetch_assoc() : [];

    $lampiran2_path = $existingData['lampiran2'] ?? null;
    $lampiran3_path = $existingData['lampiran3'] ?? null;

    /* ── Handle Upload Lampiran CPV ── */
    if (!empty($_FILES['lampiran2']['name']) && $_FILES['lampiran2']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['lampiran2']['name'], PATHINFO_EXTENSION));
        if ($ext === 'pdf' && $_FILES['lampiran2']['type'] === 'application/pdf') {
            $upload_dir = '../uploads/lampiran/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            $filename = 'cpv_' . $id_post . '_' . time() . '.pdf';
            if (move_uploaded_file($_FILES['lampiran2']['tmp_name'], $upload_dir . $filename)) {
                $lampiran2_path = $filename;
            }
        }
    }

    /* ── Handle Upload Lampiran OBL ── */
    if (!empty($_FILES['lampiran3']['name']) && $_FILES['lampiran3']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['lampiran3']['name'], PATHINFO_EXTENSION));
        if ($ext === 'pdf' && $_FILES['lampiran3']['type'] === 'application/pdf') {
            $upload_dir = '../uploads/lampiran/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            $filename = 'obl_' . $id_post . '_' . time() . '.pdf';
            if (move_uploaded_file($_FILES['lampiran3']['tmp_name'], $upload_dir . $filename)) {
                $lampiran3_path = $filename;
            }
        }
    }

    $stmt = $koneksi->prepare("
        UPDATE jv_documents
        SET
            nomor_cpv   = ?,
            tgl_cpv     = ?,
            nomor_obl   = ?,
            tanggal_obl = ?,
            vendor_name = ?,
            lampiran2   = ?,
            lampiran3   = ?,
            status      = 'review'
        WHERE id_jv = ?
    ");

    if (!$stmt) die("Prepare gagal: " . $koneksi->error);

    $stmt->bind_param("sssssssi",
        $nomor_cpv, $tgl_cpv,
        $nomor_obl, $tanggal_obl,
        $vendor_name,
        $lampiran2_path, $lampiran3_path,
        $id_post
    );

    if (!$stmt->execute()) die("Execute gagal: " . $stmt->error);

    $stmt->close();
    header("Location: arsipkonfirmasi.php?success=1");
    exit;
}

/* ── AMBIL DATA ── */
$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">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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', Tahoma, Geneva, Verdana, sans-serif;
            background: #ecfdf5;
            color: #1f2937;
            min-height: 100vh;
            padding: 32px 5%;
        }

        /* ── PAGE WRAPPER ── */
        .page-wrapper {
            width: 90%;
            max-width: 1400px;
            margin: 0 auto;
        }

        /* ── CARD CONTAINER ── */
        .card-main {
            background: #ffffff;
            border-radius: 18px;
            border: 1px solid #d1fae5;
            box-shadow: 0 4px 24px rgba(6, 78, 59, 0.07);
            overflow: hidden;
        }

        /* ── HEADER ── */
        .card-header {
            background: #064e3b;
            padding: 20px 32px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .card-header-left {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .card-header-left i {
            color: #6ee7b7;
            font-size: 22px;
        }
        .card-header-left h2 {
            font-size: 17px;
            font-weight: 600;
            color: #ffffff;
            margin: 0;
        }
        .card-header-left p {
            font-size: 11px;
            color: #a7f3d0;
            margin: 2px 0 0;
        }
        .header-badge {
            background: rgba(255,255,255,0.12);
            color: #6ee7b7;
            font-size: 11px;
            font-weight: 600;
            padding: 5px 14px;
            border-radius: 20px;
            border: 1px solid rgba(110,231,183,0.3);
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .header-badge i { font-size: 11px; }

        /* ── BODY: TWO COLUMNS ── */
        .card-body {
            display: grid;
            grid-template-columns: 1fr 1fr;
            min-height: 540px;
        }

        /* ── COLUMN LEFT ── */
        .col-left {
            padding: 28px 32px;
            background: #fafffe;
            border-right: 1px solid #d1fae5;
        }

        .sec-title {
            font-size: 10px;
            font-weight: 700;
            color: #059669;
            text-transform: uppercase;
            letter-spacing: 1.2px;
            margin-bottom: 14px;
            display: flex;
            align-items: center;
            gap: 7px;
        }
        .sec-title i { font-size: 13px; }

        .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px; }
        .mb-10 { margin-bottom: 10px; }
        .mb-16 { margin-bottom: 16px; }

        .data-card {
            background: #ffffff;
            border: 1px solid #d1fae5;
            border-radius: 10px;
            padding: 13px 16px;
        }
        .data-card .lbl {
            font-size: 10px;
            font-weight: 700;
            color: #059669;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 5px;
        }
        .data-card .val {
            font-size: 14px;
            font-weight: 600;
            color: #1f2937;
            line-height: 1.5;
        }
        .data-card .val.amount {
            font-size: 24px;
            color: #047857;
            font-weight: 700;
        }
        .data-card .val.desc-text {
            font-size: 13px;
            font-weight: 400;
            color: #374151;
            line-height: 1.7;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            background: #ecfdf5;
            color: #065f46;
            font-size: 11px;
            font-weight: 600;
            padding: 4px 10px;
            border-radius: 20px;
            border: 1px solid #a7f3d0;
            margin-top: 8px;
        }
        .status-badge i { font-size: 9px; color: #10b981; }

        .divider { border: none; border-top: 1px solid #ecfdf5; margin: 18px 0; }

        /* ── COLUMN RIGHT ── */
        .col-right {
            padding: 28px 32px;
            display: flex;
            flex-direction: column;
        }

        .info-chip {
            display: flex;
            align-items: center;
            gap: 8px;
            background: #ecfdf5;
            border: 1px solid #a7f3d0;
            border-radius: 8px;
            padding: 9px 13px;
            margin-bottom: 20px;
        }
        .info-chip i { color: #059669; font-size: 14px; flex-shrink: 0; }
        .info-chip span { font-size: 12px; color: #065f46; font-weight: 500; }

        .form-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 6px;
            margin-bottom: 14px;
        }
        .form-group label {
            font-size: 10px;
            font-weight: 700;
            color: #047857;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .form-group input[type="text"] {
            height: 40px;
            padding: 0 12px;
            border: 1px solid #d1fae5;
            border-radius: 9px;
            background: #ffffff;
            font-size: 13px;
            color: #1f2937;
            outline: none;
            transition: border-color .2s, box-shadow .2s;
            width: 100%;
        }
        .form-group input[type="text"]:focus {
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.12);
        }
        .form-group input[type="text"]:hover:not(:focus) {
            border-color: #6ee7b7;
        }
        .form-group input::placeholder { color: #a7f3d0; }

        /* required star */
        .form-group label .req,
        .file-group label .req { color: #ef4444; margin-left: 3px; }

        /* ── DATE PICKER ── */
        .date-wrap { position: relative; }
        .date-wrap input { padding-right: 36px; cursor: pointer; }
        .date-wrap .cal-icon {
            position: absolute;
            right: 11px;
            top: 50%;
            transform: translateY(-50%);
            color: #6ee7b7;
            font-size: 14px;
            pointer-events: none;
        }

        .date-picker {
            position: absolute;
            top: calc(100% + 6px);
            left: 0;
            background: #ffffff;
            border: 1px solid #d1fae5;
            border-radius: 12px;
            padding: 15px;
            z-index: 999;
            min-width: 256px;
            box-shadow: 0 8px 28px rgba(0,0,0,0.1);
            display: none;
        }
        .dp-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .dp-nav {
            background: #ecfdf5;
            border: none;
            cursor: pointer;
            padding: 4px 10px;
            border-radius: 7px;
            color: #059669;
            font-size: 16px;
            transition: background .15s;
        }
        .dp-nav:hover { background: #a7f3d0; }
        .dp-title { font-size: 13px; font-weight: 700; color: #064e3b; }

        .dp-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 2px;
            text-align: center;
        }
        .dp-day-name { font-size: 10px; color: #6ee7b7; padding: 3px 0; font-weight: 700; }
        .dp-day { font-size: 12px; padding: 5px 2px; border-radius: 6px; cursor: pointer; color: #1f2937; }
        .dp-day:hover { background: #ecfdf5; }
        .dp-day.selected { background: #059669; color: #ffffff; font-weight: 700; }
        .dp-day.today { border: 1px solid #10b981; color: #059669; }
        .dp-day.empty { cursor: default; pointer-events: none; }

        /* ── FILE INPUT ── */
        .file-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
            margin-bottom: 14px;
        }
        .file-group label {
            font-size: 10px;
            font-weight: 700;
            color: #047857;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .file-input-wrap {
            position: relative;
            display: flex;
            align-items: center;
            height: 40px;
            border: 1px solid #d1fae5;
            border-radius: 9px;
            background: #ffffff;
            overflow: hidden;
            transition: border-color .2s, box-shadow .2s;
        }
        .file-input-wrap:focus-within {
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.12);
        }
        .file-input-wrap:hover {
            border-color: #6ee7b7;
        }
        .file-input-wrap input[type="file"] {
            position: absolute;
            inset: 0;
            opacity: 0;
            cursor: pointer;
            width: 100%;
            height: 100%;
            z-index: 2;
        }
        .file-input-label {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 0 12px;
            flex: 1;
            height: 100%;
            font-size: 12px;
            color: #9ca3af;
            pointer-events: none;
            white-space: nowrap;
            overflow: hidden;
            min-width: 0;
        }
        .file-input-label i {
            color: #6ee7b7;
            font-size: 14px;
            flex-shrink: 0;
        }
        .file-input-label .file-name {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .file-input-label .file-size {
            margin-left: auto;
            flex-shrink: 0;
            font-size: 10px;
            color: #a7f3d0;
            padding-left: 8px;
        }
        .file-input-btn {
            flex-shrink: 0;
            height: 100%;
            padding: 0 14px;
            background: #ecfdf5;
            border-left: 1px solid #d1fae5;
            font-size: 11px;
            font-weight: 700;
            color: #047857;
            pointer-events: none;
            display: flex;
            align-items: center;
            gap: 5px;
            white-space: nowrap;
        }
        .file-hint {
            font-size: 10px;
            color: #a7f3d0;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .file-error {
            font-size: 10px;
            color: #ef4444;
            display: none;
            align-items: center;
            gap: 4px;
        }

        /* existing file indicator */
        .file-existing {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-size: 10px;
            color: #059669;
            background: #ecfdf5;
            border: 1px solid #a7f3d0;
            border-radius: 6px;
            padding: 3px 8px;
        }
        .file-existing i { font-size: 10px; }

        /* ── SPACER & BUTTON AREA ── */
        .spacer { flex: 1; }

        .btn-area {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 15px;
            padding-top: 18px;
            border-top: 1px solid #ecfdf5;
            margin-top: 6px;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            min-width: 170px;
            height: 44px;
            padding: 0 22px;
            border-radius: 10px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all .18s ease;
            text-decoration: none;
            border: none;
            font-family: inherit;
            white-space: nowrap;
            box-sizing: border-box;
        }
        .btn i { font-size: 14px; }

        .btn-cancel {
            background: #fee2e2;
            color: #b91c1c;
            border: 1px solid #fca5a5;
        }
        .btn-cancel:hover {
            background: #ef4444;
            color: #ffffff;
            border-color: #ef4444;
            transform: translateY(-2px);
        }

        .btn-submit {
            background: #059669;
            color: #ffffff;
            box-shadow: 0 4px 6px rgba(5, 150, 105, 0.1);
        }
        .btn-submit:hover {
            background: #047857;
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(5, 150, 105, 0.3);
        }

        /* ── SUCCESS ALERT ── */
        .alert-success {
            display: flex;
            align-items: center;
            gap: 10px;
            background: #ecfdf5;
            border: 1px solid #6ee7b7;
            border-radius: 10px;
            padding: 12px 18px;
            margin-bottom: 20px;
            color: #065f46;
            font-size: 13px;
            font-weight: 500;
        }
        .alert-success i { font-size: 18px; color: #059669; }

        /* ── RESPONSIVE ── */
        @media (max-width: 768px) {
            body { padding: 16px 4%; }
            .page-wrapper { width: 100%; }
            .card-body { grid-template-columns: 1fr; }
            .col-left { border-right: none; border-bottom: 1px solid #d1fae5; }
            .form-grid-2 { grid-template-columns: 1fr; }
            .grid-2 { grid-template-columns: 1fr; }
            .card-header { flex-direction: column; align-items: flex-start; gap: 10px; }
            .btn-area { flex-direction: column-reverse; }
            .btn { width: 100%; }
        }
    </style>
</head>
<body>

<div class="page-wrapper">

    <?php if (isset($_GET['success'])): ?>
    <div class="alert-success">
        <i class="fas fa-check-circle"></i>
        Dokumentu arkivadu ho susesu! Statusu mudadu ba <strong>Review</strong>.
    </div>
    <?php endif; ?>

    <div class="card-main">

        <!-- HEADER -->
        <div class="card-header">
            <div class="card-header-left">
                <i class="fas fa-file-invoice-dollar"></i>
                <div>
                    <h2>Konfirma &amp; Rejistu Dokumentu</h2>
                    <p>Finance Document Archive Confirmation System</p>
                </div>
            </div>
            <div class="header-badge">
                <i class="fas fa-shield-alt"></i>
                DFO Authorized
            </div>
        </div>

        <!-- FORM -->
        <form action="" method="POST" enctype="multipart/form-data" id="mainForm">
            <input type="hidden" name="id_jv" value="<?= $id ?>">

            <div class="card-body">

                <!-- ===== KOLOM KIRI: DATA ===== -->
                <div class="col-left">

                    <div class="sec-title">
                        <i class="fas fa-info-circle"></i>
                        Informasaun Dokumentu
                    </div>

                    <div class="grid-2">
                        <div class="data-card">
                            <div class="lbl">No Pedido</div>
                            <div class="val"><?= htmlspecialchars($data['nomor_prt']) ?></div>
                        </div>
                        <div class="data-card">
                            <div class="lbl">Data Simu Pedido</div>
                            <div class="val"><?= formatTanggalPortugal($data['tgl_terima']) ?></div>
                        </div>
                    </div>

                    <div class="data-card mb-10">
                        <div class="lbl">Montante Total</div>
                        <div class="val amount"><?= formatUSD($data['total_adiantamento']) ?></div>
                        <div class="status-badge">
                            <i class="fas fa-circle"></i>
                            Pendente Konfirmasaun
                        </div>
                    </div>

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

                    <div class="sec-title">
                        <i class="fas fa-building"></i>
                        Detallu Pedido
                    </div>

                    <div class="data-card mb-10">
                        <div class="lbl">Diresaun</div>
                        <div class="val"><?= htmlspecialchars($data['direksi']) ?></div>
                    </div>

                    <div class="data-card">
                        <div class="lbl">Assuntu / Deskrisaun</div>
                        <div class="val desc-text">
                            <?= nl2br(htmlspecialchars($data['descripsi'])) ?>
                        </div>
                    </div>

                </div>
                <!-- /KOLOM KIRI -->

                <!-- ===== KOLOM KANAN: INPUT ===== -->
                <div class="col-right">

                    <div class="sec-title">
                        <i class="fas fa-edit"></i>
                        Rejistu Dados Arkivu
                    </div>

                    <div class="info-chip">
                        <i class="fas fa-info-circle"></i>
                        <span>Prenxe kampu hodi kompleta prosesu arkivu dokumentu ida-ne'e.</span>
                    </div>

                    <!-- ── CPV row ── -->
                    <div class="form-grid-2">
                        <div class="form-group">
                            <label>No CPV / PR <span class="req">*</span></label>
                            <input type="text"
                                   name="nomor_cpv"
                                   placeholder="Ex: CPV-2025-001"
                                   value="<?= htmlspecialchars($data['nomor_cpv'] ?? '') ?>"
                                   required>
                        </div>
                        <div class="form-group">
                            <label>Data Kria CPV <span class="req">*</span></label>
                            <div class="date-wrap">
                                <input type="text"
                                       id="inp_cpv"
                                       name="tgl_cpv"
                                       placeholder="dd/MM/yyyy"
                                       value="<?= !empty($data['tgl_cpv']) ? formatTanggalPortugal($data['tgl_cpv']) : '' ?>"
                                       readonly
                                       required>
                                <i class="fas fa-calendar-alt cal-icon"></i>
                                <div id="picker_cpv" class="date-picker"></div>
                            </div>
                        </div>
                    </div>

                    <!-- ── Anexo CPV ── -->
                    <div class="file-group">
                        <label>Anexo CPV / PR <span class="req">*</span></label>
                        <div class="file-input-wrap" id="wrap_cpv">
                            <input type="file"
                                   id="lampiran2"
                                   name="lampiran2"
                                   accept="application/pdf,.pdf"
                                   onchange="handleFile(this, 'label_cpv', 'err_cpv')">
                            <span class="file-input-label" id="label_cpv">
                                <i class="fas fa-file-pdf"></i>
                                <span class="file-name">Hili dokumentu PDF...</span>
                            </span>
                            <span class="file-input-btn">
                                <i class="fas fa-upload"></i> Hili
                            </span>
                        </div>
                        <?php if (!empty($data['lampiran2'])): ?>
                        <span class="file-existing">
                            <i class="fas fa-paperclip"></i>
                            Arkivu ezistente: <?= htmlspecialchars($data['lampiran2']) ?>
                        </span>
                        <?php endif; ?>
                        <span class="file-hint">
                            <i class="fas fa-info-circle"></i> Formatu ne'ebé akseptu: PDF deit
                        </span>
                        <span class="file-error" id="err_cpv">
                            <i class="fas fa-exclamation-circle"></i> Arquivo tenki iha formatu PDF!
                        </span>
                    </div>

                    <!-- ── OBL row ── -->
                    <div class="form-grid-2">
                        <div class="form-group">
                            <label>No OBL / PO</label>
                            <input type="text"
                                   name="nomor_obl"
                                   placeholder="Ex: OBL-2025-001"
                                   value="<?= htmlspecialchars($data['nomor_obl'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>Data Kria OBL</label>
                            <div class="date-wrap">
                                <input type="text"
                                       id="inp_obl"
                                       name="tanggal_obl"
                                       placeholder="dd/MM/yyyy"
                                       value="<?= !empty($data['tanggal_obl']) ? formatTanggalPortugal($data['tanggal_obl']) : '' ?>"
                                       readonly>
                                <i class="fas fa-calendar-alt cal-icon"></i>
                                <div id="picker_obl" class="date-picker"></div>
                            </div>
                        </div>
                    </div>

                    <!-- ── Anexo OBL ── -->
                    <div class="file-group">
                        <label>Anexo OBL / PO</label>
                        <div class="file-input-wrap" id="wrap_obl">
                            <input type="file"
                                   id="lampiran3"
                                   name="lampiran3"
                                   accept="application/pdf,.pdf"
                                   onchange="handleFile(this, 'label_obl', 'err_obl')">
                            <span class="file-input-label" id="label_obl">
                                <i class="fas fa-file-pdf"></i>
                                <span class="file-name">Hili dokumentu PDF...</span>
                            </span>
                            <span class="file-input-btn">
                                <i class="fas fa-upload"></i> Hili
                            </span>
                        </div>
                        <?php if (!empty($data['lampiran3'])): ?>
                        <span class="file-existing">
                            <i class="fas fa-paperclip"></i>
                            Arkivu ezistente: <?= htmlspecialchars($data['lampiran3']) ?>
                        </span>
                        <?php endif; ?>
                        <span class="file-hint">
                            <i class="fas fa-info-circle"></i> Formatu ne'ebé akseptu: PDF deit
                        </span>
                        <span class="file-error" id="err_obl">
                            <i class="fas fa-exclamation-circle"></i> Arquivo tenki iha formatu PDF!
                        </span>
                    </div>

                    <!-- ── Vendor ── -->
                    <div class="form-group">
                        <label>Naran Vendor</label>
                        <input type="text"
                               name="vendor_name"
                               placeholder="Ex: PT. Suplier Timor Leste..."
                               value="<?= htmlspecialchars($data['vendor_name'] ?? '') ?>">
                    </div>

                    <div class="spacer"></div>

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

                </div>
                <!-- /KOLOM KANAN -->

            </div>
        </form>

    </div><!-- /card-main -->
</div><!-- /page-wrapper -->

<script>
/* ════════════════════════════════════
   DATE PICKER
════════════════════════════════════ */
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 buildPicker(pickerId, inputId) {
    const picker = document.getElementById(pickerId);
    const input  = document.getElementById(inputId);
    let cur      = new Date();
    let selected = null;

    const existing = input.value.trim();
    if (existing) {
        const parts = existing.split('/');
        if (parts.length === 3) {
            const hari       = parseInt(parts[0]);
            const namaBulan  = parts[1];
            const tahun      = parseInt(parts[2]);
            const indeksBulan = MESES_PT.indexOf(namaBulan);
            if (indeksBulan !== -1) {
                selected = new Date(tahun, indeksBulan, hari);
                cur      = new Date(selected);
            }
        }
    }

    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-header">
            <button type="button" class="dp-nav" onclick="PKS['${pickerId}'].prev()">&#8249;</button>
            <span class="dp-title">${MESES_PT[m]} ${y}</span>
            <button type="button" class="dp-nav" onclick="PKS['${pickerId}'].next()">&#8250;</button>
        </div>
        <div class="dp-grid">`;

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

        for (let i = 0; i < firstDay; i++) {
            html += `<div class="dp-day empty"></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-day';
            if (isSel)        cls += ' selected';
            else if (isToday) cls += ' today';
            html += `<div class="${cls}" onclick="PKS['${pickerId}'].pick(${y},${m},${d})">${d}</div>`;
        }
        html += '</div>';
        picker.innerHTML = html;
    }

    function pick(y, m, d) {
        selected    = new Date(y, m, d);
        input.value = `${pad(d)}/${MESES_PT[m]}/${y}`;
        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()   { picker.style.display = 'block'; render(); }
    function close()  { picker.style.display = 'none'; }
    function toggle() { picker.style.display === 'none' || picker.style.display === '' ? open() : close(); }

    input.addEventListener('click',  e => { e.stopPropagation(); toggle(); });
    picker.addEventListener('click', e => { e.stopPropagation(); });

    return { prev, next, pick, open, close };
}

const PKS = {};
PKS['picker_cpv'] = buildPicker('picker_cpv', 'inp_cpv');
PKS['picker_obl'] = buildPicker('picker_obl', 'inp_obl');

document.addEventListener('click', () => {
    if (PKS['picker_cpv']) PKS['picker_cpv'].close();
    if (PKS['picker_obl']) PKS['picker_obl'].close();
});

/* ════════════════════════════════════
   FILE INPUT HANDLER
════════════════════════════════════ */
function handleFile(input, labelId, errId) {
    const labelEl = document.getElementById(labelId);
    const errEl   = document.getElementById(errId);
    const file    = input.files[0];

    const iconEl = labelEl.querySelector('i');
    const nameEl = labelEl.querySelector('.file-name');
    const sizeEl = labelEl.querySelector('.file-size');

    // Reset
    if (sizeEl) sizeEl.remove();

    if (!file) {
        iconEl.style.color = '';
        nameEl.textContent = 'Hili dokumentu PDF...';
        nameEl.style.color = '';
        nameEl.style.fontWeight = '';
        errEl.style.display = 'none';
        return;
    }

    // Validasi: harus PDF
    const isPdf = file.type === 'application/pdf' ||
                  file.name.toLowerCase().endsWith('.pdf');

    if (!isPdf) {
        input.value = '';
        iconEl.style.color = '#ef4444';
        nameEl.textContent = 'Hili dokumentu PDF...';
        nameEl.style.color = '';
        nameEl.style.fontWeight = '';
        errEl.style.display = 'flex';
        return;
    }

    errEl.style.display = 'none';

    // Tampilkan nama file & ukuran
    const rawName = file.name;
    const dispName = rawName.length > 32 ? rawName.substring(0, 29) + '...' : rawName;
    const sizeKB   = file.size < 1024 * 1024
        ? (file.size / 1024).toFixed(1) + ' KB'
        : (file.size / (1024 * 1024)).toFixed(1) + ' MB';

    iconEl.style.color = '#059669';
    nameEl.textContent = dispName;
    nameEl.style.color = '#065f46';
    nameEl.style.fontWeight = '600';

    const newSize = document.createElement('span');
    newSize.className = 'file-size';
    newSize.textContent = sizeKB;
    labelEl.appendChild(newSize);
}

/* ════════════════════════════════════
   FORM SUBMIT VALIDATION
════════════════════════════════════ */
document.getElementById('mainForm').addEventListener('submit', function(e) {
    let valid = true;

    // Cek apakah lampiran2 sudah diisi (jika belum ada existing file)
    const lamp1    = document.getElementById('lampiran2');
    const errCpv   = document.getElementById('err_cpv');
    const hasExisting1 = <?= !empty($data['lampiran2']) ? 'true' : 'false' ?>;

    if (!hasExisting1 && lamp1.files.length === 0) {
        errCpv.style.display = 'flex';
        errCpv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Anexo CPV/PR obrigatoriu!';
        valid = false;
    }

    if (!valid) e.preventDefault();
});
</script>

</body>
</html>
