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

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

// =====================================
// AMBIL ID
// =====================================
$id = $_GET['id'] ?? 0;

$stmt = $koneksi->prepare("
    SELECT jv_documents.*, users.full_name
    FROM jv_documents
    LEFT JOIN users ON jv_documents.uploaded_by_id = users.id_user
    WHERE id_jv = ?
");
$stmt->bind_param("i", $id);
$stmt->execute();

$result = $stmt->get_result();
$row = $result->fetch_assoc();

if (!$row) {
    echo "<script>alert('Dadus la hetan!'); window.location='daftar_dokumen.php';</script>";
    exit;
}

// =====================================
// FORMAT TANGGAL PORTUGIS
// =====================================
function formatTanggalPortugal($tanggal)
{
    if (!$tanggal || $tanggal == '0000-00-00') return '-';

    $bulan = [
        1=>'Janeiru',2=>'Fevereiru',3=>'Marsu',4=>'Abril',
        5=>'Maiu',6=>'Juñu',7=>'Jullu',8=>'Agostu',
        9=>'Setembru',10=>'Outubru',11=>'Novembru',12=>'Dezembru'
    ];

    $time = strtotime($tanggal);

    return date('d', $time) . '/' .
           $bulan[(int)date('m', $time)] . '/' .
           date('Y', $time);
}

// =====================================
// UPDATE DATA
// =====================================
if (isset($_POST['submit'])) {

    $file_nota = $row['file_nota'];

    // upload file baru
    if (!empty($_FILES['file_nota']['name'])) {

        $namaFile = time() . "_" . basename($_FILES['file_nota']['name']);
        $tmpName  = $_FILES['file_nota']['tmp_name'];

        move_uploaded_file(
            $tmpName,
            "../assets/uploads/" . $namaFile
        );

        $file_nota = $namaFile;
    }

    $tgl_terima         = $_POST['tgl_terima'];
    $nomor_prt          = $_POST['nomor_prt'];
    $division           = $_POST['division'];
    $direksi            = $_POST['direksi'];
    $descripsi          = $_POST['descripsi'];
    $nomor_apt          = $_POST['nomor_apt'];
    $nomor_ev           = $_POST['nomor_ev'];
    $line_item          = $_POST['line_item'];
    $vendor_name        = $_POST['vendor_name'];

    $total_adiantamento = str_replace(',', '', $_POST['total_adiantamento']);

    $update = $koneksi->prepare("
        UPDATE jv_documents SET
            file_nota=?,
            tgl_terima=?,
            nomor_prt=?,
            division=?,
            direksi=?,
            descripsi=?,
            nomor_apt=?,
            nomor_ev=?,
            line_item=?,
            vendor_name=?,
            total_adiantamento=?,
            status='didaftarkan'
        WHERE id_jv=?
    ");

    $update->bind_param(
        "sssssssssssi",
        $file_nota,
        $tgl_terima,
        $nomor_prt,
        $division,
        $direksi,
        $descripsi,
        $nomor_apt,
        $nomor_ev,
        $line_item,
        $vendor_name,
        $total_adiantamento,
        $id
    );

    $update->execute();

    echo "
    <script>
        alert('Mudansa susesu salva!');
        window.location='edit.php?id=$id';
    </script>";
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Edita Dokumentu Finance</title>

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://npmcdn.com/flatpickr/dist/l10n/pt.js"></script>

<style>

:root{
    --emerald-dark:#064e3b;
    --emerald:#047857;
    --emerald-light:#10b981;
    --bg:#f0fdf4;
    --white:#ffffff;
}

*{
    margin:0;
    padding:0;
    box-sizing:border-box;
}

body{
    background:var(--bg);
    font-family:Arial, sans-serif;
    color:#111827;
}

/* FULL PAGE */
.main-container{
    width:100%;
    min-height:100vh;
    padding:30px;
}

/* HEADER */
.page-header{
    background:linear-gradient(135deg,var(--emerald-dark),var(--emerald));
    border-radius:20px;
    padding:30px;
    color:white;
    margin-bottom:25px;
    box-shadow:0 10px 30px rgba(0,0,0,.08);
}

.header-flex{
    display:flex;
    justify-content:space-between;
    align-items:center;
    flex-wrap:wrap;
    gap:20px;
}

.page-title{
    font-size:24px;
    font-weight:700;
}

.page-subtitle{
    margin-top:6px;
    opacity:.85;
    font-size:14px;
}

.btn-back{
    background:white;
    color:var(--emerald-dark);
    text-decoration:none;
    padding:12px 18px;
    border-radius:12px;
    font-weight:700;
}

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

/* CARD HEADER */
.card-header{
    padding:20px 25px;
    background:#ecfdf5;
    border-bottom:1px solid #d1fae5;
    font-size:18px;
    font-weight:700;
    color:#065f46;
}

/* FORM BODY */
.form-body{
    padding:30px;
}

/* GRID */
.form-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:22px;
}

.full-width{
    grid-column:1 / -1;
}

/* FORM */
.form-group{
    display:flex;
    flex-direction:column;
}

.form-group label{
    margin-bottom:8px;
    font-size:13px;
    font-weight:700;
    color:#065f46;
}

.form-control{
    width:100%;
    border:1px solid #d1d5db;
    border-radius:12px;
    padding:13px 15px;
    font-size:14px;
    background:white;
    transition:.2s;
}

.form-control:focus{
    outline:none;
    border-color:var(--emerald);
    box-shadow:0 0 0 4px rgba(16,185,129,.15);
}

textarea.form-control{
    min-height:130px;
    resize:vertical;
}

/* FILE BUTTON */
.btn-preview{
    display:inline-flex;
    align-items:center;
    gap:6px;
    background:#ecfdf5;
    color:#065f46;
    border:1px solid #a7f3d0;
    padding:9px 14px;
    border-radius:10px;
    cursor:pointer;
    font-weight:700;
    margin-top:10px;
}

/* USD */
.input-money{
    position:relative;
}

.input-money span{
    position:absolute;
    left:15px;
    top:50%;
    transform:translateY(-50%);
    color:#065f46;
    font-weight:700;
}

.input-money input{
    padding-left:55px;
}

/* BUTTONS */
.form-actions{
    display:flex;
    justify-content:flex-end;
    gap:14px;
    margin-top:35px;
}

.btn-submit{
    background:var(--emerald);
    color:white;
    border:none;
    padding:14px 28px;
    border-radius:12px;
    cursor:pointer;
    font-weight:700;
    font-size:14px;
}

.btn-cancel{
    background:#ef4444;
    color:white;
    text-decoration:none;
    padding:14px 28px;
    border-radius:12px;
    font-weight:700;
}

/* PDF MODAL */
#pdfModal{
    display:none;
    position:fixed;
    z-index:9999;
    left:0;
    top:0;
    width:100%;
    height:100%;
    background:rgba(0,0,0,.75);
    backdrop-filter:blur(4px);
}

.modal-content{
    width:85%;
    height:90vh;
    margin:2% auto;
    background:white;
    border-radius:18px;
    overflow:hidden;
    position:relative;
}

.close-modal{
    position:absolute;
    right:15px;
    top:12px;
    background:#ef4444;
    color:white;
    width:35px;
    height:35px;
    border-radius:50%;
    text-align:center;
    line-height:35px;
    cursor:pointer;
    font-weight:bold;
    z-index:10;
}

/* RESPONSIVE */
@media(max-width:900px){

    .form-grid{
        grid-template-columns:1fr;
    }

    .form-actions{
        flex-direction:column;
    }

    .btn-submit,
    .btn-cancel{
        width:100%;
        text-align:center;
    }
}

</style>
</head>
<body>

<div class="main-container">

    <!-- HEADER -->
    <div class="page-header">
        <div class="header-flex">

            <div>
                <div class="page-title">
                    <i class="fas fa-file-pen"></i>
                    Edita Dokumentu Finance
                </div>

                <div class="page-subtitle">
                    Emerald Financial Report System
                </div>
            </div>

            <a href="daftar_dokumen.php" class="btn-back">
                <i class="fas fa-arrow-left"></i> Kansel
            </a>

        </div>
    </div>

    <!-- CARD -->
    <div class="card-finance">

        <div class="card-header">
            <i class="fas fa-folder-open"></i>
            Form Edit Dokumentu
        </div>

        <div class="form-body">

            <form method="POST"
                  enctype="multipart/form-data"
                  id="formEdit">

                <div class="form-grid">

                    <!-- FILE -->
                    <div class="form-group">
                        <label>Dokumentu PDF</label>

                        <input type="file"
                               name="file_nota"
                               class="form-control"
                               accept="application/pdf">

                        <?php if(!empty($row['file_nota'])): ?>
                            <button type="button"
                                    class="btn-preview"
                                    onclick="openPdfPreview('../assets/uploads/<?= rawurlencode($row['file_nota']) ?>')">

                                <i class="fas fa-file-pdf"></i>
                                Preview PDF
                            </button>
                        <?php endif; ?>
                    </div>

                    <!-- DATE -->
                    <div class="form-group">
                        <label>Data Simu Pedido</label>

                        <input type="text"
                               id="tgl_terima"
                               name="tgl_terima"
                               class="form-control"
                               value="<?= htmlspecialchars($row['tgl_terima']) ?>">
                    </div>

                    <!-- NOMOR -->
                    <div class="form-group">
                        <label>Numeru Pedido</label>

                        <input type="text"
                               name="nomor_prt"
                               class="form-control"
                               value="<?= htmlspecialchars($row['nomor_prt']) ?>"
                               required>
                    </div>

                    <!-- DIVISION -->
                    <div class="form-group">
                        <label>Diresaun</label>

                        <select name="division"
                                class="form-control"
                                required>

                            <option value="<?= htmlspecialchars($row['division']) ?>">
                                <?= htmlspecialchars($row['division']) ?>
                            </option>

                            <option value="0210101-GMSSI">0210101-GMSSI</option>
                            <option value="0210102-GVMSSI">0210102-GVMSSI</option>
                            <option value="0210104-GIA">0210104-GIA</option>
                            <option value="0210401-DGPS">0210401-DGPS</option>
                            <option value="0210402-DNAS">0210402-DNAS</option>
                            <option value="0210403-DNRC">0210403-DNRC</option>
                            <option value="0210404-DNPPD">0210404-DNPPD</option>
                            <option value="0210405-DNCP">0210405-DNCP</option>
                            <option value="0210501-DGSC">0210501-DGSC</option>
                            <option value="0210502-DNPFO">0210502-DNPFO</option>
                            <option value="0210503-DNARHP">0210503-DNARHP</option>
                            <option value="0210504-DNA">0210504-DNA</option>
                            <option value="0210505-DNPCRP">0210505-DNPCRP</option>

                        </select>
                    </div>

                    <!-- ATIVIDADE -->
                    <div class="form-group">
                        <label>Atividade</label>

                        <input type="text"
                               name="direksi"
                               class="form-control"
                               value="<?= htmlspecialchars($row['direksi']) ?>">
                    </div>

                    <!-- APT -->
                    <div class="form-group">
                        <label>Numeru APT</label>

                        <input type="text"
                               name="nomor_apt"
                               class="form-control"
                               value="<?= htmlspecialchars($row['nomor_apt']) ?>">
                    </div>

                    <!-- EV -->
                    <div class="form-group">
                        <label>Numeru EV</label>

                        <input type="text"
                               name="nomor_ev"
                               class="form-control"
                               value="<?= htmlspecialchars($row['nomor_ev']) ?>">
                    </div>

                    <!-- LINE ITEM -->
                    <div class="form-group">
                        <label>Line Item</label>

                        <input type="text"
                               name="line_item"
                               class="form-control"
                               value="<?= htmlspecialchars($row['line_item']) ?>">
                    </div>

                    <!-- VENDOR -->
                    <div class="form-group">
                        <label>Naran Vendor</label>

                        <input type="text"
                               name="vendor_name"
                               class="form-control"
                               value="<?= htmlspecialchars($row['vendor_name']) ?>">
                    </div>

                    <!-- USD -->
                    <div class="form-group">
                        <label>Montante (USD)</label>

                        <div class="input-money">
                            <span>USD</span>

                            <input type="text"
                                   name="total_adiantamento"
                                   class="form-control"
                                   value="<?= number_format($row['total_adiantamento'],2,'.',',') ?>">
                        </div>
                    </div>

                    <!-- STATUS -->
                    <div class="form-group">
                        <label>Status</label>

                        <input type="text"
                               class="form-control"
                               readonly
                               value="<?= htmlspecialchars($row['status']) ?>">
                    </div>

                    <!-- DESKRIPSI -->
                    <div class="form-group full-width">
                        <label>Deskrisaun</label>

                        <textarea name="descripsi"
                                  class="form-control"><?= htmlspecialchars($row['descripsi']) ?></textarea>
                    </div>

                </div>

                <!-- BUTTON -->
                <div class="form-actions">

                    <a href="daftar_dokumen.php"
                       class="btn-cancel">
                        <i class="fas fa-times"></i>
                        Kansel
                    </a>

                    <button type="submit"
                            name="submit"
                            class="btn-submit"
                            onclick="clearFormAfterSubmit()">

                        <i class="fas fa-paper-plane"></i>
                        Submete
                    </button>

                </div>

            </form>

        </div>
    </div>
</div>

<!-- MODAL PDF -->
<div id="pdfModal">

    <div class="modal-content">

        <span class="close-modal"
              onclick="closePdfPreview()">
              &times;
        </span>

        <iframe id="pdfFrame"
                width="100%"
                height="100%"
                style="border:none;">
        </iframe>

    </div>

</div>

<script>

// DATE PICKER PORTUGAL
flatpickr("#tgl_terima",{
    locale:"pt",
    altInput:true,
    altFormat:"d/F/Y",
    dateFormat:"Y-m-d"
});

// PDF PREVIEW
function openPdfPreview(url){

    document.getElementById('pdfFrame').src = url;

    document.getElementById('pdfModal').style.display = 'block';

    document.body.style.overflow = 'hidden';
}

function closePdfPreview(){

    document.getElementById('pdfModal').style.display = 'none';

    document.getElementById('pdfFrame').src = '';

    document.body.style.overflow = 'auto';
}

// CLEAR FORM
function clearFormAfterSubmit(){

    setTimeout(function(){

        document.getElementById('formEdit').reset();

    }, 500);
}

// CLOSE MODAL CLICK OUTSIDE
window.onclick = function(event){

    let modal = document.getElementById('pdfModal');

    if(event.target == modal){
        closePdfPreview();
    }
}

</script>

</body>
</html>