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

$nama_pegawai = $_SESSION['nama_pegawai'];
$akses = $_SESSION['akses'];
$handle = $_SESSION['handle'];
?>
<!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 Telepon Customer Raxi</h1>
                </div>
                <div class="p-2 bd-highlight" style="align-items: center;display: flex;gap: 3px;">
                    <!-- <a class="tmbdata" href="penawaranraxi-tambah.php">Tambah Data</a> -->
                    <a href="function/import-raxi.php" class="btn btn-primary tmbdatap">Import Excel</a>
                    <a href="asset/autoid_telpcustraxi.php" class="btn btn-primary tmbdatap">Tambah Data</a>
                </div>
            </div>
        </div>
        <div class="row">
            <form method="GET" class="row g-2 mb-3">

                <div class="col">
                    <input type="text" name="nama_customer" class="form-control" placeholder="Cari Nama Customer"
                        value="<?= $_GET['nama_customer'] ?? '' ?>">
                </div>

                <div class="col-md-2">
                    <input type="text" name="kota" class="form-control" placeholder="Kota"
                        value="<?= $_GET['kota'] ?? '' ?>">
                </div>

                <div class="col-md-2">
                    <input type="text" name="status" class="form-control" placeholder="Status"
                        value="<?= $_GET['sumber'] ?? '' ?>">
                </div>

                <div class="col-md-2">
                    <input type="date" name="tgl_awal" class="form-control" value="<?= $_GET['tgl_awal'] ?? '' ?>">
                </div>

                <div class="col-md-2">
                    <input type="date" name="tgl_akhir" class="form-control" value="<?= $_GET['tgl_akhir'] ?? '' ?>">
                </div>
                <?php
                if ($handle != "Service" && $handle != "Penjul") {
                    ?>
                    <div class="col-md-2">
                        <select name="jenis" class="form-select">
                            <option value="">Semua</option>
                            <option value="service" <?= ($_GET['jenis'] ?? '') == 'service' ? 'selected' : '' ?>>
                                Service
                            </option>
                            <option value="nonservice" <?= ($_GET['jenis'] ?? '') == 'nonservice' ? 'selected' : '' ?>>
                                penjualan
                            </option>
                        </select>
                    </div>
                    <?php
                }
                ?>
                <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="telp_custraxi.php" class="btn btn-secondary">
                        Reset
                    </a>
                </div>

            </form>

        </div>
        <div class="row">
            <div class="table-responsive">
                <table class="table table-sm">
                    <?php
                    function sort_link($column, $label)
                    {
                        $current_order_by = $_GET['order_by'] ?? '';
                        $current_order = $_GET['order'] ?? 'ASC';

                        $icon = '';
                        $new_order = 'ASC';

                        if ($current_order_by === $column) {

                            if ($current_order === 'ASC') {
                                $icon = " <i class='bi bi-caret-up-fill'></i>";
                                $new_order = 'DESC';
                            } else {
                                $icon = " <i class='bi bi-caret-down-fill'></i>";
                                $new_order = 'ASC';
                            }
                        }

                        $query = $_GET;
                        $query['order_by'] = $column;
                        $query['order'] = $new_order;

                        // SIMPAN ORDER STATUS TERAKHIR
                        if ($column === 'status') {
                            $query['last_status_order'] = $new_order;
                        }

                        $url = '?' . http_build_query($query);

                        return "<a href='$url' style='text-decoration:none;color:black;font-weight:500;'>$label$icon</a>";
                    }
                    ?>


                    <thead>
                        <tr style="text-align: center;">
                            <th scope="col"><?= sort_link('tgltelp_custraxi', 'Tanggal Telp') ?></th>
                            <th scope="col"><?= sort_link('nama_customer', 'Nama Customer') ?></th>
                            <th scope="col"><?= sort_link('pic', 'Nama PIC') ?></th>
                            <th scope="col"><?= sort_link('telp_pic', 'Telp PIC') ?></th>
                            <th scope="col"><?= sort_link('ket_sumber', 'Sumber') ?></th>
                            <th scope="col"><?= sort_link('keperluan', 'Kebutuhan') ?></th>
                            <!-- <th scope="col"><?= sort_link('kebutuhan', 'Keperluan') ?></th> -->
                            <th scope="col"><?= sort_link('status', 'Status') ?></th>
                            <th scope="col"><?= sort_link('selisih', 'Durasi Hari') ?></th>
                            <th scope="col">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        include "koneksi.php";
                        $where = [];
                        $params = "";
                        // Hak akses
                        if ($handle == "Service") {
                            $where[] = "LOWER(t.keperluan) LIKE '%service%'";
                        } elseif ($handle == "Penjul") {
                            $where[] = "LOWER(t.keperluan) NOT LIKE '%service%'";
                        } else {
                            // User yang bisa lihat semua
                            if (!empty($_GET['jenis'])) {
                                if ($_GET['jenis'] == 'service') {
                                    $where[] = "LOWER(t.keperluan) LIKE '%service%'";
                                } elseif ($_GET['jenis'] == 'nonservice') {
                                    $where[] = "LOWER(t.keperluan) NOT LIKE '%service%'";
                                }
                            }
                        }

                        // Filter Nama Customer
                        if (!empty($_GET['nama_customer'])) {

                            $input = trim($_GET['nama_customer']);
                            $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);

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

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

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


                        // Filter Kota
                        if (!empty($_GET['kota'])) {
                            $kota = mysqli_real_escape_string($konek, $_GET['kota']);
                            $where[] = "c.kota LIKE '%$kota%'";
                        }

                        // Filter Sumber
                        if (!empty($_GET['status'])) {
                            $status = mysqli_real_escape_string($konek, $_GET['status']);
                            $where[] = "f.status LIKE '%$status%'";

                        }

                        // Filter Tanggal
                        if (!empty($_GET['tgl_awal']) && !empty($_GET['tgl_akhir'])) {
                            $tgl_awal = $_GET['tgl_awal'];
                            $tgl_akhir = $_GET['tgl_akhir'];
                            $where[] = "t.tgltelp_custraxi BETWEEN '$tgl_awal' AND '$tgl_akhir'";
                        }

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

                        // FILTER HEAD
                        $allowed_columns = [
                            'tgltelp_custraxi' => 't.tgltelp_custraxi',
                            'nama_customer' => 'c.nama_customer',
                            'pic' => 'p.nama_pic',
                            'telp_pic' => 'p.telp_pic',
                            'status' => 'f.status',
                            'selisih' => 'selisih'
                        ];

                        $order_by = $_GET['order_by'] ?? '';
                        $order = $_GET['order'] ?? 'DESC';
                        $order = strtoupper($order) === 'ASC' ? 'ASC' : 'DESC';

                        /*
                        |--------------------------------------------------------------------------
                        | DEFAULT → DATA TERBARU
                        |--------------------------------------------------------------------------
                        */
                        if (empty($order_by)) {

                            // $order_sql = "t.idtelp_custraxi DESC";
                            // $order_sql = "t.tgltelp_custraxi DESC, t.idtelp_custraxi DESC";
                            $status_filter = !empty($_GET['status']);
                            if ($status_filter) {
                                $order_sql = "f.tglraxi_followup DESC";
                            } else {
                                $order_sql = "t.tgltelp_custraxi DESC, t.idtelp_custraxi DESC";
                            }

                            /*
                            |--------------------------------------------------------------------------
                            | STATUS DIKLIK
                            |--------------------------------------------------------------------------
                            */
                        } elseif ($order_by === 'status') {

                            $order_sql = "f.status $order";

                            /*
                            |--------------------------------------------------------------------------
                            | DURASI DIKLIK
                            |--------------------------------------------------------------------------
                            */
                        } elseif ($order_by === 'selisih') {

                            // cek apakah sebelumnya user klik status
                            // if (isset($_GET['last_status_order'])) {
                        
                            //     $status_order = $_GET['last_status_order'];
                            // } else {
                        
                            //     // default kalau belum pernah klik status
                            //     $status_order = 'ASC';
                            // }
                        
                            // $order_sql = "f.status $status_order, selisih $order";
                            if (!empty($_GET['status'])) {

                                // ada filter status
                                $order_sql = "f.status ASC, selisih $order";

                            } elseif (isset($_GET['last_status_order'])) {

                                // pernah klik header status
                                $status_order = $_GET['last_status_order'];
                                $order_sql = "f.status $status_order, selisih $order";

                            } else {

                                // default
                                $order_sql = "selisih $order";
                            }

                            /*
                            |--------------------------------------------------------------------------
                            | KOLOM LAIN
                            |--------------------------------------------------------------------------
                            */
                        } else {

                            $allowed_columns = [
                                'tgltelp_custraxi' => 't.tgltelp_custraxi',
                                'nama_customer' => 'c.nama_customer',
                                'pic' => 'p.nama_pic',
                                'telp_pic' => 'p.telp_pic',
                                'keperluan' => 't.keperluan'
                            ];

                            if (array_key_exists($order_by, $allowed_columns)) {

                                $column_sql = $allowed_columns[$order_by];
                                $order_sql = "$column_sql $order";
                            } else {

                                $order_sql = "t.idtelp_custraxi DESC";
                            }
                        }

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

                        // PAGINATION
                        $limit = 10; // jumlah data per halaman
                        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
                        $page = ($page > 0) ? $page : 1;
                        $start = ($page - 1) * $limit;

                        // Hitung total data
                        $total_query = mysqli_query($konek, "
                            SELECT COUNT(DISTINCT t.idtelp_custraxi) as total
                            FROM telp_custraxi t
                            INNER JOIN customer c ON t.idcustomer=c.idcustomer
                            INNER JOIN followup_raxi f ON f.idtelp_custraxi = t.idtelp_custraxi
                            $where_sql
                        ");

                        $total_data = mysqli_fetch_assoc($total_query)['total'];
                        $total_pages = ceil($total_data / $limit);

                        // $idtelp_custraxi = $_GET["idtelp_custraxi"] ?? "";
                        // c.nama_customer,
                        //         c.bu,
                        //         c.kota,
                        // p.nama_pic,
                        //         p.telp_pic,
                        // CASE 
                        //             WHEN f.status = 'Prospec'
                        //                 THEN DATEDIFF(CURDATE(), f.tglraxi_followup)
                        //             WHEN f.status = 'Hold'
                        //                 THEN DATEDIFF(CURDATE(), f.tgl_hold)
                        //             ELSE NULL
                        //         END AS selisih
                        $no = 1;
                        $sql = mysqli_query($konek, "
                            SELECT t.idtelp_custraxi,t.tgltelp_custraxi,
                                
                                COALESCE(c.nama_customer) AS nama_customer,
                                COALESCE(c.bu) AS bu,
                                COALESCE(c.kota) AS kota,
                                t.keperluan,t.kebutuhan,t.sumber,t.ket_sumber,
                                COALESCE(p.nama_pic) AS nama_pic,
                                COALESCE(p.telp_pic) AS telp_pic,
                                f.status,
                                f.tglraxi_followup,f.tgl_hold,f.tglfolloweraxi,
                                CASE
                                    WHEN f.status IN (
                                        'Penawaran',
                                        'Demo',
                                        'Follow Up',
                                        'Prospec',
                                        'PO',
                                        'Belum Bayar',
                                        'Proses Kirim'
                                    )
                                    THEN DATEDIFF(CURDATE(), f.tglraxi_followup)

                                    WHEN f.status = 'Hold'
                                    THEN DATEDIFF(CURDATE(), f.tgl_hold)

                                    ELSE 0
                                END AS selisih,
                                CASE
                                    WHEN DATEDIFF(CURDATE(), c.tglinput) > 365
                                        THEN 'Customer Lama'
                                    ELSE 'Customer Baru'
                                END AS kategori_customer
                            FROM telp_custraxi t
                            INNER JOIN telp_custraxi_detail td ON td.idtelp_custraxi=t.idtelp_custraxi
                            LEFT JOIN customer c ON t.idcustomer=c.idcustomer
                            LEFT JOIN pic p ON p.idcustomer = c.idcustomer
                            INNER JOIN followup_raxi f ON f.idtelp_custraxi = t.idtelp_custraxi AND f.idfollowup_raxi = (
                                                                                                        SELECT fr.idfollowup_raxi
                                                                                                        FROM followup_raxi fr
                                                                                                        WHERE fr.idtelp_custraxi = t.idtelp_custraxi
                                                                                                        ORDER BY fr.tglraxi_followup DESC, fr.idfollowup_raxi DESC
                                                                                                        LIMIT 1
                                                                                                    )
                            $where_sql
                            GROUP BY t.idtelp_custraxi
                            ORDER BY $order_sql
                            LIMIT $start, $limit
                        ");

                        //INI BARU
                        function hitungHariKerja($tanggalAwal, $tanggalAkhir)
                        {
                            $awal = new DateTime($tanggalAwal);
                            $akhir = new DateTime($tanggalAkhir);

                            $hariKerja = 0;

                            while ($awal < $akhir) {
                                $hari = $awal->format('N'); // 1=Senin ... 7=Minggu
                        
                                if ($hari < 6) {
                                    $hariKerja++;
                                }

                                $awal->modify('+1 day');
                            }

                            return $hariKerja;
                        }

                        while ($row = mysqli_fetch_array($sql)) {
                            ?>
                            <tr style="text-align: center;">
                                <td><?php echo date('d F Y', strtotime($row['tgltelp_custraxi'])) ?></td>
                                <td><?php
                                if (!empty($row['nama_customer']) && strpos($row['nama_customer'], 'NULL') === 0) {
                                    echo $row['nama_customer'] . " (" . $row['kategori_customer'] . ")";
                                } else {
                                    echo $row['bu'] . " " . $row['nama_customer'] . " (" . $row['kategori_customer'] . ")";
                                }
                                ?>
                                </td>
                                <td><?php echo $row['nama_pic'] ?></td>
                                <td><?php echo $row['telp_pic'] ?></td>
                                <td>
                                    <?php
                                    $pecah = array_map('trim', explode('/', $row['ket_sumber']));
                                    $key = strtolower($row['sumber']);

                                    $mapping = [
                                        'website' => 0,
                                        'email'   => 1,
                                        'telepon'    => 2,
                                        'wa'      => 2
                                    ];

                                    if (isset($mapping[$key]) && isset($pecah[$mapping[$key]])) {
                                        echo $pecah[$mapping[$key]];
                                    } else {
                                        // jika format ket_sumber tidak sesuai
                                        echo $row['ket_sumber'];
                                    }
                                    ?>
                                </td>
                                <td><?php echo $row['keperluan'] ?></td>
                                <!-- <td><?php echo $row['kebutuhan'] ?></td> -->
                                <td><?php
                                echo $row['status'];
                                $status = $row['status'];
                                echo "</br>";
                                $idtelp = $row["idtelp_custraxi"];
                                $cekfllw = mysqli_query($konek, "SELECT COUNT(*) as total FROM followup_raxi WHERE idtelp_custraxi = '$idtelp' AND status = 'Follow Up'");
                                $datafllw = mysqli_fetch_assoc($cekfllw);
                                $jmlfllwe = $datafllw["total"];
                                $jmlflw = $jmlfllwe - 1;
                                if ($jmlfllwe >= 1 && $status == "Follow Up") {
                                    echo "<p style='color:green;font-weight:600;'>Follow $jmlfllwe</p>";
                                }
                                ?>
                                </td>
                                <td>
                                    <?php

                                    $status = $row['status'];
                                    if ($status == "Penawaran" || $status == "Demo") {
                                        $jumlahHari = hitungHariKerja(
                                            $row['tglraxi_followup'],
                                            date('Y-m-d')
                                        );
                                        if ($jumlahHari <= 2) {
                                            echo $jumlahHari . " Hari";
                                        } else {
                                            echo "<span style='color:red;font-weight:600;'>$jumlahHari Hari</span> <i class='bi bi-exclamation-diamond text-danger' title='Segera Follow Up'></i>";
                                        }
                                    } else if ($status == "Follow Up") {
                                        $jumlahHari = hitungHariKerja(
                                            $row['tglraxi_followup'],
                                            date('Y-m-d')
                                        );
                                        if ($jumlahHari <= 2) {
                                            echo $jumlahHari . " Hari";
                                        } else {
                                            echo "<span style='color:red;font-weight:600;'>$jumlahHari Hari</span> <i class='bi bi-exclamation-diamond text-danger' title='Segera Follow Up'></i>";
                                        }
                                    } else if ($status == "Prospec") {
                                        $jumlahHari = hitungHariKerja(
                                            $row['tglraxi_followup'],
                                            date('Y-m-d')
                                        );
                                        if ($jumlahHari <= 2) {
                                            echo $jumlahHari . " Hari";
                                        } else {
                                            echo "<span style='color:red;font-weight:600;'>$jumlahHari Hari</span> <i class='bi bi-exclamation-diamond text-danger' title='Segera Follow Up'></i>";
                                        }
                                    } else if ($status == "PO") {
                                        $jumlahHari = hitungHariKerja(
                                            $row['tglraxi_followup'],
                                            date('Y-m-d')
                                        );
                                        if ($jumlahHari <= 3) {
                                            echo $jumlahHari . " Hari";
                                        } else {
                                            echo "<span style='color:red;font-weight:600;'>$jumlahHari Hari</span> <i class='bi bi-exclamation-diamond text-danger' title='Segera Follow Up'></i>";
                                        }
                                    } else if ($status == "Belum Bayar") {
                                        $jumlahHari = hitungHariKerja(
                                            $row['tglraxi_followup'],
                                            date('Y-m-d')
                                        );
                                        if ($jumlahHari <= 2) {
                                            echo $jumlahHari . " Hari";
                                        } else {
                                            echo "<span style='color:red;font-weight:600;'>$jumlahHari Hari</span> <i class='bi bi-exclamation-diamond text-danger' title='Segera Follow Up'></i>";
                                        }
                                    } else if ($status == "Proses Kirim") {
                                        $jumlahHari = hitungHariKerja(
                                            $row['tglraxi_followup'],
                                            date('Y-m-d')
                                        );
                                        if ($jumlahHari <= 1) {
                                            echo $jumlahHari . " Hari";
                                        } else {
                                            echo "<span style='color:red;font-weight:600;'>$jumlahHari Hari</span> <i class='bi bi-exclamation-diamond text-danger' title='Segera Follow Up'></i>";
                                        }
                                    } else if ($status == "Closing") {
                                        echo "-";
                                    } else if ($status == "Cancel") {
                                        echo "-";
                                    } else if ($status == "Hold") {
                                        $tglfolloweraxi = new DateTime($row['tglfolloweraxi']);
                                        $tgl_hold = new DateTime($row['tgl_hold']);
                                        $tglsekarang = new DateTime(date('Y-m-d'));
                                        $selisih = $tgl_hold->diff($tglsekarang);
                                        $jumlahHari = $selisih->days;
                                        // $jumlahHari = 5;
                                        if ($tglsekarang > $tgl_hold) {
                                            echo "Lewat " . $jumlahHari . " Hari <i class='bi bi-exclamation-diamond text-danger' title='Segera Follow Up'></i>";
                                        } else {
                                            if ($jumlahHari <= 2) {
                                                echo "Kurang " . $jumlahHari . " Hari Lagi <i class='bi bi-exclamation-diamond text-danger' title='Segera Follow Up'></i>";
                                            } else {
                                                echo "Kurang " . $jumlahHari . " Hari Lagi";
                                            }
                                        }
                                        // $tglsekarang = new DateTime(date('Y-m-d'));
                                    }
                                    ?>
                                </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> -->
                                        <!-- <a href="" class="btn btn-secondary btn-sm" title="REVISI"><i class="bi bi-wrench-adjustable"></i></a> -->
                                        <a href="telp_custraxiedit.php?idtelp_custraxi=<?= $row["idtelp_custraxi"] ?>&nama_customer=<?= $row["nama_customer"] ?>"
                                            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="#view<?= $row['idtelp_custraxi']; ?>">
                                            <i class="bi bi-eye-fill"></i>
                                        </button>
                                        <a href="function/function-telp.php?hpstelp&idtelp_custraxi=<?php echo $row['idtelp_custraxi'] ?>&tgl=<?php echo $row['tgltelp_custraxi'] ?>"
                                            class="btn btn-sm btn-danger" title="HAPUS"><i class="bi bi-trash3"></i></a>
                                        <?php
                                        if ($status != "Closing" && $status != "Cancel") {
                                            ?>
                                            <button class="btn btn-info btn-sm" title="FOLLOW UP" data-bs-toggle="modal"
                                                data-bs-target="#followup<?php echo $row['idtelp_custraxi'] ?>"
                                                style="font-weight: 800;color:white;">
                                                <i class="bi bi-plus-circle"></i>
                                            </button>
                                            <?php
                                        }
                                        ?>
                                        <button class="btn btn-success btn-sm" title="PENAWARAN" data-bs-toggle="modal"
                                            data-bs-target="#penawaran<?php echo $row['idtelp_custraxi'] ?>"
                                            style="font-weight: 800;color:white;">
                                            <i class="bi bi-tools"></i>
                                        </button>
                                        <!-- <a href="" class="btn btn-sm btn-print" title="PRINT"><i class="bi bi-printer-fill"></i></a> -->
                                    </div>
                                </td>
                            </tr>
                            <?php
                            $no++;
                        }
                        ?>
                    </tbody>
                </table>
            </div>
            <?php
            mysqli_data_seek($sql, 0);
            while ($row = mysqli_fetch_assoc($sql)) {
                ?>
                <div class="modal fade" id="view<?= $row['idtelp_custraxi']; ?>" tabindex="-1">
                    <div class="modal-dialog modal-lg modal-dialog-scrollable">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Detail Telp Customer Raxi</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <?php
                                $id = $row['idtelp_custraxi'];
                                $carikperluan = mysqli_query($konek, "SELECT keperluan FROM telp_custraxi WHERE idtelp_custraxi = '$id'");
                                $keperluanrow = mysqli_fetch_assoc($carikperluan);
                                $keperluan = $keperluanrow['keperluan'];

                                if (str_contains(strtolower($keperluan), 'service')) {
                                    $sqle = mysqli_query($konek, "
                                    SELECT t.idtelp_custraxi,t.tgltelp_custraxi,
                                        c.nama_customer,c.bu,c.kota,
                                        t.keperluan,t.sumber,t.note_telp,t.ket_sumber,p.nama_pic,p.telp_pic,p.note as note_pic,f.status,
                                        f.tglraxi_followup,f.tgl_hold,f.tglfolloweraxi,
                                        (SELECT MIN(tt.tgltelp_custraxi) 
                                        FROM telp_custraxi tt 
                                        WHERE tt.idcustomer = t.idcustomer
                                        ) AS transaksi_pertama,
                                        CASE
                                            WHEN DATEDIFF(CURDATE(), (SELECT MIN(tt.tgltelp_custraxi) 
                                                                        FROM telp_custraxi tt 
                                                                        WHERE tt.idcustomer = t.idcustomer)) > 365
                                            THEN 'Customer Lama'
                                            ELSE 'Customer Baru'
                                        END AS kategori_customer
                                    FROM telp_custraxi t
                                    INNER JOIN customer c ON t.idcustomer=c.idcustomer
                                    INNER JOIN pic p ON p.idcustomer = c.idcustomer
                                    INNER JOIN followup_raxi f ON f.idtelp_custraxi = t.idtelp_custraxi AND f.idfollowup_raxi = (
                                                                                                                SELECT fr.idfollowup_raxi
                                                                                                                FROM followup_raxi fr
                                                                                                                WHERE fr.idtelp_custraxi = t.idtelp_custraxi
                                                                                                                ORDER BY fr.tglraxi_followup DESC, fr.idfollowup_raxi DESC
                                                                                                                LIMIT 1
                                                                                                            )
                                    WHERE t.idtelp_custraxi = '$id'
                                    GROUP BY t.idtelp_custraxi");
                                } else {
                                    $sqle = mysqli_query($konek, "
                                    SELECT t.idtelp_custraxi,t.tgltelp_custraxi,
                                        c.nama_customer,c.bu,c.kota,
                                        t.keperluan,t.sumber,t.ket_sumber,t.note_telp,p.nama_pic,p.telp_pic,p.note as note_pic,f.status,
                                        f.tglraxi_followup,f.tgl_hold,f.tglfolloweraxi,
                                        (SELECT MIN(tt.tgltelp_custraxi) 
                                        FROM telp_custraxi tt 
                                        WHERE tt.idcustomer = t.idcustomer
                                        ) AS transaksi_pertama,
                                        CASE
                                            WHEN DATEDIFF(CURDATE(), (SELECT MIN(tt.tgltelp_custraxi) 
                                                                        FROM telp_custraxi tt 
                                                                        WHERE tt.idcustomer = t.idcustomer)) > 365
                                            THEN 'Customer Lama'
                                            ELSE 'Customer Baru'
                                        END AS kategori_customer
                                    FROM telp_custraxi t
                                    INNER JOIN customer c ON t.idcustomer=c.idcustomer
                                    INNER JOIN pic p ON p.idcustomer = c.idcustomer
                                    INNER JOIN followup_raxi f ON f.idtelp_custraxi = t.idtelp_custraxi AND f.idfollowup_raxi = (
                                                                                                                SELECT fr.idfollowup_raxi
                                                                                                                FROM followup_raxi fr
                                                                                                                WHERE fr.idtelp_custraxi = t.idtelp_custraxi
                                                                                                                ORDER BY fr.tglraxi_followup DESC, fr.idfollowup_raxi DESC
                                                                                                                LIMIT 1
                                                                                                            )
                                    WHERE t.idtelp_custraxi = '$id'
                                    GROUP BY t.idtelp_custraxi");
                                }
                                $data = $rows = mysqli_fetch_assoc($sqle);
                                ?>
                                <div class="row">
                                    <div class="col">
                                        <p style="font-weight: 700;">Nama PIC : <?= $data['nama_pic'] ?></p>
                                        <p>Sumber : <span><?= $data['sumber'] ?></span></p>
                                        <p>Keterangan Sumber :
                                            <br><span><?= !empty($data['ket_sumber']) ? $data['ket_sumber'] : '-' ?></span>
                                        </p>
                                        <p style="font-weight: 700;">Note : <span><?= $data['note_telp'] ?></span></p>
                                    </div>
                                    <div class="col">
                                        <p style="font-weight: 700;">Tentang PIC :</p>
                                        <p><?= nl2br(htmlspecialchars($data['note_pic'])) ?></p>
                                    </div>
                                </div>
                                <h3 style="text-decoration: underline;">Rincian Follow Up</h3>
                                <div class="row">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Tanggal Follow Up</th>
                                                <th>Status</th>
                                                <th>Note</th>
                                                <th>Tanggal Hold</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $queryfllw = mysqli_query($konek, "SELECT * FROM followup_raxi 
                                            WHERE idtelp_custraxi = '$id' ORDER BY tglfolloweraxi ASC
                                            LIMIT 1, 1000;");
                                            while ($rowf = mysqli_fetch_assoc($queryfllw)) {
                                                ?>
                                                <tr>
                                                    <td><?php echo date('d F Y', strtotime($rowf['tglfolloweraxi'])) ?></td>
                                                    <td><?php echo $rowf['status'] ?></td>
                                                    <td><?php echo $rowf['note'] ?></td>
                                                    <td>
                                                        <?php
                                                        echo ($rowf['status'] == 'Hold' && !empty($rowf['tgl_hold']))
                                                            ? date('d F Y', strtotime($rowf['tgl_hold']))
                                                            : '-';
                                                        ?>
                                                    </td>
                                                </tr>
                                                <?php
                                            }
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php } ?>
            <?php
            mysqli_data_seek($sql, 0);
            while ($row = mysqli_fetch_assoc($sql)) {
                ?>
                <div class="modal fade" id="followup<?= $row['idtelp_custraxi']; ?>" tabindex="-1">
                    <div class="modal-dialog modal-lg modal-dialog-scrollable">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Tambah Follow Up</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <form action="function/function-telp.php?idtelp_custraxi=<?= $row['idtelp_custraxi']; ?>"
                                method="post">
                                <div class="modal-body">
                                    <input type="text" name="idtelp_custraxi" value="<?= $row['idtelp_custraxi']; ?>"
                                        hidden>
                                    <div class="mb-3">
                                        <label for="">PIC Ada?</label>
                                        <select name="picada" class="form-select">
                                            <option value="ada">Ada</option>
                                            <option value="tidak">Tidak Ada</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="">Status Follow Up</label>
                                        <select name="sttsfollowup" id="pilihstatus" class="form-select">
                                            <option value="Follow Up">Follow Up</option>
                                            <option value="Prospec">Prospec</option>
                                            <option value="PO">PO</option>
                                            <option value="Proses Kirim">Proses Kirim</option>
                                            <option value="Belum Bayar">Belum Bayar</option>
                                            <option value="Hold">Hold</option>
                                            <option value="Cancel">Cancel</option>
                                            <option value="Closing">Closing (Deal Beli/PO)</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <input type="date" name="tglhold" id="tgl_hold" class="form-control"
                                            style="display: none;">
                                    </div>
                                    <div class="mb-3">
                                        <label for="">Notes Follow Up</label>
                                        <textarea name="notefllw" class="form-control"></textarea>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button class="btn btn-primary" type="submit" name="fllwup">Submit</button>
                                    <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            <?php } ?>
            <?php
            mysqli_data_seek($sql, 0);
            while ($row = mysqli_fetch_assoc($sql)) {
                ?>
                <div class="modal fade" id="penawaran<?= $row['idtelp_custraxi']; ?>" tabindex="-1">
                    <div class="modal-dialog modal-lg modal-dialog-scrollable">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Penawaran</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <form action="function/function-telp.php?idtelp_custraxi=<?= $row['idtelp_custraxi']; ?>"
                                method="post">
                                <div class="modal-body">
                                    <div class="row">
                                        <div class="col">
                                            <label class="form-label">Pilih Jenis Penawaran :</label>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="radiopen" id="radiopen1"
                                                    value="Penawaran Service" checked>
                                                <label class="form-check-label" for="radiopen1">
                                                    Penawaran Service
                                                </label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="radiopen" id="radiopen2"
                                                    value="Penawaran Unit Baru">
                                                <label class="form-check-label" for="radiopen2">
                                                    Penawaran Unit Baru
                                                </label>
                                            </div>
                                            <br>
                                            <label class="form-label">Pilih Kota :</label>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="radiokot" id="radiokot1"
                                                    value="tangerang" checked>
                                                <label class="form-check-label" for="radiokot1">
                                                    Tangerang
                                                </label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="radiokot" id="radiokot2"
                                                    value="surabaya">
                                                <label class="form-check-label" for="radiokot2">
                                                    Surabaya
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button class="btn btn-primary" type="submit" name="buatpen">Buat Penawaran</button>
                                    <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            <?php } ?>
        </div>
        <nav>
            <ul class="pagination justify-content-center">

                <!-- First -->
                <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                    <a class="page-link"
                        href="?page=1<?= '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) ?>">
                        <i class="bi bi-chevron-double-left"></i>
                    </a>
                </li>

                <!-- Previous -->
                <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                    <a class="page-link"
                        href="?page=<?= $page - 1 ?><?= '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) ?>">
                        <i class="bi bi-chevron-left"></i>
                    </a>
                </li>

                <?php
                $range = 2;

                if ($page > 3) {
                    echo '<li class="page-item">
                    <a class="page-link" href="?page=1&' . http_build_query(array_diff_key($_GET, ['page' => ''])) . '">1</a>
                  </li>';

                    if ($page > 4) {
                        echo '<li class="page-item disabled">
                        <span class="page-link">...</span>
                      </li>';
                    }
                }

                for ($i = max(1, $page - $range); $i <= min($total_pages, $page + $range); $i++) {
                    echo '<li class="page-item ' . ($i == $page ? 'active' : '') . '">
                    <a class="page-link" href="?page=' . $i . '&' .
                        http_build_query(array_diff_key($_GET, ['page' => ''])) .
                        '">' . $i . '</a>
                  </li>';
                }

                if ($page < $total_pages - 2) {

                    if ($page < $total_pages - 3) {
                        echo '<li class="page-item disabled">
                        <span class="page-link">...</span>
                      </li>';
                    }

                    echo '<li class="page-item">
                    <a class="page-link" href="?page=' . $total_pages . '&' .
                        http_build_query(array_diff_key($_GET, ['page' => ''])) .
                        '">' . $total_pages . '</a>
                  </li>';
                }
                ?>

                <!-- Next -->
                <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                    <a class="page-link"
                        href="?page=<?= $page + 1 ?><?= '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) ?>">
                        <i class="bi bi-chevron-right"></i>
                    </a>
                </li>

                <!-- Last -->
                <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                    <a class="page-link"
                        href="?page=<?= $total_pages ?><?= '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) ?>">
                        <i class="bi bi-chevron-double-right"></i>
                    </a>
                </li>

            </ul>
        </nav>

    </div>
    <script>
        function toggleChecker() {
            let nilai = document.getElementById('pilihstatus').value;

            let tgl_hold = document.getElementById('tgl_hold');

            // sembunyikan semua dulu
            tgl_hold.style.display = 'none';

            // tampilkan sesuai pilihan
            if (nilai == 'Hold') {
                tgl_hold.style.display = 'block';
            }
        }

        document.getElementById('pilihstatus').addEventListener('change', toggleChecker);
        document.addEventListener('DOMContentLoaded', toggleChecker);
    </script>
    <!-- INI FOOTER -->
    <?php
    include "asset/footer.php";
    ?>
</body>

</html>