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

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

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

if ($id <= 0) {
    header("Location: daftar_dokumen.php");
    exit;
}

// =====================================
// QUERY DATA
// =====================================
$stmt = $koneksi->prepare("
    SELECT *
    FROM jv_documents
    WHERE id_jv = ?
");
$stmt->bind_param("i", $id);
$stmt->execute();

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

if (!$data) {
    die("Dadus la hetan.");
}

// =====================================
// UPDATE DATA
// =====================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $tgl_terima         = $_POST['tgl_terima'];
    $nomor_prt          = trim($_POST['nomor_prt']);
    $direksi            = trim($_POST['direksi']);
    $descripsi          = trim($_POST['descripsi']);
    $total_adiantamento = trim($_POST['total_adiantamento']);

    // file lama
    $file_nota = $data['file_nota'];
    $lampiran1 = $data['lampiran1'];

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

        $tmp  = $_FILES['file_nota']['tmp_name'];
        $name = time() . "_nota_" . basename($_FILES['file_nota']['name']);

        move_uploaded_file($tmp, "../assets/uploads/" . $name);

        $file_nota = $name;
    }

    // upload lampiran baru
    if (!empty($_FILES['lampiran1']['name'])) {

        $tmp  = $_FILES['lampiran1']['tmp_name'];
        $name = time() . "_lamp_" . basename($_FILES['lampiran1']['name']);

        move_uploaded_file($tmp, "../assets/uploads/" . $name);

        $lampiran1 = $name;
    }

    $update = $koneksi->prepare("
        UPDATE jv_documents SET
            tgl_terima = ?,
            nomor_prt = ?,
            direksi = ?,
            descripsi = ?,
            total_adiantamento = ?,
            file_nota = ?,
            lampiran1 = ?
        WHERE id_jv = ?
    ");

    $update->bind_param(
        "sssssssi",
        $tgl_terima,
        $nomor_prt,
        $direksi,
        $descripsi,
        $total_adiantamento,
        $file_nota,
        $lampiran1,
        $id
    );

    $update->execute();

    $_SESSION['alert_success'] = "Dokumentu susesu atualiza!";

    header("Location: daftar_dokumen.php");
    exit;
}

// =====================================
// ALERT
// =====================================
$alert_success = $_SESSION['alert_success'] ?? null;
unset($_SESSION['alert_success']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Edita Dokumentu</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;
}

/* hide adminlte */
.main-header,
.main-sidebar,
.main-footer,
#sidebar-overlay{
    display:none !important;
}

.content-wrapper,
body:not(.sidebar-mini-md):not(.sidebar-mini-xs):not(.layout-top-nav) .content-wrapper{
    margin-left:0 !important;
    margin-top:0 !important;
    padding:0 !important;
    background:var(--bg);
    min-height:100vh;
    width:100% !important;
}

body{
    margin:0;
    padding:0;
    background:var(--bg);
    font-family:Arial,sans-serif;
}

.main-container{
    padding:30px;
}

/* header */
.page-header{
    background:linear-gradient(135deg,var(--emerald-dark),var(--emerald));
    border-radius:18px;
    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:15px;
}

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

.page-subtitle{
    font-size:13px;
    opacity:.8;
    margin-top:5px;
}

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

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

.card-header{
    background:#f8fffb;
    padding:18px 24px;
    border-bottom:1px solid #ecfdf5;
    font-size:15px;
    font-weight:700;
    color:#065f46;
}

.card-body{
    padding:30px;
}

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

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

.form-group-full{
    grid-column:1 / -1;
}

label{
    margin-bottom:8px;
    font-size:13px;
    font-weight:700;
    color:#374151;
}

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

.form-control:focus{
    border-color:#10b981;
    box-shadow:0 0 0 3px rgba(16,185,129,.15);
}

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

/* file preview */
.file-box{
    background:#f8fafc;
    border:1px dashed #cbd5e1;
    padding:15px;
    border-radius:12px;
    margin-bottom:10px;
}

.file-link{
    color:#047857;
    font-weight:700;
    text-decoration:none;
}

.file-link:hover{
    text-decoration:underline;
}

/* button */
.btn-submit{
    background:linear-gradient(135deg,#047857,#10b981);
    color:white;
    border:none;
    padding:14px 24px;
    border-radius:12px;
    font-size:14px;
    font-weight:700;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    gap:8px;
}

.btn-back{
    background:#ef4444;
    color:white;
    text-decoration:none;
    padding:14px 24px;
    border-radius:12px;
    font-size:14px;
    font-weight:700;
    display:inline-flex;
    align-items:center;
    gap:8px;
}

.button-group{
    margin-top:30px;
    display:flex;
    gap:12px;
    flex-wrap:wrap;
}

/* responsive */
@media(max-width:768px){

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

    .main-container{
        padding:15px;
    }

    .card-body{
        padding:20px;
    }
}
</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-edit"></i>
                    Edita Dokumentu
                </div>

                <div class="page-subtitle">
                    Sistema Arkivu Finanseiru - Emerald Financial Report
                </div>
            </div>

            <a href="daftar_dokumen.php" class="btn-dashboard">
                <i class="fas fa-arrow-left"></i>
                Fila Fali
            </a>
        </div>
    </div>

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

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

        <div class="card-body">

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

                <div class="form-grid">

                    <!-- DATA -->
                    <div class="form-group">
                        <label>Data Simu Pedido</label>
                        <input
                            type="text"
                            id="tgl_terima"
                            name="tgl_terima"
                            class="form-control"
                            value="<?= htmlspecialchars($data['tgl_terima']) ?>"
                            required>
                    </div>

                    <!-- NOMOR -->
                    <div class="form-group">
                        <label>No Pedido</label>
                        <input
                            type="text"
                            name="nomor_prt"
                            class="form-control"
                            value="<?= htmlspecialchars($data['nomor_prt']) ?>"
                            required>
                    </div>

                    <!-- DIRESAUN -->
                    <div class="form-group">
                        <label>Diresaun</label>
                        <input
                            type="text"
                            name="direksi"
                            class="form-control"
                            value="<?= htmlspecialchars($data['direksi']) ?>"
                            required>
                    </div>

                    <!-- MONTANTE -->
                    <div class="form-group">
                        <label>Montante</label>
                        <input
                            type="number"
                            step="0.01"
                            name="total_adiantamento"
                            class="form-control"
                            value="<?= htmlspecialchars($data['total_adiantamento']) ?>"
                            required>
                    </div>

                    <!-- ASSUNTU -->
                    <div class="form-group form-group-full">
                        <label>Assuntu</label>
                        <textarea
                            name="descripsi"
                            class="form-control"
                            required><?= htmlspecialchars($data['descripsi']) ?></textarea>
                    </div>

                    <!-- FILE NOTA -->
                    <div class="form-group">
                        <label>Dokumentu Principal (Nota)</label>

                        <?php if (!empty($data['file_nota'])): ?>
                        <div class="file-box">
                            <a
                                class="file-link"
                                target="_blank"
                                href="../assets/uploads/<?= rawurlencode($data['file_nota']) ?>">
                                <i class="fas fa-file-pdf"></i>
                                Haree Dokumentu Atual
                            </a>
                        </div>
                        <?php endif; ?>

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

                    <!-- LAMPIRAN -->
                    <div class="form-group">
                        <label>Anexo</label>

                        <?php if (!empty($data['lampiran1'])): ?>
                        <div class="file-box">
                            <a
                                class="file-link"
                                target="_blank"
                                href="../assets/uploads/<?= rawurlencode($data['lampiran1']) ?>">
                                <i class="fas fa-file-pdf"></i>
                                Haree Anexo Atual
                            </a>
                        </div>
                        <?php endif; ?>

                        <input
                            type="file"
                            name="lampiran1"
                            class="form-control"
                            accept=".pdf">
                    </div>

                </div>

                <!-- BUTTON -->
                <div class="button-group">

                    <button type="submit" class="btn-submit">
                        <i class="fas fa-save"></i>
                        Rai Alterasaun
                    </button>

                    <a href="daftar_dokumen.php" class="btn-back">
                        <i class="fas fa-times-circle"></i>
                        Kansela
                    </a>

                </div>

            </form>

        </div>

    </div>

</div>

<script>
flatpickr("#tgl_terima", {
    locale: "pt",
    altInput: true,
    altFormat: "d/F/Y",
    dateFormat: "Y-m-d"
});
</script>

</body>
</html>