<?php
// Bagian Logika & koneksi 
session_start();

include 'koneksi.php';

// Proteksi Halaman
if (!isset($_SESSION['status']) || $_SESSION['status'] != "login") {
    header("Location: login.php");
    exit();
}
function formatNPWP($npwp) {
    // 1. Bersihkan dari karakter non-angka
    $npwp = preg_replace("/[^0-9]/", "", $npwp);
    
    // 2. Jika kosong, kembalikan string kosong
    if (empty($npwp)) return "-";

    // 3. Terapkan masking bertahap berdasarkan panjang karakter
    $len = strlen($npwp);
    if ($len == 16) {
        return preg_replace("/(\d{2})(\d{3})(\d{3})(\d{1})(\d{3})(\d{3})/", "$1.$2.$3.$4-$5.$6", $npwp);
    } elseif ($len > 12) {
        return substr($npwp, 0, 2) . "." . substr($npwp, 2, 3) . "." . substr($npwp, 5, 3) . "." . substr($npwp, 8, 1) . "-" . substr($npwp, 9, 3) . "." . substr($npwp, 12);
    } elseif ($len > 9) {
        return substr($npwp, 0, 2) . "." . substr($npwp, 2, 3) . "." . substr($npwp, 5, 3) . "." . substr($npwp, 8, 1) . "-" . substr($npwp, 9);
    } elseif ($len > 8) {
        return substr($npwp, 0, 2) . "." . substr($npwp, 2, 3) . "." . substr($npwp, 5, 3) . "." . substr($npwp, 8);
    } elseif ($len > 5) {
        return substr($npwp, 0, 2) . "." . substr($npwp, 2, 3) . "." . substr($npwp, 5);
    } elseif ($len > 2) {
        return substr($npwp, 0, 2) . "." . substr($npwp, 2);
    }
    
    return $npwp;
}

// Inisialisasi Data Profil (Fallback jika tabel profil kosong)
$nama_pt = "BEST PROCUREMENT";
$alamat_pt = "Alamat belum diatur di menu Profil";
$logo_pt = "assets/logosys.png";

$check_table = mysqli_query($koneksi, "SHOW TABLES LIKE 'profil_perusahaan'");
if ($check_table && mysqli_num_rows($check_table) > 0) {
    $query_profil = mysqli_query($koneksi, "SELECT * FROM profil_perusahaan LIMIT 1");
    if ($query_profil && mysqli_num_rows($query_profil) > 0) {
        $profil = mysqli_fetch_array($query_profil);
        $nama_pt = $profil['nama_perusahaan'];
        $alamat_pt = $profil['alamat'];
        $logo_pt = (!empty($profil['logo'])) ? $profil['logo'] : "assets/logosys.png";
    }
}
?>
<!--Bagian Head & CSS -->
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Supplier - <?php echo $nama_pt; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        :root {
            --bg-sidebar: linear-gradient(180deg, #e60000 0%, #000000 100%);
            --accent-red: #dc3545;
            --text-gray: #b0b0b0;
        }

        body { margin: 0; font-family: 'Inter', sans-serif; display: flex; background-color: #f4f7f6; height: 100vh; overflow: hidden; }
        
        /* Layout */
        aside { width: 260px; background: var(--bg-sidebar); color: white; display: flex; flex-direction: column; flex-shrink: 0; }
        main { flex-grow: 1; display: flex; flex-direction: column; overflow-y: auto; }
        
        /* Sidebar Components */
        .brand { padding: 30px 25px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .brand img { max-width: 200px; height: auto; }
        .nav-category { padding: 20px 25px 5px; font-size: 11px; color: rgba(255,255,255,0.5); text-transform: uppercase; font-weight: bold; letter-spacing: 1px; }
        .nav-item { padding: 12px 25px; display: flex; align-items: center; gap: 15px; text-decoration: none; color: var(--text-gray); font-size: 14px; transition: 0.3s; border-left: 4px solid transparent; }
        .nav-item:hover, .nav-item.active { background: rgba(255,255,255,0.1); color: white; border-left: 4px solid white; }
        
        /* Content Components */
        header { background: white; padding: 15px 30px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
        .content-body { padding: 25px; }
        .card { background: white; padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        
        table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        th { background: #f8f9fa; padding: 15px; text-align: left; font-size: 13px; color: #666; border-bottom: 2px solid #eee; }
        td { padding: 15px; border-bottom: 1px solid #eee; font-size: 14px; }

        /* Modal */
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 1000; align-items: center; justify-content: center; backdrop-filter: blur(4px); }
        .modal-content { background: white; padding: 30px; border-radius: 12px; width: 800px; max-height: 90vh; overflow-y: auto; position: relative; }
        .form-control { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; margin-top: 5px; }
        
        /* PO Specific */
        .po-header { display: flex; justify-content: space-between; border-bottom: 2px solid #333; padding-bottom: 15px; margin-bottom: 20px; }
        .po-table th { background: #333; color: white; }

        /* CSS untuk Tabel PO Minimalis */
        /* KUNCI TAMPILAN TABEL PO */
        .po-table {
            width: 100%;
            border-collapse: collapse !important;
            border: none !important;
            margin-top: 15px;
        }

        .po-table thead th {
            background-color: #333 !important;
            color: white !important;
            padding: 12px 10px !important;
            font-size: 13px;
            text-align: center;
            border: none !important;
        }

        .po-table td {
            padding: 12px 10px;
            border: none !important;
            border-bottom: 1px solid #eee !important;
            text-align: center;
            vertical-align: middle;
        }

        .po-table .form-control {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 6px;
            text-align: center;
        }
    </style>
</head>
<!--Bagian Body Sidebar & Content -->
<body>
    <aside>
        <div class="brand"><img src="assets/logosys.png" alt="Logo"></div>
        <div class="nav-category">Menu Utama</div>
        <a href="dashboard.php" class="nav-item"><i class="fa-solid fa-gauge"></i> Dashboard</a>
        <a href="supplier.php" class="nav-item active"><i class="fa-solid fa-truck-field"></i> Supplier</a>
        <div class="nav-category">Laporan</div>
        <a href="daftar_po.php" class="nav-item"><i class="fa-solid fa-file-invoice"></i> Daftar PO</a>
        <div class="logout-area" style="margin-top:auto; padding-bottom:20px;">
            <a href="logout.php" class="nav-item" style="color:#ff5252;"><i class="fa-solid fa-power-off"></i> Logout</a>
        </div>
    </aside>

    <main>
        <header>
            <div style="font-weight: 600;">Data Master Supplier</div>
            <div><i class="fa-regular fa-user"></i> <strong><?php echo $_SESSION['username']; ?></strong></div>
        </header>

        <div class="content-body">
            <?php
            if (isset($_SESSION['pesan_sukses'])) {
                echo '<div style="width: 100%; box-sizing: border-box; background: #d4edda; color: #155724; padding: 12px 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #c3e6cb; font-size: 14px; display: block;">
                        <i class="fa-solid fa-check-circle"></i> ' . $_SESSION['pesan_sukses'] . '
                    </div>';
                unset($_SESSION['pesan_sukses']);
            }
            ?>
            <div class="card">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <h3 style="margin: 0;">Daftar Supplier</h3>
                    <button onclick="openAddModal()" style="background: var(--accent-red); color: white; padding: 10px 20px; border: none; border-radius: 6px; cursor: pointer; font-weight: bold;">
                        <i class="fa-solid fa-plus"></i> Tambah Supplier
                    </button>
                </div>

                <table>
                    <thead>
                        <tr>
                        <th>Nama Supplier</th>
                        <th>Alamat Lengkap</th>
                        <th>PIC & Kontak</th>
                        <th>Status</th> <th style="text-align: center;">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $query = mysqli_query($koneksi, "SELECT * FROM supplier ORDER BY id DESC");
                        while ($d = mysqli_fetch_array($query)) {
                            $data_json = htmlspecialchars(json_encode($d), ENT_QUOTES, 'UTF-8');
                        ?>
                        <tr>
                            <td><strong style="color:var(--accent-red);"><?php echo $d['nama_supplier']; ?></strong></td>
                            <td><?php echo $d['alamat']; ?></td>
                            <td>
                            <strong><?php echo $d['pic']; ?></strong><br>
                            <small><?php echo $d['telp']; ?></small><br>
                            <small style="color: blue;">
                                NPWP: <?php echo formatNPWP($d['npwp']); ?>
                            </small>
                            </td>
                            <td>
                            <?php if($d['status'] == 'Aktif'): ?>
                                <span style="background: #e8f5e9; color: #2e7d32; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">Aktif</span>
                            <?php else: ?>
                                <span style="background: #ffebee; color: #c62828; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">Non-Aktif</span>
                            <?php endif; ?>
                            </td>
                            <td style="text-align: center;"> 
                            <!--... tombol aksi ...--> 
                                <button onclick='openOrderModal(<?php echo $data_json; ?>)' title="Rilis PO" style="color:green; border:none; background:none; cursor:pointer; font-size:18px;"><i class="fa-solid fa-file-invoice-dollar"></i></button>
                                <button onclick='openEditModal(<?php echo $data_json; ?>)' style="color:blue; border:none; background:none; cursor:pointer; font-size:18px; margin: 0 10px;"><i class="fa-solid fa-pen-to-square"></i></button>
                                <a href="hapus_supplier.php?id=<?php echo $d['id']; ?>" onclick="return confirm('Hapus supplier?')"><i class="fa-solid fa-trash" style="color:red; font-size:16px;"></i></a>
                            </td>
                            </td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
    <!--Bagian Modal-->
    <div id="orderModal" class="modal-overlay" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; align-items:center; justify-content:center;">
        <div class="modal-content">
            <div class="po-header">
                <div>
                    <img src="<?php echo $logo_pt; ?>" style="max-height:50px;"><br>
                    </div>
        <div class="info-pt">
            <strong><?php echo $profil['nama_perusahaan'] ?? "PT. BERDUA SEJAHTERA TEKNIK"; ?></strong><br>
            <?php echo $profil['alamat'] ?? "Alamat belum diatur"; ?><br>
            Email: <?php echo $profil['email'] ?? "-"; ?> | Telp: <?php echo $profil['telp'] ?? "-"; ?>
        </div>
                <div style="text-align:right;">
                    <h2 style="margin:0; color:var(--accent-red);">PURCHASE ORDER</h2>
                    <small>No: PO-<?php echo date('Ymd-His'); ?></small>
                </div>
            </div>

            <form action="proses_rilis_order.php" method="POST">
                <input type="hidden" name="id_supplier" id="po_supplier_id">
                <input type="hidden" name="no_po" value="PO-<?php echo date('Ymd-His'); ?>">
                <input type="hidden" name="subtotal" id="hidden_subtotal">
                <input type="hidden" name="diskon" id="hidden_diskon" value="0">
                <input type="hidden" name="ppn" id="hidden_ppn">
                <input type="hidden" name="total" id="hidden_total">
                
                <div class="vendor-info" style="margin-bottom: 20px; padding: 10px; background: #f9f9f9; border-radius: 8px;">
                    <small style="color: #666; text-transform: uppercase; font-weight: bold; font-size: 11px;">VENDOR:</small>
                    <div style="font-weight:bold; color: #dc3545; font-size: 18px; margin-bottom: 5px;" id="po_nama_supplier"></div>
                    <div style="font-size: 14px; color: #333; line-height: 1.5;">
                        <span id="disp_supp_addr"></span><br>
                        <span style="font-weight: bold;">PIC: </span><span id="disp_supp_pic"></span> | 
                        <span style="font-weight: bold;">Telp: </span><span id="disp_supp_telp"></span><br>
                        <span id="disp_supp_npwp"></span>
                    </div>
                </div>

                <table class="po-table">
                    <thead>
                        <tr>
                            <th>Item Description</th>
                            <th style="width:80px;">Qty</th>
                            <th style="width:150px;">Harga (Rp)</th>
                            <th style="width:150px;">Total (Rp)</th>
                            <th style="width:40px;"></th>
                        </tr>
                    </thead>
                    <tbody id="po_item_list"></tbody>
                </table>
                <button type="button" onclick="addPOItem()" style="margin-top:10px; cursor:pointer; background:none; border:1px solid #ccc; padding:5px 10px; border-radius:4px;">+ Tambah Item</button>

                <div style="margin-top:20px; display: flex; justify-content: flex-end;">
                <div style="width: 320px; border-top: 2px solid #333; padding-top: 10px;">
                <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                <span>Subtotal</span>
                <strong>Rp <span id="txt_subtotal">0</span></strong>
                </div>
        
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
                <span>Diskon (Rp)</span>
                <input type="number" id="input_diskon" name="diskon" value="0" oninput="calculatePO()" 
                   style="width: 120px; text-align: right; border: 1px solid #ddd; border-radius: 4px; padding: 3px;">
                </div>

                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                <span>PPN (11%)</span>
                <strong>Rp <span id="txt_ppn">0</span></strong>
                </div>

        <div style="display: flex; justify-content: space-between; font-size: 20px; color: #dc3545; border-top: 1px solid #eee; padding-top: 10px;">
            <strong>TOTAL</strong>
            <strong>Rp <span id="txt_grandtotal">0</span></strong>
        </div>
    </div>
</div>

                <div style="margin-top:20px; text-align:right;">
                    <button type="button" onclick="closeModal('orderModal')" style="padding:10px 20px; border:1px solid #ddd; background:none; border-radius:8px; cursor:pointer;">Batal</button>
                    <button type="submit" style="padding:10px 20px; background:#2e7d32; color:white; border:none; border-radius:8px; cursor:pointer; margin-left:10px;">Rilis Sekarang</button>
                </div>
            </form>
        </div>
    </div>

    <div id="supplierModal" class="modal-overlay" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; align-items:center; justify-content:center;">
    <div class="modal-content" style="background:white; padding:25px; border-radius:12px; width:500px; max-width:90%;">
        <h3 id="modalTitle" style="margin-top:0;">Tambah Supplier Baru</h3>
        
        <form action="proses_tambah_supplier.php" method="POST" id="supplierForm">
            <input type="hidden" name="id" id="form_id">

            <div style="margin-bottom:12px;">
                <label>Nama Perusahaan</label>
                <input type="text" name="nama" id="form_nama" class="form-control" required>
            </div>

            <div style="margin-bottom:12px;">
                <label>Alamat</label>
                <textarea name="alamat" id="form_alamat" class="form-control" rows="3" required></textarea>
            </div>

            <div style="display:flex; gap:10px; margin-bottom:12px;">
                <div style="flex:1;"><label>PIC</label><input type="text" name="pic" id="form_pic" class="form-control" required></div>
                <div style="flex:1;"><label>Telp</label><input type="text" name="telp" id="form_telp" class="form-control" required></div>
            </div>

            <div style="margin-bottom:12px;">
                <input type="text" name="npwp" id="form_npwp" class="form-control" 
                placeholder="00.000.000.0-000.000" 
                maxlength="20" 
                oninput="maskNPWP(this)">
            </div>

            <div style="margin-bottom:15px;">
                <label>Status Supplier</label>
                <select name="status" id="form_status" class="form-control" required>
                    <option value="Aktif">Aktif</option>
                    <option value="Non-Aktif">Non-Aktif</option>
                </select>
            </div>

            <div style="text-align:right; margin-top:20px;">
                <button type="button" onclick="closeModal()" style="padding: 8px 15px; background: #ccc; border: none; border-radius: 5px; cursor: pointer;">Batal</button>
                <button type="submit" style="padding:8px 15px; border:none; background:#d9534f; color:white; border-radius:5px; cursor:pointer;">Simpan Data</button>
            </div>
        </form>
    </div>
</div>
<!--Bagian Modal-->

<!--Bagian Javascript-->
    <script>
    // 1. MODAL MANAGEMENT
    function openAddModal() {
        document.getElementById('modalTitle').innerText = 'Tambah Supplier Baru';
        document.getElementById('supplierForm').action = 'proses_tambah_supplier.php';
        document.getElementById('supplierForm').reset();
        document.getElementById('form_id').value = '';
        document.getElementById('form_status').value = 'Aktif';
        document.getElementById('supplierModal').style.display = 'flex';
    }

    function openEditModal(data) {
        document.getElementById('modalTitle').innerText = 'Edit Data Supplier';
        document.getElementById('supplierForm').action = 'proses_update_supplier.php';
        document.getElementById('form_id').value = data.id;
        document.getElementById('form_nama').value = data.nama_supplier;
        document.getElementById('form_alamat').value = data.alamat;
        document.getElementById('form_pic').value = data.pic;
        document.getElementById('form_telp').value = data.telp;
        document.getElementById('form_npwp').value = data.npwp;
        document.getElementById('form_status').value = data.status;
        document.getElementById('supplierModal').style.display = 'flex';

        let npwpInput = document.getElementById('form_npwp');
    npwpInput.value = data.npwp; 
    
    // Panggil fungsi masking agar saat data masuk, langsung terformat
    maskNPWP(npwpInput);
    }

    function openOrderModal(data) {
        document.getElementById('po_supplier_id').value = data.id;
        document.getElementById('po_nama_supplier').innerText = data.nama_supplier;
        document.getElementById('disp_supp_addr').innerText = data.alamat;
        document.getElementById('disp_supp_pic').innerText = data.pic;
        document.getElementById('disp_supp_telp').innerText = data.telp;
        
        let npwpRaw = data.npwp.replace(/\D/g, '');
        let npwpFormatted = npwpRaw.replace(/(\d{2})(\d{3})(\d{3})(\d{1})(\d{3})(\d{3})/, '$1.$2.$3.$4-$5.$6');
        document.getElementById('disp_supp_npwp').innerHTML = `<span style="color:blue; font-weight:500;">NPWP: ${npwpFormatted}</span>`;
        
        document.getElementById('po_item_list').innerHTML = ""; 
        addPOItem(); 
        document.getElementById('orderModal').style.display = 'flex';
    }

    function closeModal(idModal) {
        if (idModal) {
            document.getElementById(idModal).style.display = 'none';
        } else {
            document.getElementById('supplierModal').style.display = 'none';
        }
    }

    // 2. PO CALCULATION
    function addPOItem() {
        const html = `<tr>
            <td><input type="text" name="item[]" class="form-control" required placeholder="Deskripsi Barang"></td>
            <td><input type="number" name="qty[]" class="form-control qty" value="1" min="1" oninput="calculatePO()"></td>
            <td><input type="number" name="price[]" class="form-control price" required placeholder="0" oninput="calculatePO()"></td>
            <td style="font-weight: bold; vertical-align: middle;">Rp <span class="line-total">0</span></td>
            <td style="vertical-align: middle;">
                <button type="button" onclick="this.parentElement.parentElement.remove(); calculatePO();" style="color:#dc3545; border:none; background:none; cursor:pointer;"><i class="fa-solid fa-trash"></i></button>
            </td>
        </tr>`;
        document.getElementById('po_item_list').insertAdjacentHTML('beforeend', html);
    }

    function calculatePO() {
        let subtotal = 0;
        const rows = document.querySelectorAll('#po_item_list tr');
        rows.forEach(row => {
            const qty = parseFloat(row.querySelector('.qty').value) || 0;
            const price = parseFloat(row.querySelector('.price').value) || 0;
            const lineTotal = qty * price;
            row.querySelector('.line-total').innerText = lineTotal.toLocaleString('id-ID');
            subtotal += lineTotal;
        });

        const diskon = parseFloat(document.getElementById('input_diskon').value) || 0;
        const dpp = subtotal - diskon;
        const ppn = dpp * 0.11;
        const grandTotal = dpp + ppn;

        document.getElementById('txt_subtotal').innerText = subtotal.toLocaleString('id-ID');
        document.getElementById('txt_ppn').innerText = ppn.toLocaleString('id-ID');
        document.getElementById('txt_grandtotal').innerText = grandTotal.toLocaleString('id-ID');

        document.getElementById('hidden_subtotal').value = subtotal;
        document.getElementById('hidden_ppn').value = ppn;
        document.getElementById('hidden_total').value = grandTotal;
    }

    // 3. GLOBAL CLICK EVENT (Diletakkan di luar fungsi, di bagian bawah script)
    window.onclick = function(event) {
        let supplierModal = document.getElementById('supplierModal');
        let orderModal = document.getElementById('orderModal');
        if (event.target == supplierModal) {
            closeModal('supplierModal');
        }
        if (event.target == orderModal) {
            closeModal('orderModal');
        }
    };

    function maskNPWP(input) {
    // 1. Ambil nilai dan hapus semua karakter non-angka
    let val = input.value.replace(/\D/g, '');
    
    // 2. Batasi maksimal 16 digit angka
    if (val.length > 16) {
        val = val.substring(0, 16);
    }

    // 3. Terapkan masking format: 00.000.000.0-000.000
    let formatted = val;
    if (val.length > 12) {
        formatted = val.replace(/(\d{2})(\d{3})(\d{3})(\d{1})(\d{3})(\d{3})/, '$1.$2.$3.$4-$5.$6');
    } else if (val.length > 9) {
        formatted = val.replace(/(\d{2})(\d{3})(\d{3})(\d{1})(\d{3})/, '$1.$2.$3.$4-$5');
    } else if (val.length > 8) {
        formatted = val.replace(/(\d{2})(\d{3})(\d{3})(\d{1})/, '$1.$2.$3.$4');
    } else if (val.length > 5) {
        formatted = val.replace(/(\d{2})(\d{3})(\d{3})/, '$1.$2.$3');
    } else if (val.length > 2) {
        formatted = val.replace(/(\d{2})(\d{3})/, '$1.$2');
    }

    // 4. Update nilai input dengan format baru
    input.value = formatted;
}
</script>
</body>
</html>