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

// Report error untuk memudahkan debugging
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// 1. FUNGSI WHATSAPP
function kirimWA($no, $pesan) {
    $token = "hbXfbV6ZbY4yVW5rsonS";
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.fonnte.com/send",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => array('target' => $no, 'message' => $pesan),
        CURLOPT_HTTPHEADER => array("Authorization: $token"),
    ));
    curl_exec($curl);
    curl_close($curl);
}

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

$id_user   = $_SESSION['id_user'];
$full_name = $_SESSION['full_name'] ?? 'Admin';

// 3. PROSES UPLOAD & INSERT
if (isset($_POST['upload'])) {
    $upload_dir = "../assets/uploads/";
    if (!is_dir($upload_dir)) { mkdir($upload_dir, 0777, true); }

    $error = null;
    $file_nota = $_FILES['file_nota'];
    
    // Validasi Ekstensi File Utama
    $ext_utama = strtolower(pathinfo($file_nota['name'], PATHINFO_EXTENSION));
    if ($ext_utama !== 'pdf') {
        $error = "Sala! Dokumentu prinsipál tenke PDF.";
    } else {
        // Validasi Ekstensi Lampiran (1-5)
        $lampiran_names = [null, null, null, null, null, null]; // Index 1-5
        for ($i = 1; $i <= 5; $i++) {
            if (!empty($_FILES["lampiran$i"]['name'])) {
                $ext_lamp = strtolower(pathinfo($_FILES["lampiran$i"]['name'], PATHINFO_EXTENSION));
                if ($ext_lamp !== 'pdf') {
                    $error = "Sala! Anexo numeru $i tenke formatu PDF.";
                    break;
                }
            }
        }

        if (!$error) {
            // Upload File Utama
            $nama_file = time() . "_" . preg_replace('/[^A-Za-z0-9.\-_]/', '_', $file_nota['name']);
            if (move_uploaded_file($file_nota['tmp_name'], $upload_dir . $nama_file)) {
                
                // Upload Lampiran
                for ($i = 1; $i <= 5; $i++) {
                    if (isset($_FILES["lampiran$i"]) && $_FILES["lampiran$i"]['error'] == 0) {
                        $l_name = time() . "_lamp_" . $i . "_" . preg_replace('/[^A-Za-z0-9.\-_]/', '_', $_FILES["lampiran$i"]['name']);
                        if (move_uploaded_file($_FILES["lampiran$i"]['tmp_name'], $upload_dir . $l_name)) {
                            $lampiran_names[$i] = $l_name;
                        }
                    }
                }

                // Ambil Data Form
                $tgl_terima  = $_POST['tgl_terima'];
                $nomor_prt   = $_POST['nomor_prt'];
                $descripsi   = $_POST['descripsi'];
                $direksi     = $_POST['direksi'];
                $jumlah      = $_POST['total_adiantamento'];
                $status      = "didaftarkan";
                $tipe_dokumen = "Pagamento"; 

                // Simpan ke Database
                $stmt = $koneksi->prepare("
                    INSERT INTO jv_documents (
                        file_nota, lampiran1, lampiran2, lampiran3, lampiran4, lampiran5,
                        tgl_terima, nomor_prt, descripsi, direksi, total_adiantamento,
                        status, uploaded_by_id, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
                ");

                $stmt->bind_param(
                    "ssssssssssssi",
                    $nama_file, $lampiran_names[1], $lampiran_names[2], $lampiran_names[3], 
                    $lampiran_names[4], $lampiran_names[5], $tgl_terima, $nomor_prt, 
                    $descripsi, $direksi, $jumlah, $status, $id_user
                );

                if ($stmt->execute()) {
                    // Kirim WA
                    $pesanWA = "📢 *DOKUMENTU FFM*\n👤 User: $full_name\n📄 Tipo: $tipe_dokumen\n🔢 No: $nomor_prt\n💰 Montante: $jumlah\n✅ Status: Didaftarkan";
                    kirimWA("085641811940", $pesanWA);
                    
                    header("Location: " . $_SERVER['PHP_SELF'] . "?status=success");
                    exit;
                } else {
                    $error = "Database Error: " . $stmt->error;
                }
            } else {
                $error = "Gagal mengunggah file utama.";
            }
        }
    }
}
?>
<!-- Notifikasi Error (Sudah Ada) -->
            <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    <h5><i class="icon fas fa-ban"></i> Erru!</h5>
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <!-- TAMBAHKAN INI: Notifikasi Sukses -->
            <?php if (isset($_GET['status']) && $_GET['status'] == 'success'): ?>
    <div class="alert alert-success alert-dismissible" style="position: relative; padding: 25px;">
        
        <!-- Wadah Tombol di Pojok Kanan Atas dengan Flexbox -->
        <div style="position: absolute; top: 15px; right: 15px; display: flex; gap: 10px;">
            <!-- Tombol Ke Daftar (Ukuran Besar & Proporsional) -->
            <a href="daftar_dokumen.php" class="btn" style="background-color: #1b4d3e; color: white; border: none; padding: 10px 20px; font-weight: 600; border-radius: 5px; display: flex; align-items: center;">
                <i class="fas fa-list" style="margin-right: 8px;"></i> Lista Dokumentu
            </a>
            
            <!-- Tombol Close (Ukuran Besar & Proporsional) -->
            <button type="button" class="btn" data-dismiss="alert" style="background-color: #1b4d3e; color: white; border: none; padding: 10px 20px; font-weight: 600; border-radius: 5px;">
                Close
            </button>
        </div>
        
        <!-- Konten Alert -->
        <div style="padding-right: 280px;"> <!-- Menjaga teks agar tidak tertabrak tombol -->
            <h4 style="font-weight: bold;"><i class="icon fas fa-check"></i> Susesu!</h4>
            <p style="font-size: 1.1rem; margin-bottom: 0;">Dokumentu rejista ona ho susesu iha sistema.</p>
        </div>
        
    </div>
<?php endif; ?>

<?php include "../header.php"; ?>

<style>
    :root {
        --finance-green: #0b5d3b;
        --finance-dark: #1a3a5f;
    }

    .content-wrapper { background: #f4f6f9; }
    
    /* Progress Stepper style decoration */
    .card-finance {
        border-top: 5px solid var(--finance-green);
        border-radius: 8px;
    }
/* Sembunyikan headernya secara permanen khusus di halaman ini */
.main-header {
    display: none !important;
}
/* Sembunyikan sidebar secara permanen khusus di halaman ini */
.main-sidebar {
    display: none !important;
}
/* PAKSA KONTEN UNTUK FULL WIDTH */
    .content-wrapper { 
        margin-left: 0 !important;
        padding-top: 20px;
        background: #f4f6f9; 
        min-height: 100vh !important;
    }
    .form-section-title {
        font-size: 1rem;
        font-weight: 700;
        color: var(--finance-dark);
        text-transform: uppercase;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid #e9ecef;
        display: flex;
        align-items: center;
    }

    .form-section-title i {
        margin-right: 10px;
        color: var(--finance-green);
    }

    .label-finance {
        font-weight: 600;
        color: #495057;
        font-size: 0.9rem;
    }

    .input-finance:focus {
        border-color: var(--finance-green);
        box-shadow: 0 0 0 0.2rem rgba(11, 93, 59, 0.15);
    }

    /* File Upload Box Custom */
    .custom-file-upload {
        border: 2px dashed #ced4da;
        padding: 20px;
        text-align: center;
        border-radius: 8px;
        background: #fdfdfd;
        transition: 0.3s;
    }

    .custom-file-upload:hover {
        border-color: var(--finance-green);
        background: #f0f7f2;
    }

    .btn-finance-submit {
        background-color: var(--finance-green);
        border-color: var(--finance-green);
        padding: 12px 30px;
        font-weight: 600;
        transition: 0.3s;
    }

    .btn-finance-submit:hover {
        background-color: #084a2f;
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
	/* Mengatur agar teks di dalam dropdown Select2 bisa pindah baris */
.select2-container--default .select2-selection--single .select2-selection__rendered {
    white-space: normal;
    word-wrap: break-word;
    line-height: 1.2;
    padding: 8px 0;
}

.select2-container .select2-selection--single {
    height: auto !important;
    min-height: 38px;
}

/* Mengatur agar pilihan di dalam list dropdown juga pindah baris */
.select2-results__option {
    white-space: normal;
    word-wrap: break-word;
}
</style>

<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2 align-items-center">
                <div class="col-sm-6">
                    <h1 class="m-0 font-weight-bold" style="color: var(--finance-dark);">
                        <i class="fas fa-file-invoice-dollar mr-2"></i>Rejistu Dokumentu Pagamento
                    </h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item active">Upload</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <div class="content">
        <div class="container-fluid">
            
            <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    <h5><i class="icon fas fa-ban"></i> Erru!</h5>
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">
                <div class="row">
                    
                    <!-- SISI KIRI: DATA DOKUMEN -->
                    <div class="col-md-8">
                        <div class="card card-finance shadow-sm">
                            <div class="card-body">
                                <div class="form-section-title">
                                    <i class="fas fa-info-circle"></i> Informasaun Dokumentu
                                </div>
                                
                                <div class="row">
                                   
                                    <div class="col-md-6">
                                        <!-- 1. Pastikan CSS Flatpickr sudah ada di atas -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

<!-- Tambahkan sedikit CSS untuk mencegah flicker -->
<style>
    /* Mencegah input terlihat sebelum JS siap */
    #datePicker:not(.flatpickr-input) {
        color: transparent;
    }
</style>

<!-- 2. Pastikan JS Flatpickr sudah dimuat -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/pt.js"></script>

                                    </div>
                                </div>

                                <!-- ================= ROW 1 ================= -->
<div class="row">
    
    <!-- KIRI -->
    <div class="col-md-6">
        <div class="form-group">
    <label class="label-finance">
        Data Simu Pedido <span class="text-danger">*</span>
    </label>
    <input type="text" 
           id="datePicker" 
           name="tgl_terima" 
           class="form-control input-finance" 
           placeholder="Hili data..." 
           readonly="readonly"
           required>
</div>
    </div>

    <!-- KANAN -->
    <div class="col-md-6">
        <div class="form-group">
            <label class="label-finance">
                Numeru Pedido <span class="text-danger">*</span>
            </label>

            <input type="text"
                   name="nomor_prt"
                   class="form-control input-finance"
                   placeholder="Ex: 001/DNPFO/2026"
                   required>
        </div>
    </div>

</div>

<!-- ================= ROW 2 ================= -->
<div class="row">

    <!-- KIRI -->
    <div class="col-md-6">
        <div class="form-group">
            <label class="label-finance">
                Montante (USD) <span class="text-danger">*</span>
            </label>

            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text bg-light font-weight-bold">
                        $
                    </span>
                </div>

                <input type="text"
                       id="total_adiantamento_view"
                       class="form-control input-finance text-right font-weight-bold"
                       placeholder="0.00"
                       autocomplete="off"
                       required>

                <input type="hidden"
                       name="total_adiantamento"
                       id="total_adiantamento">
            </div>
        </div>
    </div>

    <!-- KANAN -->
    <div class="col-md-6">
        <div class="form-group">
            <label class="label-finance">
                Divizaun <span class="text-danger">*</span>
            </label>

            <select name="direksi"
                    class="form-control select2"
                    required>

                <option value="">-- Hili Divizaun --</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>
    </div>

</div>

                                <div class="form-group">
                                    <label class="label-finance">Deskrisaun / Justifikasaun <span class="text-danger">*</span></label>
                                    <textarea name="descripsi" class="form-control input-finance" rows="3" placeholder="Escreve deskrisaun badak..." required></textarea>
                                </div>

                                

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

                    <!-- SISI KANAN: UPLOAD FILE -->
                    <div class="col-md-4">
                        <!-- Card User Info -->
                        <div class="card shadow-sm mb-4">
                            <div class="card-body p-3">
                                <div class="d-flex align-items-center">
                                    <div class="bg-success p-3 rounded-circle mr-3">
                                        <i class="fas fa-user-tie text-white"></i>
                                    </div>
                                    <div>
                                        <small class="text-muted d-block">Utilizador</small>
                                        <span class="font-weight-bold text-dark"><?= htmlspecialchars($full_name) ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Card File Upload -->
                        <div class="card shadow-sm">
                            <div class="card-body">
                                <div class="form-section-title">
                                    <i class="fas fa-cloud-upload-alt"></i> Arkivu PDF
                                </div>

                                <div class="form-group">
    <label class="label-finance">Dokumentu Prinsipál (PDF) <span class="text-danger">*</span></label>
    <div class="custom-file-upload">
        <i class="fas fa-file-pdf fa-3x text-danger mb-2"></i>
        <!-- Tambahkan id untuk validasi JS -->
        <input type="file" id="file_nota" name="file_nota" class="form-control-file check-pdf" accept=".pdf" required>
        <small class="text-muted d-block mt-2">Upload scan nota/karta prinsipál (Tenke PDF)</small>
    </div>
</div>

<div class="form-group mt-4">
    <label class="label-finance">Anexo / Lampiran (Opsiunál)</label>
    <div class="input-group mb-2">
        <div class="input-group-prepend">
            <span class="input-group-text"><i class="fas fa-paperclip"></i></span>
        </div>
        <!-- Tambahkan accept=".pdf" agar user hanya melihat file PDF saat memilih -->
        <input type="file" name="lampiran1" class="form-control form-control-sm check-pdf" accept=".pdf">
    </div>
    <small class="text-muted">Dokumentu suporta mós tenke PDF.</small>
</div>


                                <hr>

                                <button type="submit" name="upload" class="btn btn-finance-submit btn-block text-white shadow-sm">
                                    <i class="fas fa-check-circle mr-2"></i> SUBMETE AGORA
                                </button>
                               <a href="/arsip-pagamento/dashboard.php"  
   class="btn btn-danger btn-block text-white font-weight-bold">
   <i class="fas fa-times-circle mr-1"></i> Kansela
</a>
                            </div>
                        </div>
                    </div>

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

<!-- JS Script tetap sama seperti logika sebelumnya -->
<script>
   const inputView = document.getElementById('total_adiantamento_view');
const inputReal = document.getElementById('total_adiantamento');

function formatUSD(value) {
    return new Intl.NumberFormat('en-US', {
        
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(value);
}

function cleanNumber(value) {
    return value.replace(/[^0-9.-]/g, '');
}

inputView.addEventListener('blur', function(){
    let raw = cleanNumber(this.value);
    if (raw !== '' && !isNaN(raw)) {
        inputReal.value = parseFloat(raw).toFixed(2);
        this.value = formatUSD(raw);
    }
});

inputView.addEventListener('keydown', function(e){
    if (e.key === 'Enter') {
        e.preventDefault();
        this.blur();
    }
});
</script>
<!-- Load Library -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/pt.js"></script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        flatpickr("#datePicker", {
            locale: "pt", // Bahasa Portugis
            altInput: true,
            // altFormat: "d/m/Y" -> 14/05/2026
            // altFormat: "d/F/Y" -> 14/Maio/2026
            altFormat: "d/F/Y", 
            dateFormat: "Y-m-d", // Tetap Y-m-d agar sinkron dengan MySQL
            altInputClass: "form-control input-finance",
            allowInput: false,
            disableMobile: "true" // Memaksa library tampil di HP bukan picker bawaan
        });
    });
</script>
<script defer src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script defer src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/pt.js"></script>
<?php include "../footer.php"; ?>