<?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="penawaranraxi-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-penawaranraxi.php?kota=tangerang">Tanggerang</a>
                                        <a class="tmbdata" href="asset/autoid-penawaranraxi.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 g-2 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-1 d-grid">
                    <button type="submit" class="btn btn-primary">Filter</button>
                </div>
                <div class="col-md-1 d-grid">
                    <a href="penawaran-serviceraxi.php" class="btn btn-secondary">Reset</a>
                </div>
            </form>
            <div class="table-responsive">
                <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_checkraxips, r.status_checkraxips) = '$statusFilter'";
                        }

                        // Filter Nama Nofile
                        if (!empty($nofileFilter)) {
                            $whereArray[] = "COALESCE(rv.nofile_revisi_raxips, r.nofile_raxips) 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'] ?? 'idraxips';
                        $sortOrder  = $_GET['order'] ?? 'DESC';

                        $allowedColumns = [
                            'idraxips',
                            'nofile',
                            'tgl_raxips_bru',
                            'nama_customer',
                            'status_checkraxips',
                            'tgl_checkraxips'
                        ];

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

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

                        // ORDER BY khusus
                        if ($sortColumn === 'tgl_checkraxips') {
                            $orderBy = "
                        ORDER BY
                            CASE 
                                WHEN COALESCE(rv.status_checkraxips, r.status_checkraxips) = 'Sudah' THEN 0
                                ELSE 1
                            END,
                            COALESCE(rv.tgl_checkraxips, r.tgl_checkraxips) $sortOrder
                        ";
                        } elseif ($sortColumn === 'status_checkraxips') {
                            $orderBy = "ORDER BY status_checkraxips $sortOrder, tgl_checkraxips DESC";
                        } else {
                            if ($sortColumn === 'idraxips') {
                                $orderBy = "ORDER BY r.idraxips $sortOrder";
                            } 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_raxips_bru&order=<?= ($sortColumn == 'tgl_raxips_bru' && $sortOrder == 'DESC') ? 'ASC' : 'DESC' ?>&status=<?= $statusFilter ?>&namcus=<?= $customerFilter ?>">
                                    Tanggal Penawaran
                                    <?php if ($sortColumn == 'tgl_raxips_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_checkraxips&order=<?= ($sortColumn == 'status_checkraxips' && $sortOrder == 'DESC') ? 'ASC' : 'DESC' ?>&status=<?= $statusFilter ?>&namcus=<?= $customerFilter ?>">
                                    Status Check
                                    <?php if ($sortColumn == 'status_checkraxips'): ?>
                                        <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_checkraxips&order=<?= ($sortColumn == 'tgl_checkraxips' && $sortOrder == 'DESC') ? 'ASC' : 'DESC' ?>&status=<?= $statusFilter ?>&namcus=<?= $customerFilter ?>&nofiles=<?= $nofileFilter ?>">
                                    Tanggal Check
                                    <?php if ($sortColumn == 'tgl_checkraxips'): ?>
                                        <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 raxi_ps";
                        $totalResult = mysqli_query($konek, $totalQuery);
                        $totalData = mysqli_fetch_assoc($totalResult)['total'];

                        $totalHalaman = ceil($totalData / $batas);
                        $kodequery = "SELECT 
                        r.idraxips,
                        r.nofile_raxips,
                        rv.nofile_revisi_raxips,
                        r.tgl_raxips,
                        rv.idrevisi_raxips,

                        COALESCE(rv.nofile_revisi_raxips, r.nofile_raxips) AS nofile,
                        COALESCE(rv.tgl_raxips, r.tgl_raxips) AS tgl_raxips_bru,
                        COALESCE(rv.idpegawai, r.idpegawai) AS idpegawai,
                        COALESCE(rv.status_checkraxips, r.status_checkraxips) AS status_checkraxips,
                        COALESCE(rv.tgl_checkraxips, r.tgl_checkraxips) AS tgl_checkraxips,
                        COALESCE(rv.checker, r.checker) AS checker,

                        c.nama_customer,
                        c.bu

                    FROM raxi_ps r

                    LEFT JOIN (
                        SELECT rv1.*
                        FROM revisi_raxi_ps rv1
                        INNER JOIN (
                            SELECT idraxips, MAX(idrevisi_raxips) AS max_id
                            FROM revisi_raxi_ps
                            GROUP BY idraxips
                        ) rv2 
                            ON rv1.idraxips = rv2.idraxips 
                            AND rv1.idrevisi_raxips = rv2.max_id
                    ) rv 
                        ON rv.idraxips = r.idraxips

                    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_raxips_bru'])) ?></td>
                                <td><?php echo $row['bu'] . " " . $row['nama_customer'] ?></td>
                                <td><?php echo $row['status_checkraxips'] ?></td>
                                <td>
                                    <?php
                                    if ($row['status_checkraxips'] == "Belum") {
                                        echo "-";
                                    } else {
                                        echo date('d F Y', strtotime($row['tgl_checkraxips']));
                                    }
                                    ?>
                                </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 (strpos($nofile, '.') !== false) {
                                        ?>
                                            <a href="function/function-penawaranraxi.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="penawaranraxi-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_raxips']; ?>">
                                                <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_raxips']; ?>">
                                                <i class="bi bi-printer-fill"></i>
                                            </button>
                                            <!-- <a href="print-raxips-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-revisiraxips.php";
                                        } else {
                                        ?>
                                            <a href="function/function-penawaranraxi.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="penawaranraxi-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['idraxips']; ?>">
                                                <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['idraxips']; ?>">
                                                <i class="bi bi-printer-fill"></i>
                                            </button>
                                            <!-- <a href="print-raxips.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-raxips.php";
                                        }
                                        ?>
                                    </div>
                                </td>
                            </tr>
                        <?php
                            $no++;
                        }
                        ?>
                    </tbody>
                </table>
            </div>
            <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_keterangan').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>