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

if (!isset($_SESSION['id_user']) || $_SESSION['role'] != 'dct') {
    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, '.', ',');
}

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) return null;
    $mes = $bulan[$exp[1]] ?? null;
    if (!$mes) return null;
    return $exp[2] . '-' . $mes . '-' . $exp[0];
}

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']     ?? '');
    $total_relatorio2 = trim($_POST['total_relatorio2'] ?? '');
    $nomor_ev         = trim($_POST['nomor_ev']         ?? '');
    $tanggal_ev       = convertTanggal($_POST['tanggal_ev']       ?? '');
    $nomor_tpo        = trim($_POST['nomor_tpo']        ?? '');
    $tgl_tpo          = convertTanggal($_POST['tgl_tpo']          ?? '');
    $nomor_pep        = trim($_POST['nomor_pep']        ?? '');
    $tanggal_pep      = convertTanggal($_POST['tanggal_pep']      ?? '');
    $tanggal_verifikasi = convertTanggal($_POST['tanggal_verifikasi'] ?? '');
    $nama_verikador   = trim($_POST['nama_verikador']   ?? '');
    $tipo_pagamento   = trim($_POST['tipo_pagamento']   ?? '');
    $deskripsi2       = trim($_POST['deskripsi2']       ?? '');

    /* ── Upload lampiran4 (Anexo PRT) ── */
    $lampiran4_path = null;
    if (!empty($_FILES['lampiran4']['name']) && $_FILES['lampiran4']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['lampiran4']['name'], PATHINFO_EXTENSION));
        if ($ext === 'pdf') {
            $dir = '../uploads/lampiran/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $fn = 'prt_' . $id_post . '_' . time() . '.pdf';
            if (move_uploaded_file($_FILES['lampiran4']['tmp_name'], $dir . $fn)) $lampiran4_path = $fn;
        }
    }

    /* ── Upload lampiran5 (Anexo TPO) ── */
    $lampiran5_path = null;
    if (!empty($_FILES['lampiran5']['name']) && $_FILES['lampiran5']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['lampiran5']['name'], PATHINFO_EXTENSION));
        if ($ext === 'pdf') {
            $dir = '../uploads/lampiran/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $fn = 'tpo_' . $id_post . '_' . time() . '.pdf';
            if (move_uploaded_file($_FILES['lampiran5']['tmp_name'], $dir . $fn)) $lampiran5_path = $fn;
        }
    }

    $stmt = $koneksi->prepare("
        UPDATE jv_documents SET
            nomor_apt=?, tanggal_its=?, nomor_prt2=?, tanggal_prt2=?,
            total_relatorio2=?,
            nomor_ev=?, tanggal_ev=?, nomor_tpo=?, tgl_tpo=?,
            lampiran4=COALESCE(?,lampiran4), lampiran5=COALESCE(?,lampiran5),
            nomor_pep=?, tanggal_pep=?,
            tanggal_verifikasi=?, nama_verikador=?,
            tipo_pagamento=?, deskripsi2=?,
            status='diaudit'
        WHERE id_jv=?
    ");
    $stmt->bind_param("sssssssssssssssssi",
        $nomor_apt, $tanggal_its, $nomor_prt2, $tanggal_prt2,
        $total_relatorio2,
        $nomor_ev, $tanggal_ev, $nomor_tpo, $tgl_tpo,
        $lampiran4_path, $lampiran5_path,
        $nomor_pep, $tanggal_pep,
        $tanggal_verifikasi, $nama_verikador,
        $tipo_pagamento, $deskripsi2,
        $id_post
    );
    $stmt->execute();
    $stmt->close();
    header("Location: dctarsipkonfirmasi.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">
<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', sans-serif;
    background: #044919;
    color: #1f2937;
    padding: 28px 20px;
    min-height: 100vh;
}

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

/* ── HEADER ── */
.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: 13px;
    font-weight: 600;
    padding: 4px 14px;
    border-radius: 20px;
    letter-spacing: .04em;
}

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

/* ── CONTENT ── */
.content { padding: 28px 30px; }

/* ── SECTION LABEL ── */
.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; }

/* ── READ-ONLY INFO GRID — 3 COL ── */
.info-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    margin-bottom: 26px;
}
.info-card {
    background: #f0fdf4;
    border: 1px solid #d1fae5;
    border-radius: 10px;
    padding: 12px 15px;
}
.info-card.span3 { grid-column: span 3; }
.info-card .lbl {
    font-size: 9.5px; font-weight: 700; color: #059669;
    text-transform: uppercase; letter-spacing: .08em; margin-bottom: 5px;
}
.info-card .val { font-size: 13.5px; font-weight: 600; color: #1f2937; line-height: 1.4; }
.info-card .val.amount { font-size: 19px; color: #047857; font-variant-numeric: tabular-nums; }
.info-card .val.desc { font-size: 12.5px; font-weight: 400; color: #374151; line-height: 1.65; }

/* ── DIVIDER ── */
.divider { border: none; border-top: 2px solid #f0fdf4; margin: 0 0 26px; }

/* ════════════════════════════════════════
   INPUT SECTION — 3 COLUMNS
════════════════════════════════════════ */
.form-3col {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    align-items: start;
}
/* ── FULL WIDTH SECTION ── */
.full-width-card {
    margin-top: 20px;
    background: #f8fffe;
    border: 1px solid #d1fae5;
    border-radius: 14px;
    padding: 20px 18px;
}

.full-width-grid {
    display: grid;
    grid-template-columns: 1fr 2fr;
    gap: 18px;
    align-items: start;
}

@media (max-width: 700px) {
    .full-width-grid {
        grid-template-columns: 1fr;
    }
}
/* Each column card */
.col-card {
    background: #f8fffe;
    border: 1px solid #d1fae5;
    border-radius: 14px;
    padding: 20px 18px;
    display: flex;
    flex-direction: column;
    gap: 14px;
}

/* Column header label */
.col-head {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 9.5px;
    font-weight: 800;
    color: #047857;
    text-transform: uppercase;
    letter-spacing: .12em;
    padding-bottom: 10px;
    border-bottom: 1.5px solid #d1fae5;
    margin-bottom: 2px;
}
.col-head i { font-size: 12px; color: #10b981; }

/* Form fields */
.form-group { display: flex; flex-direction: column; gap: 5px; }

.form-group label {
    font-size: 9.5px;
    font-weight: 700;
    color: #059669;
    text-transform: uppercase;
    letter-spacing: .08em;
}
.form-group label .req { color: #ef4444; margin-left: 2px; }

.form-group input[type="text"] {
    height: 40px;
    padding: 0 12px;
    border: 1px solid #c6f0df;
    border-radius: 9px;
    font-size: 13px;
    font-family: 'Segoe UI', sans-serif;
    color: #1f2937;
    background: #ffffff;
    outline: none;
    width: 100%;
    transition: border-color .15s, box-shadow .15s;
}
.form-group input[type="text"]:focus {
    border-color: #34d399;
    box-shadow: 0 0 0 3px rgba(52,211,153,.12);
}
.form-group input[type="text"]:hover:not(:focus) { border-color: #6ee7b7; }
.form-group input::placeholder { color: #a7f3d0; }
.form-group input.amt-input {
    font-variant-numeric: tabular-nums;
    font-weight: 600;
    color: #047857;
    text-align: right;
    padding-right: 14px;
}

/* ── DATE WRAPPER ── */
.date-wrap { position: relative; }
.date-wrap .cal-ico {
    position: absolute;
    right: 11px; top: 50%;
    transform: translateY(-50%);
    font-size: 14px;
    color: #6ee7b7;
    pointer-events: none;
}
.dpicker {
    position: absolute;
    top: calc(100% + 5px);
    left: 0;
    z-index: 400;
    background: #fff;
    border: 1px solid #d1fae5;
    border-radius: 14px;
    padding: 14px;
    box-shadow: 0 10px 28px rgba(0,0,0,.10);
    display: none;
    min-width: 244px;
}
.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: #6ee7b7; font-weight: 700; padding: 3px 0; }
.dp-d {
    font-size: 12px; padding: 6px 2px;
    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; }
.dp-d.selected { background: #059669; color: #fff; font-weight: 700; }

/* ── FILE INPUT ── */
.file-wrap {
    position: relative;
    display: flex;
    align-items: center;
    height: 40px;
    border: 1px solid #c6f0df;
    border-radius: 9px;
    background: #fff;
    overflow: hidden;
    transition: border-color .15s, box-shadow .15s;
    cursor: pointer;
}
.file-wrap:focus-within {
    border-color: #34d399;
    box-shadow: 0 0 0 3px rgba(52,211,153,.12);
}
.file-wrap:hover { border-color: #6ee7b7; }
.file-wrap input[type="file"] {
    position: absolute; inset: 0; opacity: 0; cursor: pointer; z-index: 2; width: 100%; height: 100%;
}
.file-label {
    display: flex; align-items: center; gap: 7px;
    padding: 0 10px; flex: 1; min-width: 0;
    font-size: 12px; color: #9ca3af;
    pointer-events: none;
    white-space: nowrap; overflow: hidden;
}
.file-label i { color: #6ee7b7; font-size: 13px; flex-shrink: 0; }
.file-label .fn { overflow: hidden; text-overflow: ellipsis; }
.file-btn {
    flex-shrink: 0; height: 100%; padding: 0 12px;
    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;
}
.file-hint { font-size: 10px; color: #a7f3d0; display: flex; align-items: center; gap: 4px; margin-top: 2px; }
.file-err  { font-size: 10px; color: #ef4444; display: none; align-items: center; gap: 4px; margin-top: 2px; }

/* ── FOOTER BUTTONS ── */
.pg-footer {
    background: #f8fafc;
    border-top: 1px solid #e2e8f0;
    padding: 20px 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 .15s;
    font-family: 'Segoe UI', sans-serif;
}
.btn:hover { opacity: .88; transform: translateY(-2px); }
.btn:active { transform: scale(.98); }
.btn-cancel { background: #ef4444; color: #fff; }
.btn-submit { background: #047857; color: #fff; }

/* ── RESPONSIVE ── */
@media (max-width: 1024px) {
    .form-3col { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 700px) {
    .info-grid { grid-template-columns: 1fr; }
    .info-card.span3 { grid-column: span 1; }
    .form-3col { grid-template-columns: 1fr; }
    .pg-footer { flex-direction: column; gap: 12px; }
    .btn { width: 100%; }
}
</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>

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

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

            <!-- ══ INFO READONLY ══ -->
            <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">No CPV / PR</div>
                    <div class="val"><?= htmlspecialchars($data['nomor_cpv']) ?></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 Simu Pedido</div>
                    <div class="val"><?= formatTanggalPortugal($data['tgl_terima']) ?></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">Data Kria OBL / PO</div>
                    <div class="val"><?= formatTanggalPortugal($data['tanggal_obl']) ?></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">Montante</div>
                    <div class="val amount"><?= formatUSD($data['total_adiantamento']) ?></div>
                </div>
                <div class="info-card">
                    <div class="lbl">Vendor</div>
                    <div class="val"><?= htmlspecialchars($data['vendor_name']) ?></div>
                </div>
                <div class="info-card span3">
                    <div class="lbl">Assuntu</div>
                    <div class="val desc"><?= nl2br(htmlspecialchars($data['descripsi'])) ?></div>
                </div>
            </div>

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

            <!-- ══ INPUT — 3 KOLOM ══ -->
            <div class="sec-label"><i class="fas fa-edit"></i> Input Konfirmasaun</div>

            <div class="form-3col">

                <!-- ═══ KOLOM KIRI ═══ -->
                <div class="col-card">
                    <div class="col-head"><i class="fas fa-file-alt"></i> ITS / APT &amp; PRT</div>

                    <!-- No ITS/APT -->
                    <div class="form-group">
                        <label>No ITS / APT <span class="req">*</span></label>
                        <input type="text" name="nomor_apt"
                               value="<?= htmlspecialchars($data['nomor_apt'] ?? '') ?>"
                               placeholder="Ex: APT-2025-001" required autocomplete="off">
                    </div>

                    <!-- Data Kria ITS/APT -->
                    <div class="form-group">
                        <label>Data Kria ITS / APT <span class="req">*</span></label>
                        <div class="date-wrap">
                            <input type="text" id="inp_its" name="tanggal_its"
                                   value="<?= !empty($data['tanggal_its']) ? formatTanggalPortugal($data['tanggal_its']) : '' ?>"
                                   placeholder="dd/MM/yyyy" readonly required autocomplete="off">
                            <i class="fas fa-calendar-alt cal-ico"></i>
                            <div id="picker_its" class="dpicker"></div>
                        </div>
                    </div>

                    <!-- No PRT -->
                    <div class="form-group">
                        <label>No PRT<span class="req">*</span></label>
                        <input type="text" name="nomor_prt2"
                               value="<?= htmlspecialchars($data['nomor_prt2'] ?? '') ?>"
                               placeholder="Ex: PRT-2025-001" required autocomplete="off">
                    </div>

                    <!-- Data Kria PRT -->
                    <div class="form-group">
                        <label>Data Kria PRT<span class="req">*</span></label>
                        <div class="date-wrap">
                            <input type="text" id="inp_prt" name="tanggal_prt2"
                                   value="<?= !empty($data['tanggal_prt2']) ? formatTanggalPortugal($data['tanggal_prt2']) : '' ?>"
                                   placeholder="dd/MM/yyyy" required readonly autocomplete="off">
                            <i class="fas fa-calendar-alt cal-ico"></i>
                            <div id="picker_prt" class="dpicker"></div>
                        </div>
                    </div>

                    <!-- Anexo PRT -->
                    <div class="form-group">
                        <label>Anexo PRT</label>
                        <div class="file-wrap">
                            <input type="file" id="lampiran4" name="lampiran4"
                                   accept="application/pdf,.pdf"
                                   onchange="handleFile(this,'flabel4','ferr4')">
                            <span class="file-label" id="flabel4">
                                <i class="fas fa-file-pdf"></i>
                                <span class="fn">Hili PDF...</span>
                            </span>
                            <span class="file-btn"><i class="fas fa-upload"></i> Hili</span>
                        </div>
                        <?php if (!empty($data['lampiran4'])): ?>
                        <span style="font-size:10px;color:#059669;margin-top:2px;">
                            <i class="fas fa-paperclip"></i> <?= htmlspecialchars($data['lampiran4']) ?>
                        </span>
                        <?php endif; ?>
                        <span class="file-hint"><i class="fas fa-info-circle"></i> PDF deit</span>
                        <span class="file-err" id="ferr4"><i class="fas fa-exclamation-circle"></i> Tenki PDF!</span>
                    </div>

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

                <!-- ═══ KOLOM TENGAH ═══ -->
                <div class="col-card">
                    <div class="col-head"><i class="fas fa-receipt"></i> EV &amp; TPO</div>

                    <!-- Numeru EV -->
                    <div class="form-group">
                        <label>Numeru EV<span class="req">*</span></label>
                        <input type="text" id="nomor_ev" name="nomor_ev"
                               value="<?= htmlspecialchars($data['nomor_ev'] ?? '') ?>"
                               placeholder="Ex: EV-2025-001" required autocomplete="off">
                    </div>

                    <!-- Data Kria EV -->
                    <div class="form-group">
                        <label>Data Kria EV<span class="req">*</span></label>
                        <div class="date-wrap">
                            <input type="text" id="tanggal_ev" name="tanggal_ev"
                                   value="<?= !empty($data['tanggal_ev']) ? formatTanggalPortugal($data['tanggal_ev']) : '' ?>"
                                   placeholder="dd/MM/yyyy" required readonly autocomplete="off">
                            <i class="fas fa-calendar-alt cal-ico"></i>
                            <div id="picker_ev" class="dpicker"></div>
                        </div>
                    </div>

                    <!-- Numeru TPO -->
                    <div class="form-group">
                        <label>Numeru TPO<span class="req">*</span></label>
                        <input type="text" id="nomor_tpo" name="nomor_tpo"
                               value="<?= htmlspecialchars($data['nomor_tpo'] ?? '') ?>"
                               placeholder="Ex: TPO-2025-001" required autocomplete="off">
                    </div>

                    <!-- Data Kria TPO -->
                    <div class="form-group">
                        <label>Data Kria TPO<span class="req">*</span></label>
                        <div class="date-wrap">
                            <input type="text" id="tgl_tpo" name="tgl_tpo"
                                   value="<?= !empty($data['tgl_tpo']) ? formatTanggalPortugal($data['tgl_tpo']) : '' ?>"
                                   placeholder="dd/MM/yyyy" required readonly autocomplete="off">
                            <i class="fas fa-calendar-alt cal-ico"></i>
                            <div id="picker_tpo" class="dpicker"></div>
                        </div>
                    </div>

                    <!-- Anexo TPO -->
                    <div class="form-group">
                        <label>Anexo TPO</label>
                        <div class="file-wrap">
                            <input type="file" id="lampiran5" name="lampiran5"
                                   accept="application/pdf,.pdf"
                                   onchange="handleFile(this,'flabel5','ferr5')">
                            <span class="file-label" id="flabel5">
                                <i class="fas fa-file-pdf"></i>
                                <span class="fn">Hili PDF...</span>
                            </span>
                            <span class="file-btn"><i class="fas fa-upload"></i> Hili</span>
                        </div>
                        <?php if (!empty($data['lampiran5'])): ?>
                        <span style="font-size:10px;color:#059669;margin-top:2px;">
                            <i class="fas fa-paperclip"></i> <?= htmlspecialchars($data['lampiran5']) ?>
                        </span>
                        <?php endif; ?>
                        <span class="file-hint"><i class="fas fa-info-circle"></i> PDF deit</span>
                        <span class="file-err" id="ferr5"><i class="fas fa-exclamation-circle"></i> Tenki PDF!</span>
                    </div>
                </div>
                <!-- /KOLOM TENGAH -->

                <!-- ═══ KOLOM KANAN ═══ -->
                <div class="col-card">
                    <div class="col-head"><i class="fas fa-stamp"></i> PEP &amp; Verifikasaun</div>

                    <!-- Numeru PEP -->
                    <div class="form-group">
                        <label>Numeru PEP<span class="req">*</span></label>
                        <input type="text" id="nomor_pep" name="nomor_pep"
                               value="<?= htmlspecialchars($data['nomor_pep'] ?? '') ?>"
                               placeholder="Ex: PEP-2025-001" required autocomplete="off">
                    </div>

                    <!-- Data Kria PEP -->
                    <div class="form-group">
                        <label>Data Kria PEP<span class="req">*</span></label>
                        <div class="date-wrap">
                            <input type="text" id="tanggal_pep" name="tanggal_pep"
                                   value="<?= !empty($data['tanggal_pep']) ? formatTanggalPortugal($data['tanggal_pep']) : '' ?>"
                                   placeholder="dd/MM/yyyy" required readonly autocomplete="off">
                            <i class="fas fa-calendar-alt cal-ico"></i>
                            <div id="picker_pep" class="dpicker"></div>
                        </div>
                    </div>

                    <!-- Data Verifikado -->
                    <div class="form-group">
                        <label>Data Verifikado<span class="req">*</span></label>
                        <div class="date-wrap">
                            <input type="text" id="tanggal_verifikasi" name="tanggal_verifikasi"
                                   value="<?= !empty($data['tanggal_verifikasi']) ? formatTanggalPortugal($data['tanggal_verifikasi']) : '' ?>"
                                   placeholder="dd/MM/yyyy" required readonly autocomplete="off">
                            <i class="fas fa-calendar-alt cal-ico"></i>
                            <div id="picker_vrf" class="dpicker"></div>
                        </div>
                    </div>

                    <!-- Naran Verifikado -->
                    <div class="form-group">
                        <label>Naran Verifikado<span class="req">*</span></label>
                        <input type="text" id="nama_verikador" name="nama_verikador"
                               value="<?= htmlspecialchars($data['nama_verikador'] ?? '') ?>"
                               placeholder="Naran ema ne'ebé verifikadu..." required autocomplete="off">
                    </div>

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

            </div><!-- /form-3col -->

            <!-- ═══ FULL WIDTH SECTION ═══ -->
<div class="full-width-card">

    <div class="col-head">
        <i class="fas fa-wallet"></i>
        Informasaun Pagamentu & Assuntu
    </div>

    <div class="full-width-grid">
<!-- Montante -->
                    <div class="form-group">
                        <label>Montante Relatorio (USD) <span class="req">*</span></label>
                        <input type="text" id="amtView" class="amt-input"
                               placeholder="$ 0.00" autocomplete="off" inputmode="decimal" required>
                        <input type="hidden" name="total_relatorio2" id="amtReal"
                               value="<?= htmlspecialchars($data['total_relatorio2'] ?? '') ?>">
                    </div>

        <!-- Tipo Pagamento -->
        <div class="form-group">
            <label>Tipo Pagamento<span class="req">*</span></label>
            <input type="text" name="tipo_pagamento"
                   value="<?= htmlspecialchars($data['tipo_pagamento'] ?? '') ?>"
                   placeholder="Ex: Transferénsia, Txeke..." required autocomplete="off">
        </div>

        <!-- Assuntu -->
       
<div class="info-card span3">
    <div class="form-group">
                    <label>Assuntu Relatorio<span class="req">*</span></label>
            <input type="text" name="deskripsi2"
                   value="<?= htmlspecialchars($data['deskripsi2'] ?? '') ?>"
                   placeholder="Deskrisaun badak..." required autocomplete="off">
                </div>
                </div>
    </div>

</div>
        </div><!-- /content -->

        <!-- FOOTER -->
        <div class="pg-footer">
            <a href="dctkonfirmasidok.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><!-- /page -->

<script>
/* ════════════ DATE PICKER ════════════ */
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();
    let selected = null;

    // Pre-load existing value
    const existing = inp.value.trim();
    if (existing) {
        const parts = existing.split('/');
        if (parts.length === 3) {
            const idx = MESES.indexOf(parts[1]);
            if (idx !== -1) {
                selected = new Date(parseInt(parts[2]), idx, parseInt(parts[0]));
                cur = new Date(selected);
            }
        }
    }

    function render() {
        const y = cur.getFullYear(), 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 isT = today.getDate()===d && today.getMonth()===m && today.getFullYear()===y;
            const isS = selected && selected.getDate()===d && selected.getMonth()===m && selected.getFullYear()===y;
            let cls = 'dp-d';
            if (isS) cls += ' selected';
            else if (isT) cls += ' today';
            h += `<div class="${cls}" data-d="${d}">${d}</div>`;
        }
        h += '</div>';
        pk.innerHTML = h;

        pk.querySelectorAll('.dp-nav').forEach(b => b.addEventListener('click', e => {
            e.stopPropagation();
            cur = b.dataset.a === 'prev'
                ? new Date(cur.getFullYear(), cur.getMonth()-1, 1)
                : new Date(cur.getFullYear(), cur.getMonth()+1, 1);
            render();
        }));
        pk.querySelectorAll('.dp-d').forEach(el => el.addEventListener('click', e => {
            e.stopPropagation();
            const d = parseInt(el.dataset.d);
            selected = new Date(cur.getFullYear(), cur.getMonth(), d);
            inp.value = `${pad(d)}/${MESES[cur.getMonth()]}/${cur.getFullYear()}`;
            pk.style.display = 'none';
        }));
    }

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

// Init all pickers
const pickerMap = [
    ['picker_its','inp_its'],
    ['picker_prt','inp_prt'],
    ['picker_ev', 'tanggal_ev'],
    ['picker_tpo','tgl_tpo'],
    ['picker_pep','tanggal_pep'],
    ['picker_vrf','tanggal_verifikasi'],
];
pickerMap.forEach(([pid, iid]) => makePicker(pid, iid));
document.addEventListener('click', () => {
    document.querySelectorAll('.dpicker').forEach(p => p.style.display = 'none');
});

/* ════════════ MONTANTE FORMAT ════════════ */
const amtView = document.getElementById('amtView');
const amtReal = document.getElementById('amtReal');

// Init display from existing value
if (amtReal.value) {
    const n = parseFloat(amtReal.value);
    if (!isNaN(n)) {
        amtView.value = '$ ' + n.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2});
    }
}

amtView.addEventListener('focus', function() {
    this.value = amtReal.value || '';
    this.select();
});
amtView.addEventListener('blur', function() {
    const raw = this.value.replace(/[^0-9.]/g, '');
    if (!raw) { this.value = ''; amtReal.value = ''; return; }
    const num = parseFloat(raw);
    if (isNaN(num)) { this.value = ''; amtReal.value = ''; return; }
    amtReal.value = num.toFixed(2);
    this.value = '$ ' + num.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2});
});
amtView.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') { e.preventDefault(); this.blur(); }
});

/* ════════════ FILE INPUT HANDLER ════════════ */
function handleFile(input, labelId, errId) {
    const lbl = document.getElementById(labelId);
    const err = document.getElementById(errId);
    const file = input.files[0];
    const ico  = lbl.querySelector('i');
    const fn   = lbl.querySelector('.fn');

    if (!file) {
        ico.style.color = '';
        fn.textContent = 'Hili PDF...';
        fn.style.color = '';
        err.style.display = 'none';
        return;
    }

    const isPdf = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf');
    if (!isPdf) {
        input.value = '';
        ico.style.color = '#ef4444';
        fn.textContent = 'Hili PDF...';
        fn.style.color = '';
        err.style.display = 'flex';
        return;
    }

    err.style.display = 'none';
    ico.style.color = '#059669';
    const name = file.name.length > 28 ? file.name.substring(0, 25) + '...' : file.name;
    fn.textContent = name;
    fn.style.color = '#065f46';
    fn.style.fontWeight = '600';
}
</script>

</body>
</html>