<?php
include "asset/session_check.php";
$nama_pegawai = $_SESSION['nama_pegawai'];
$akses = $_SESSION['akses'];
include 'koneksi.php';
?>
<!doctype html>
<html lang="en">

<head>
    <?php
    include "asset/head.php";
    ?>
</head>

<body>
    <!-- NAVIGASI -->
    <?php
    include "asset/navigasi.php";
    ?>
    <div class="container">
        <div class="row">
            <div class="d-flex bd-highlight mb-3">
                <div class="me-auto p-2 bd-highlight">
                    <h1>Form Tambah Data Penawaran bisman</h1>
                </div>
            </div>
        </div>
        <?php
        $nofile = $_GET["nofile"];
        if (isset($_GET["idtelp_custbisman"])) {
            $idtelp_custbisman = $_GET['idtelp_custbisman'];
            $crps = mysqli_query($konek, "SELECT c.idcustomer,c.nama_customer,c.alamat,c.telp,c.email,c.bu,p.telp_pic,p.nama_pic
                                                    FROM telp_custbisman t INNER JOIN customer c 
                                                    ON t.idcustomer=c.idcustomer INNER JOIN pic p ON p.idcustomer = c.idcustomer WHERE idtelp_custbisman='$idtelp_custbisman'");
        } else {
            $crps = mysqli_query($konek, "SELECT r.idbismanps,r.keterangan_status,p.nama_pic,p.telp_pic,c.idcustomer,c.nama_customer,c.alamat,c.telp,c.email,c.bu,r.status_checkbismanps,r.tgl_checkbismanps,r.checker 
                                                    FROM bisman_ps r INNER JOIN customer c
                                                    ON r.idcustomer=c.idcustomer INNER JOIN pic p ON p.idcustomer = c.idcustomer WHERE nofile_bismanps='$nofile'");
        }
        $datap = mysqli_fetch_array($crps);
        $idcustomer = $datap["idcustomer"] ?? '';
        $nama_customer = $datap["nama_customer"] ?? '';
        $alamat = $datap["alamat"] ?? '';
        $pic = $datap["nama_pic"] ?? '';
        preg_match('/^\w+/', $pic, $hasil);
        $depan = strtolower($hasil[0]);
        $pic = preg_replace('/\b(Bapak|Ibu)\b\s*/i', '', $pic);
        $pice = trim($pic);
        $telp = $datap["telp"] ?? '';
        $telppic = $datap["telp_pic"] ?? '';
        $email = $datap["email"] ?? '';
        $bu = $datap["bu"] ?? '';
        $status_checkbismanps = $datap["status_checkbismanps"] ?? '';
        $keterangan_status = $datap["keterangan_status"] ?? '';
        $tgl_checkbismanps = $datap["tgl_checkbismanps"] ?? '';
        $checker = $datap["checker"] ?? '';
        ?>
        <form action="function/function-penawaranbisman.php?nofile=<?php echo $nofile ?>" method="post">
            <div class="row">
                <div class="col">
                    <div class="mb-3">
                        <label class="form-label">No File</label>
                        <input type="text" class="form-control" name="nofile" value="<?php echo $nofile ?>">
                        <input type="text" class="form-control idcust" id="idcust" name="idcustomer"
                            value="<?= $idcustomer ?? '' ?>" hidden>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Customers</label>
                        <div class="input-group">
                            <select class="form-select" name="bu" id="bu" style="max-width: 70px;">
                                <option value="PT " <?= (strtoupper(trim($bu)) == 'PT ') ? 'selected' : '' ?>>PT</option>
                                <option value="CV " <?= (strtoupper(trim($bu)) == 'CV ') ? 'selected' : '' ?>>CV</option>
                                <option value="UD " <?= (strtoupper(trim($bu)) == 'UD ') ? 'selected' : '' ?>>UD</option>
                                <option value="TOKO " <?= (strtoupper(trim($bu)) == 'Toko ') ? 'selected' : '' ?>>TOKO
                                </option>
                                <option value="Bapak" <?= (strtoupper(trim($bu)) == 'BAPAK') ? 'selected' : '' ?>>Bapak
                                </option>
                                <option value="Ibu " <?= (strtoupper(trim($bu)) == 'Ibu ') ? 'selected' : '' ?>>Ibu
                                </option>
                            </select>
                            <input type="text" class="form-control" autocomplete="off" name="nama_customer"
                                id="nama_customer" value="<?= $nama_customer ?? '' ?>"
                                placeholder="Masukkan Nama Customer">
                        </div>
                        <div id="customerList" class="list-group w-100" style="z-index:1000; display:none;"></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Alamat</label>
                        <input type="text" class="form-control" id="alamat" name="alamat" value="<?= $alamat ?? '' ?>"
                            placeholder="Masukkan Alamat">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="text" class="form-control" id="email" name="email" value="<?= $email ?? '' ?>"
                            placeholder="Masukkan Email">
                    </div>
                </div>
                <div class="col">
                    <div class="mb-3">
                        <?php
                        $tgl = date("d M Y");
                        ?>
                        <label class="form-label">Tanggal</label>
                        <input type="text" class="form-control" name="tglps" value="<?php echo $tgl ?>">
                    </div>
                    <!-- <div class="mb-3">
                        <label class="form-label">PIC</label>
                        <input type="text" class="form-control pic" id="pic" name="pic" value="<?= $pic ?? '' ?>" placeholder="Masukkan Nama PIC">
                    </div> -->
                    <div class="mb-3">
                        <label class="form-label">PIC</label>
                        <div class="input-group">
                            <select class="form-select" name="tt" id="tt" style="max-width: 95px;">
                                <option value="Bapak" <?= ($depan == 'bapak') ? 'selected' : '' ?>>Bapak</option>
                                <option value="Ibu" <?= ($depan == 'ibu') ? 'selected' : '' ?>>Ibu</option>
                            </select>
                            <input type="text" class="form-control idcustomer" autocomplete="off" name="idcustomer"
                                id="idcustomer" value="<?= $idcustomer ?>" hidden>
                            <input type="text" class="form-control pic" autocomplete="off" name="pic" id="pice"
                                value="<?= $pic ?>" placeholder="Masukkan Nama PIC">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Telp PIC</label>
                        <input type="text" class="form-control" id="telp" name="telp" value="<?= $telppic ?? '' ?>"
                            placeholder="Masukkan Telpone">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status Check</label>
                        <div class="input-group">
                            <select class="form-select" name="check" id="status">
                                <option value="Belum" <?= ($status_checkbismanps == 'Belum') ? 'selected' : '' ?>>Belum
                                </option>
                                <option value="Sudah" <?= ($status_checkbismanps == 'Sudah') ? 'selected' : '' ?>>Sudah
                                </option>
                            </select>
                            <div id="formketstatus" style="display:none; margin-left:10px;">
                                <select class="form-select" name="ketstatus" id="ketstatus">
                                    <option value="Belum di ambil" <?= ($keterangan_status == 'Belum di ambil') ? 'selected' : '' ?>>Belum di ambil</option>
                                    <option value="Sudah di ambil" <?= ($keterangan_status == 'Sudah di ambil') ? 'selected' : '' ?>>Sudah di ambil</option>
                                </select>
                            </div>
                            <div id="formTambahan" style="display:none; margin-left:10px;">
                                <input type="text" name="checker" class="form-control" placeholder="Nama checker"
                                    value="<?= $checker ?>">
                            </div>
                            <div id="formTanggal" style="display:none; margin-left:10px;">
                                <input type="date" name="tgl_check" class="form-control"
                                    value="<?= $tgl_checkbismanps ?>">
                            </div>
                        </div>
                    </div>
                </div>
                <button type="submit" class="btn btnfunc" name="tambah">Tambah Unit</button>
            </div>
        </form>
        <hr>
        <div class="row">
            <table class="table table-hover">
                <thead>
                    <tr style="text-align: center;">
                        <th scope="col">No</th>
                        <th scope="col">Uraian</th>
                        <th scope="col">QTY</th>
                        <th scope="col">Keterangan</th>
                        <th scope="col">Harga Satuan</th>
                        <th scope="col">Harga</th>
                        <th scope="col">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $cridrps = mysqli_query($konek, "select idbismanps from bisman_ps where nofile_bismanps='$nofile'");
                    $cridrps = mysqli_fetch_array($cridrps);
                    $idbismanps = $cridrps["idbismanps"] ?? "";

                    $no = 1;
                    $sql = mysqli_query($konek, "SELECT d.iddetail_bismanps,u.nama_unit,d.no_unit,d.wo_unit FROM detail_bismanps d INNER JOIN unit u ON d.idunit=u.idunit WHERE idbismanps='$idbismanps'");
                    while ($row = mysqli_fetch_array($sql)) {
                        // echo $ddr = $row['iddetail_bismanps'];
                        // $cridrpsd = mysqli_query($konek, "select iddetail_bismanps from detail_bismanps where idbismanps='$idbismanps'");
                        // $cridrpsd = mysqli_fetch_assoc($cridrpsd);
                        // $iddbismanps = $cridrpsd["iddetail_bismanps"] ?? "";
                        $iddbismanps = $row['iddetail_bismanps'];
                        $querygabung = mysqli_query(
                            $konek,
                            "SELECT s.jenis_service AS keterangan,j.harga_servicebisman AS harga,j.qty_service AS kuota,j.totalservice_bisman AS total,j.keterangan AS kete FROM uraianbismanps_service j INNER JOIN jenis_service s ON j.idjenis_service=s.idjenis_service WHERE j.iddetail_bismanps = '$iddbismanps'
                        UNION ALL
                        SELECT b.nama_barang AS keterangan,ub.harga_barangbisman AS harga,ub.qty AS kuota,ub.totalbarang_bisman AS total,ub.keterangan AS kete FROM uraianbismanps_barang ub INNER JOIN barang b ON ub.idbarang=b.idbarang WHERE ub.iddetail_bismanps = '$iddbismanps'
                        "
                        );
                        $rows = mysqli_num_rows($querygabung);

                        if ($rows == 0) {
                            ?>
                            <tr style="text-align:center;">
                                <th><?php echo $no; ?></th>
                                <th>
                                    <?php
                                    echo $row['nama_unit'];
                                    echo "<br>";
                                    echo !empty($row['no_unit']) ? " ({$row['no_unit']})" : "";
                                    echo "<br>";
                                    echo !empty($row['wo_unit']) ? " ({$row['wo_unit']})" : "";
                                    ?>
                                </th>
                                <td>-</td>
                                <td><i>Belum ada uraian</i></td>
                                <td>-</td>
                                <td>-</td>
                                <td>
                                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal"
                                        data-bs-target="#tmbs<?= $row['iddetail_bismanps']; ?>">
                                        + Service
                                    </button>
                                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal"
                                        data-bs-target="#tmbb<?= $row['iddetail_bismanps']; ?>">
                                        + Sparepart
                                    </button>
                                </td>
                                <!-- modal service -->
                                <?php include 'asset/modal-servicebisman.php'; ?>
                                <!-- modal barang -->
                                <?php include 'asset/modal-barangbisman.php'; ?>
                            </tr>
                            <?php
                            $no++;
                            continue; // lanjut ke unit berikutnya
                        }

                        // if ($rows == 0) continue;
                        $noe = 0;
                        while ($d = mysqli_fetch_array($querygabung)) {
                            ?>
                            <tr style="text-align: center;">
                                <?php
                                if ($noe == 0) {
                                    ?>
                                    <th rowspan="<?php echo $rows + 3 ?>"><?php echo $no; ?></th>
                                    <th rowspan="<?php echo $rows + 3 ?>">
                                        <?php
                                        echo $row['nama_unit'];
                                        echo "<br>";
                                        echo !empty($row['no_unit']) ? " ({$row['no_unit']})" : "";
                                        echo "<br>";
                                        echo !empty($row['wo_unit']) ? " ({$row['wo_unit']})" : "";

                                        ?>
                                    </th>
                                    <?php
                                }
                                ?>
                                <td><?php echo $d['kuota'] ?></td>
                                <td style="text-align: left;">
                                    <div style="text-align:center; font-weight:600;">
                                        <?= htmlspecialchars($d['keterangan']) ?>
                                    </div>
                                    <?php if (!empty($d['kete'])): ?>
                                        <div style="text-align:left; margin-top:6px; line-height:1.5;">
                                            <?= nl2br(htmlspecialchars($d['kete'])) ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td><span style="text-align: left;">Rp
                                    </span><?php echo number_format($d['harga'], 0, ',', '.') ?></td>
                                <td><span style="text-align: left;">Rp
                                    </span><?php echo number_format($d['total'], 0, ',', '.') ?></td>
                                <!-- button edit -->
                                 <td>
                                    <?php
                                    $namak = $d['keterangan'];
                                    $carinama = mysqli_query($konek, "SELECT * FROM jenis_service WHERE jenis_service='$namak'");
                                    $datanama = mysqli_num_rows($carinama);
                                    $databisman = mysqli_fetch_assoc($carinama);
                                    $iddetail_bismanps = $row["iddetail_bismanps"];
                                    // $namae = $datanama['jenis_service'];
                            
                                    if ($datanama > 0) {
                                        $idjenis = $databisman['idjenis_service'];
                                        $caribisman = mysqli_query($konek, "SELECT idbismanps_service 
                                            FROM uraianbismanps_service 
                                            WHERE idjenis_service = '$idjenis' AND iddetail_bismanps = '$iddetail_bismanps'
                                        ");

                                        $databisman = mysqli_fetch_assoc($caribisman);
                                        $idbismanps_service = $databisman['idbismanps_service'];
                                        ?>
                                        <button class="btn btn-sm btn-warning" data-bs-toggle="modal"
                                            data-bs-target="#edts<?= $idbismanps_service ?>">   
                                            <i class="bi bi-pencil-fill"></i>
                                        </button>
                                        <a href="function/function-penawaranbisman.php?hpssere&iddetail=<?= $idbismanps_service ?>&nofile=<?= $nofile ?>"
                                            class="btn btn-sm btn-danger"><i class="bi bi-trash3"></i></a>
                                        <!-- modal service -->
                                        <?php include 'asset/modal-edittambahb-service.php'; ?>
                                        <?php
                                    } else {
                                        $namak = $d['keterangan'];
                                        $carinama = mysqli_query($konek, "SELECT * FROM barang WHERE nama_barang='$namak'");
                                        $datanama = mysqli_num_rows($carinama);
                                        $databisman = mysqli_fetch_assoc($carinama);
                                        $iddetail_bismanps = $row["iddetail_bismanps"];

                                        $idjenis = $databisman['idbarang'];
                                        $caribisman = mysqli_query($konek, "SELECT idbismanps_barang 
                                            FROM uraianbismanps_barang 
                                            WHERE idbarang = '$idjenis' AND iddetail_bismanps = '$iddetail_bismanps'
                                        ");

                                        $databisman = mysqli_fetch_assoc($caribisman);
                                        $idbismanps_barang = $databisman['idbismanps_barang'];
                                        ?>
                                        <button class="btn btn-sm btn-warning" data-bs-toggle="modal"
                                            data-bs-target="#edtb<?= $idbismanps_barang ?>">
                                            <i class="bi bi-pencil-fill"></i>
                                        </button>
                                        <a href="function/function-penawaranbisman.php?hpsbare&iddetail=<?= $idbismanps_barang ?>&nofile=<?= $nofile ?>"
                                            class="btn btn-sm btn-danger"><i class="bi bi-trash3"></i></a>
                                        <!-- modal service -->
                                        <?php include 'asset/modal-edittambahb-barang.php'; ?>
                                        <?php
                                    }
                                    ?>
                                </td>
                                <?php
                                if ($noe == 0) {
                                    ?>
                                    <td rowspan="<?php echo $rows + 3 ?>">
                                        <button class="btn btn-primary btn-sm" data-bs-toggle="modal"
                                            data-bs-target="#tmbs<?= $row['iddetail_bismanps']; ?>">
                                            + Service
                                        </button>
                                        <button class="btn btn-primary btn-sm" data-bs-toggle="modal"
                                            data-bs-target="#tmbb<?= $row['iddetail_bismanps']; ?>">
                                            + Sparepart
                                        </button>
                                    </td>
                                    <?php
                                }
                                ?>
                                <!-- modal service -->
                                <?php include 'asset/modal-servicebisman.php'; ?>
                                <!-- modal barang -->
                                <?php include 'asset/modal-barangbisman.php'; ?>
                            </tr>
                            <?php
                            $noe++;
                        }
                        $query_total = mysqli_query($konek, "
                            SELECT SUM(total) AS grand_total
                            FROM (
                                SELECT totalservice_bisman AS total
                                FROM uraianbismanps_service
                                WHERE iddetail_bismanps = '$iddbismanps'

                                UNION ALL

                                SELECT totalbarang_bisman AS total
                                FROM uraianbismanps_barang
                                WHERE iddetail_bismanps = '$iddbismanps'
                            ) AS total_all
                        ");

                        $total = mysqli_fetch_assoc($query_total);
                        ?>
                        <tr style="text-align: center;">
                            <td colspan="3" style="font-weight: 700;">Subtotal</td>
                            <th><?php echo $tuotal = $total['grand_total'] ?></th>
                        </tr>
                        <tr style="text-align: center;">
                            <td colspan="3" style="font-weight: 700;">PPN 11%</td>
                            <th><?php echo $ppn = $total['grand_total'] * 0.11 ?></th>
                        </tr>
                        <tr style="text-align: center;">
                            <td colspan="3" style="font-weight: 700;">TOTAL</td>
                            <th><?php echo $kabeh = $ppn + $tuotal ?></th>
                        </tr>
                        <?php
                        $no++;
                    }
                    ?>
                </tbody>
            </table>
        </div>
        <a href="penawaran-servicebisman.php" class="btn btnfunct">Simpan dan Selesai</a>
    </div>
    <?php
    $modal = $_GET['modal'] ?? '';
    ?>
    <!-- Modal Unit-->
    <div class="modal fade" id="ModalTmb" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Tambah Data Unit</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="function/function-penawaranbisman.php?nofile=<?php echo $nofile ?>" method="post">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">UNIT</label>
                            <input type="text" class="form-control unit" id="unit" autocomplete="off" name="unit"
                                placeholder="Masukkan unit">
                        </div>
                        <div id="unitList" class="list-group unitList w-100" style=" display:none;"></div>
                        <div class="mb-3">
                            <label class="form-label">No/Warna/Unit</label>
                            <input type="text" class="form-control" id="nounit" autocomplete="off" name="nounit"
                                placeholder="Masukkan No Unit">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">No Wo</label>
                            <input type="text" class="form-control" id="wo" autocomplete="off" name="wo"
                                placeholder="Masukkan No WO">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn" name="tmbunit"
                            style="background-color: #1E93AB;color: white;">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Uraian -->
    <div class="modal fade" id="ModalUraian" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">

                <div class="modal-header">
                    <h5 class="modal-title">Tambah Uraian Service</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">
                    <div class="mb-2">
                        <label>Uraian</label>
                        <input type="text" class="form-control" id="uraian">
                    </div>

                    <div class="mb-2">
                        <label>Qty</label>
                        <input type="number" class="form-control" id="qty" value="1">
                    </div>

                    <div class="mb-2">
                        <label>Harga</label>
                        <input type="number" class="form-control" id="harga">
                    </div>
                </div>

                <div class="modal-footer">
                    <button class="btn btn-primary" id="simpanUraian">Simpan Uraian</button>
                </div>

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


    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <?php if ($modal === 'ModalTmb'): ?>
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const modal = new bootstrap.Modal(
                    document.getElementById('ModalTmb')
                );
                modal.show();
            });
        </script>
    <?php endif; ?>

    <!-- customer -->
    <script src="asset/js/auto_cust.js"></script>
    <!-- pic -->
    <script src="asset/js/auto_pic.js"></script>
    <!-- unit -->
    <script src="asset/js/auto_unit.js"></script>

    <!-- Service -->
    <script src="asset/js/auto_service.js"></script>

    <!-- Service 1 -->
    <!-- <script src="asset/js/auto_service1.js"></script> -->

    <!-- Sparepart -->
    <script src="asset/js/auto_barang.js"></script>

    <script>
        function toggleChecker() {
            let nilai = document.getElementById('status').value;
            let form = document.getElementById('formTambahan');
            let formk = document.getElementById('formketstatus');
            let formt = document.getElementById('formTanggal');

            if (nilai === 'Sudah') {
                form.style.display = 'block';
                formt.style.display = 'block';
                formk.style.display = 'block';
            } else {
                form.style.display = 'none';
                formk.style.display = 'none';
                formt.style.display = 'none';
            }
        }

        // saat select berubah
        document.getElementById('status').addEventListener('change', toggleChecker);

        // saat halaman pertama kali dibuka
        document.addEventListener('DOMContentLoaded', toggleChecker);
    </script>
    <script>
        var rupiah = document.getElementById("rupiah");
        document.addEventListener("DOMContentLoaded", function () {
            document.querySelectorAll(".rupiah").forEach(function (input) {
                input.addEventListener("keyup", function () {
                    this.value = formatRupiah(this.value);
                });
            });
        });

        /* Fungsi formatRupiah */
        function formatRupiah(angka, prefix) {
            var number_string = angka.replace(/[^,\d]/g, "").toString(),
                split = number_string.split(","),
                sisa = split[0].length % 3,
                rupiah = split[0].substr(0, sisa),
                ribuan = split[0].substr(sisa).match(/\d{3}/gi);

            // tambahkan titik jika yang di input sudah menjadi angka ribuan
            if (ribuan) {
                separator = sisa ? "." : "";
                rupiah += separator + ribuan.join(".");
            }

            rupiah = split[1] != undefined ? rupiah + "," + split[1] : rupiah;
            return prefix == undefined ? rupiah : rupiah ? "Rp. " + rupiah : "";
        }
    </script>
    <script>
        var rupiah = document.getElementById("rupiahb");
        document.addEventListener("DOMContentLoaded", function () {
            document.querySelectorAll(".rupiah").forEach(function (input) {
                input.addEventListener("keyup", function () {
                    this.value = formatRupiah(this.value);
                });
            });
        });

        /* Fungsi formatRupiah */
        function formatRupiah(angka, prefix) {
            var number_string = angka.replace(/[^,\d]/g, "").toString(),
                split = number_string.split(","),
                sisa = split[0].length % 3,
                rupiah = split[0].substr(0, sisa),
                ribuan = split[0].substr(sisa).match(/\d{3}/gi);

            // tambahkan titik jika yang di input sudah menjadi angka ribuan
            if (ribuan) {
                separator = sisa ? "." : "";
                rupiah += separator + ribuan.join(".");
            }

            rupiah = split[1] != undefined ? rupiah + "," + split[1] : rupiah;
            return prefix == undefined ? rupiah : rupiah ? "Rp. " + rupiah : "";
        }
    </script>

    <!-- INI FOOTER -->
    <?php
    include "asset/footer.php";
    ?>

</body>

</html>