<?php
include "asset/session_check.php";

$nama_pegawai = $_SESSION['nama_pegawai'];
$akses = $_SESSION['akses'];
?>
<!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>Data Penawaran Service</h1>
                </div>
                <div class="p-2 bd-highlight" style="align-items: center;display: flex;">
                    <!-- <a class="tmbdata" href="penawaranbisman-tambah.php">Tambah Data</a> -->
                    <!-- <button type="button" class="btn btn-primary tmbdatap" data-bs-toggle="modal" data-bs-target="#exampleModal">
                        Tambah Data
                    </button> -->
                    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="exampleModalLabel">Pilih Kota</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <center>
                                        <a class="tmbdata" href="asset/autoid-penawaranbisman.php?kota=tanggerang">Tanggerang</a>
                                        <a class="tmbdata" href="asset/autoid-penawaranbisman.php?kota=surabaya">Surabaya</a>
                                    </center>
                                </div>
                                <!-- <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                    <button type="button" class="btn btn-primary">Save changes</button>
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <form method="GET" class="row mb-3">
                <div class="col-md-2">
                    <input type="text" class="form-control" name="nofiles" placeholder="Nofile" value="<?= htmlspecialchars($_GET['nofile'] ?? '') ?>">
                </div>
                <div class="col-md-2">
                    <input type="text" class="form-control" name="namcus" placeholder="Nama Customer" value="<?= htmlspecialchars($_GET['namcus'] ?? '') ?>">
                </div>
                <div class="col-md-2">
                    <select name="status" class="form-select">
                        <option value="">-- Semua Status --</option>
                        <option value="Belum" <?= ($_GET['status'] ?? '') == 'Belum' ? 'selected' : '' ?>>Belum</option>
                        <option value="Sudah" <?= ($_GET['status'] ?? '') == 'Sudah' ? 'selected' : '' ?>>Sudah</option>
                    </select>
                </div>

                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary">Filter</button>
                </div>
            </form>
            <table class="table">
                <thead>
                    <?php
                    include 'koneksi.php';
                    //FILTER
                    $nofileFilter = $_GET['nofiles'] ?? '';
                    $customerFilter = $_GET['namcus'] ?? '';
                    $statusFilter   = $_GET['status'] ?? '';

                    $whereArray = [];

                    // Filter Status
                    if (!empty($statusFilter)) {
                        $whereArray[] = "COALESCE(rv.status_checkbismanps, r.status_checkbismanps) = '$statusFilter'";
                    }

                    // Filter Nama Nofile
                    if (!empty($nofileFilter)) {
                        $whereArray[] = "COALESCE(rv.nofile_revisi_bismanps, r.nofile_bismanps) LIKE '%$nofileFilter%'";
                    }

                    if (!empty($customerFilter)) {

                            $input = trim($customerFilter);
                            $input = str_replace('.', '', $input);

                            $pisah = explode(" ", $input);

                            $daftar_bu = ['PT', 'CV', 'UD', 'Toko', 'Bapak', 'Ibu'];

                            if (in_array(strtoupper($pisah[0]), $daftar_bu)) {

                                $bu = strtoupper($pisah[0]);
                                $nama = implode(" ", array_slice($pisah, 1));

                                $bu   = mysqli_real_escape_string($konek, $bu);
                                $nama = mysqli_real_escape_string($konek, $nama);

                                $whereArray[] = "(c.bu = '$bu' AND c.nama_customer LIKE '%$nama%')";
                            } else {

                                $input = mysqli_real_escape_string($konek, $input);

                                $whereArray[] = "c.nama_customer LIKE '%$input%'";
                            }
                        }

                    // Filter Nama Customer
                    // if (!empty($customerFilter)) {
                    //     $whereArray[] = "c.nama_customer LIKE '%$customerFilter%'";
                    // }

                    // Gabungkan kondisi
                    $where = "";
                    if (!empty($whereArray)) {
                        $where = "WHERE " . implode(" AND ", $whereArray);
                    }

                    /* SORTING */
                    $sortColumn = $_GET['sort'] ?? 'tgl_bismanps_bru';
                    $sortOrder  = $_GET['order'] ?? 'DESC';

                    $allowedColumns = [
                        'nofile',
                        'tgl_bismanps_bru',
                        'nama_customer',
                        'status_checkbismanps',
                        'tgl_checkbismanps'
                    ];

                    if (!in_array($sortColumn, $allowedColumns)) {
                        $sortColumn = 'tgl_bismanps_bru';
                    }

                    $sortOrder = strtoupper($sortOrder) === 'ASC' ? 'ASC' : 'DESC';

                    // ORDER BY khusus
                    if ($sortColumn === 'tgl_checkbismanps') {
                        $orderBy = "
                        ORDER BY
                            CASE 
                                WHEN COALESCE(rv.status_checkbismanps, r.status_checkbismanps) = 'Sudah' THEN 0
                                ELSE 1
                            END,
                            COALESCE(rv.tgl_checkbismanps, r.tgl_checkbismanps) $sortOrder
                        ";
                    } elseif ($sortColumn === 'status_checkbismanps') {
                        $orderBy = "ORDER BY status_checkbismanps $sortOrder, tgl_checkbismanps DESC";
                    } else {
                        $orderBy = "ORDER BY $sortColumn $sortOrder";
                    }
                    ?>
                    <tr style="text-align: center;">
                        <th>
                            <a style="text-decoration: none;color: black;" href="?hal=1&sort=nofile&order=<?= ($sortColumn == 'nofile' && $sortOrder == 'DESC') ? 'ASC' : 'DESC' ?>&status=<?= $statusFilter ?>&namcus=<?= $customerFilter ?>">
                                No File
                                <?php if ($sortColumn == 'nofile'): ?>
                                    <i class="bi <?= $sortOrder == 'ASC'
                                                        ? 'bi-caret-up-fill'
                                                        : 'bi-caret-down-fill' ?>"></i>
                                <?php endif; ?>
                            </a>
                        </th>
                        <th>
                            <a style="text-decoration: none;color: black;" href="?hal=1&sort=tgl_bismanps_bru&order=<?= ($sortColumn == 'tgl_bismanps_bru' && $sortOrder == 'DESC') ? 'ASC' : 'DESC' ?>&status=<?= $statusFilter ?>&namcus=<?= $customerFilter ?>">
                                Tanggal Penawaran
                                <?php if ($sortColumn == 'tgl_bismanps_bru'): ?>
                                    <i class="bi <?= $sortOrder == 'ASC'
                                                        ? 'bi-caret-up-fill'
                                                        : 'bi-caret-down-fill' ?>"></i>
                                <?php endif; ?>
                            </a>
                        </th>
                        <th>
                            <a style="text-decoration: none;color: black;" href="?hal=1&sort=nama_customer&order=<?= ($sortColumn == 'nama_customer' && $sortOrder == 'DESC') ? 'ASC' : 'DESC' ?>&status=<?= $statusFilter ?>&namcus=<?= $customerFilter ?>">
                                Nama Customer
                                <?php if ($sortColumn == 'nama_customer'): ?>
                                    <i class="bi <?= $sortOrder == 'ASC'
                                                        ? 'bi-caret-up-fill'
                                                        : 'bi-caret-down-fill' ?>"></i>
                                <?php endif; ?>
                            </a>
                        </th>
                        <th>
                            <a style="text-decoration: none;color: black;"
                                href="?hal=1&sort=status_checkbismanps&order=<?= ($sortColumn == 'status_checkbismanps' && $sortOrder == 'DESC') ? 'ASC' : 'DESC' ?>&status=<?= $statusFilter ?>&namcus=<?= $customerFilter ?>">
                                Status Check
                                <?php if ($sortColumn == 'status_checkbismanps'): ?>
                                    <i class="bi <?= $sortOrder == 'ASC'
                                                        ? 'bi-caret-up-fill'
                                                        : 'bi-caret-down-fill' ?>"></i>
                                <?php endif; ?>
                            </a>
                        </th>
                        <th>
                            <a style="text-decoration: none;color: black;"
                                href="?hal=1&sort=tgl_checkbismanps&order=<?= ($sortColumn == 'tgl_checkbismanps' && $sortOrder == 'DESC') ? 'ASC' : 'DESC' ?>&status=<?= $statusFilter ?>&namcus=<?= $customerFilter ?>&nofiles=<?= $nofileFilter ?>">
                                Tanggal Check
                                <?php if ($sortColumn == 'tgl_checkbismanps'): ?>
                                    <i class="bi <?= $sortOrder == 'ASC'
                                                        ? 'bi-caret-up-fill'
                                                        : 'bi-caret-down-fill' ?>"></i>
                                <?php endif; ?>
                            </a>
                        </th>
                        <th>Checker</th>
                        <th>Action</th>

                    </tr>
                </thead>
                <tbody>
                    <?php
                    include "koneksi.php";
                    $no = 1;

                    // PAGINATION
                    $batas = 5; // jumlah data per halaman
                    $halaman = isset($_GET['hal']) ? (int)$_GET['hal'] : 1;

                    if ($halaman < 1) {
                        $halaman = 1;
                    }

                    $offset = ($halaman - 1) * $batas;

                    // Hitung total data
                    $totalQuery = "SELECT COUNT(*) as total FROM bisman_ps";
                    $totalResult = mysqli_query($konek, $totalQuery);
                    $totalData = mysqli_fetch_assoc($totalResult)['total'];

                    $totalHalaman = ceil($totalData / $batas);
                    $kodequery = "SELECT 
                        r.idbismanps,
                        r.nofile_bismanps,
                        rv.nofile_revisi_bismanps,
                        r.tgl_bismanps,
                        rv.idrevisi_bismanps,

                        COALESCE(rv.nofile_revisi_bismanps, r.nofile_bismanps) AS nofile,
                        COALESCE(rv.tgl_bismanps, r.tgl_bismanps) AS tgl_bismanps_bru,
                        COALESCE(rv.idpegawai, r.idpegawai) AS idpegawai,
                        COALESCE(rv.status_checkbismanps, r.status_checkbismanps) AS status_checkbismanps,
                        COALESCE(rv.tgl_checkbismanps, r.tgl_checkbismanps) AS tgl_checkbismanps,
                        COALESCE(rv.checker, r.checker) AS checker,

                        c.nama_customer,
                        c.bu

                    FROM bisman_ps r

                    LEFT JOIN (
                        SELECT rv1.*
                        FROM revisi_bisman_ps rv1
                        INNER JOIN (
                            SELECT idbismanps, MAX(idrevisi_bismanps) AS max_id
                            FROM revisi_bisman_ps
                            GROUP BY idbismanps
                        ) rv2 
                            ON rv1.idbismanps = rv2.idbismanps 
                            AND rv1.idrevisi_bismanps = rv2.max_id
                    ) rv 
                        ON rv.idbismanps = r.idbismanps

                    LEFT JOIN customer c 
                        ON c.idcustomer = COALESCE(rv.idcustomer, r.idcustomer)

                    $where

                    $orderBy
                    LIMIT $offset, $batas
                    ";
                    $sql = mysqli_query($konek, "$kodequery");
                    while ($row = mysqli_fetch_array($sql)) {
                    ?>
                        <tr style="text-align: center;">
                            <td><?php echo $row['nofile'] ?></td>
                            <td><?php echo date('d F Y', strtotime($row['tgl_bismanps_bru'])) ?></td>
                            <td><?php echo $row['bu'] . " " . $row['nama_customer'] ?></td>
                            <td><?php echo $row['status_checkbismanps'] ?></td>
                            <td>
                                <?php
                                if ($row['status_checkbismanps'] == "Belum") {
                                    echo "-";
                                } else {
                                    echo date('d F Y', strtotime($row['tgl_checkbismanps']));
                                }
                                ?>
                            </td>
                            <td><?php echo substr($row['checker'] ?? '-', 0, 2) ?></td>
                            <td>
                                <div class="d-flex flex-column flex-md-row gap-1 justify-content-center">
                                    <!-- <a href="" class="btn btn-primary btn-sm">+</a> -->
                                    <?php

                                    $nofile = $row['nofile'];

                                    if (preg_match('/\.\d+\.\d+$/', $nofile)) {
                                    ?>
                                        <a href="function/function-penawaranbisman.php?revisike&nofile=<?php echo $row['nofile'] ?>" class="btn btn-secondary btn-sm" title="REVISI"><i class="bi bi-wrench-adjustable"></i></a>
                                        <!-- <a href="penawaranbisman-tambah.php?nofile=<?php echo $row['nofile'] ?>" class="btn btn-warning btn-sm" title="EDIT"><i class="bi bi-pencil-fill"></i></a> -->
                                        <button
                                            class="btn btn-primary btn-sm"
                                            title="VIEW"
                                            data-bs-toggle="modal"
                                            data-bs-target="#views<?= $row['idrevisi_bismanps']; ?>">
                                            <i class="bi bi-eye-fill"></i>
                                        </button>
                                        <button
                                            class="btn btn-print btn-sm"
                                            title="PRINT"
                                            data-bs-toggle="modal"
                                            data-bs-target="#prints<?= $row['idrevisi_bismanps']; ?>">
                                            <i class="bi bi-printer-fill"></i>
                                        </button>
                                        <!-- <a href="print-bismanps-revisi.php?nofile=<?php echo $row['nofile'] ?>" target="_blank" class="btn btn-sm btn-print" title="PRINT"><i class="bi bi-printer-fill"></i></a> -->
                                    <?php
                                        include "asset/modal-view-revisibismanps.php";
                                    } else {
                                    ?>
                                        <a href="function/function-penawaranbisman.php?revisi&nofile=<?php echo $row['nofile'] ?>" class="btn btn-secondary btn-sm" title="REVISI"><i class="bi bi-wrench-adjustable"></i></a>
                                        <!-- <a href="penawaranbisman-revisi.php?nofile=<?php echo $row['nofile'] ?>" class="btn btn-warning btn-sm" title="EDIT"><i class="bi bi-pencil-fill"></i></a> -->
                                        <button
                                            class="btn btn-primary btn-sm"
                                            title="VIEW"
                                            data-bs-toggle="modal"
                                            data-bs-target="#viewe<?= $row['idbismanps']; ?>">
                                            <i class="bi bi-eye-fill"></i>
                                        </button>
                                        <button
                                            class="btn btn-print btn-sm"
                                            title="PRINT"
                                            data-bs-toggle="modal"
                                            data-bs-target="#printe<?= $row['idbismanps']; ?>">
                                            <i class="bi bi-printer-fill"></i>
                                        </button>
                                        <!-- <a href="print-bismanps.php?nofile=<?php echo $row['nofile'] ?>" target="_blank" class="btn btn-sm btn-print" title="PRINT"><i class="bi bi-printer-fill"></i></a> -->
                                    <?php
                                        include "asset/modal-view-bismanps.php";
                                    }
                                    ?>
                                </div>
                            </td>
                        </tr>
                    <?php
                        $no++;
                    }
                    ?>
                </tbody>
            </table>
            <nav>
                <ul class="pagination justify-content-center">

                    <!-- Tombol Previous -->
                    <li class="page-item <?php if ($halaman <= 1) echo 'disabled'; ?>">
                        <a class="page-link"
                            href="?hal=<?= $halaman - 1 ?>&sort=<?= $sortColumn ?>&order=<?= $sortOrder ?>&status=<?= $statusFilter ?>">
                            Previous
                        </a>
                    </li>

                    <?php for ($i = 1; $i <= $totalHalaman; $i++) : ?>
                        <li class="page-item <?php if ($i == $halaman) echo 'active'; ?>">
                            <a class="page-link" href="?hal=<?= $i ?>&sort=<?= $sortColumn ?>&order=<?= $sortOrder ?>&status=<?= $statusFilter ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                    <?php endfor; ?>

                    <!-- Tombol Next -->
                    <li class="page-item <?php if ($halaman >= $totalHalaman) echo 'disabled'; ?>">
                        <a class="page-link"
                            href="?hal=<?= $halaman + 1 ?>&sort=<?= $sortColumn ?>&order=<?= $sortOrder ?>&status=<?= $statusFilter ?>">
                            Next
                        </a>
                    </li>

                </ul>
            </nav>
        </div>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.default_keteranganbisman').forEach(function(master) {
                master.addEventListener('change', function() {
                    const modal = this.closest('.modal'); // ambil modal terdekat
                    const isChecked = this.checked;
                    modal.querySelectorAll('.catatan').forEach(function(cb) {
                        cb.checked = isChecked;
                    });
                });
            });
        });
    </script>
    <!-- INI FOOTER -->
    <?php
    include "asset/footer.php";
    ?>
</body>

</html>