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

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

<body>
    <!-- NAVIGASI -->
    <?php include "asset/navigasi.php"; ?>

    <!-- CONTENT -->
    <div class="container">
        <div class="row">
            <div class="col-4">
                <h4 class="mb-4">
                    Dashboard
                    <small class="text-muted">Selamat datang, <?= $nama_pegawai; ?> 👋</small>
                </h4>
            </div>
            <div class="col-7">
                <?php
                $filterTipe = isset($_GET['tipe']) ? $_GET['tipe'] : 'All';
                $filterPeriode = isset($_GET['periode']) ? $_GET['periode'] : 'HariIni';

                // Tanggal sekarang
                $today = date('Y-m-d');
                $startOfWeek = date('Y-m-d', strtotime('monday this week'));
                $startOfMonth = date('Y-m-01');

                $periodeSQL = "";

                $tgl_awal = $_GET['tgl_awal'] ?? '';
                $tgl_akhir = $_GET['tgl_akhir'] ?? '';

                if (!empty($tgl_awal) && !empty($tgl_akhir)) {

                    $tgl_awal = mysqli_real_escape_string($konek, $tgl_awal);
                    $tgl_akhir = mysqli_real_escape_string($konek, $tgl_akhir);

                    $periodeSQL = " AND DATE(tgltelp_custbisman) 
                    BETWEEN '$tgl_awal' AND '$tgl_akhir'";
                } else {

                    if ($filterPeriode == 'HariIni') {
                        $periodeSQL = " AND DATE(tgltelp_custbisman) = '$today'";
                    } elseif ($filterPeriode == 'MingguIni') {
                        $periodeSQL = " AND DATE(tgltelp_custbisman) 
                        BETWEEN '$startOfWeek' AND '$today'";
                    } elseif ($filterPeriode == 'BulanIni') {
                        $periodeSQL = " AND DATE(tgltelp_custbisman) 
                        BETWEEN '$startOfMonth' AND '$today'";
                    }
                }

                ?>
                <form id="filterForm" method="GET" action="">
                    <input type="hidden" name="tipe" value="<?= $filterTipe ?>">
                    <div class="row g-2">
                        <div class="col-md-2">
                            <select name="periode" class="form-select">
                                <option value="HariIni" <?= $filterPeriode == 'HariIni' ? 'selected' : '' ?>>Hari Ini</option>
                                <option value="MingguIni" <?= $filterPeriode == 'MingguIni' ? 'selected' : '' ?>>Minggu Ini</option>
                                <option value="BulanIni" <?= $filterPeriode == 'BulanIni' ? 'selected' : '' ?>>Bulan Ini</option>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <div class="input-group">
                                <span class="input-group-text">Dari:</span>
                                <input type="date" name="tgl_awal" class="form-control" value="<?= $_GET['tgl_awal'] ?? '' ?>">
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="input-group">
                                <span class="input-group-text">Sampai:</span>
                                <input type="date" name="tgl_akhir" class="form-control" value="<?= $_GET['tgl_akhir'] ?? '' ?>">
                            </div>
                        </div>

                        <div class="col-md-2 d-flex gap-1">
                            <button type="submit" class="btn btn-primary w-100">Filter</button>
                            <a href="dashboard.php" class="btn btn-secondary w-100">Reset</a>
                        </div>
                    </div>
                </form>
                <!-- <div class="btn btn-primary">Filter</div> -->
            </div>
        </div>
        <br>
        <div class="row g-3">
            <div class="col">
                <div class="card shadow">
                    <p style="font-weight: 700;font-size: 20px;margin-left: 10px;margin-top: 10px;">Total Customer Baru</p>
                    <div class="card-body">
                        <?php
                        $query = mysqli_query($konek, "
                            SELECT COUNT(*) AS total_customer_baru
                            FROM (
                                SELECT idcustomer, MIN(tgltelp_custbisman) AS tgltelp_custbisman
                                FROM telp_custbisman
                                GROUP BY idcustomer
                                HAVING 
                                    DATEDIFF(CURDATE(), tgltelp_custbisman) <= 365
                                    $periodeSQL
                            ) AS cust_baru
                        ");
                        $data = mysqli_fetch_array($query);
                        $total = $data['total_customer_baru'];
                        ?>
                        <p style="margin-top:-20px;font-size:30px;font-weight:700;margin-bottom:-1px;">
                            <span style="
                                        display:inline-flex;
                                        align-items:center;
                                        justify-content:center;
                                        width:45px;
                                        height:45px;
                                        background-color:#0d6efd;
                                        color:white;
                                        border-radius:50%;
                                        margin-right:10px;
                                        font-size:20px;
                                    ">
                                <i class="bi bi-people"></i>
                            </span>
                            <?= $total ?>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card shadow">
                    <p style="font-weight: 700;font-size: 20px;margin-left: 10px;margin-top: 10px;">Total Customer Lama</p>
                    <div class="card-body">
                        <?php
                        $query = mysqli_query($konek, "
                            SELECT COUNT(DISTINCT t1.idcustomer) AS total_customer_lama
                            FROM telp_custbisman t1
                            WHERE 1
                            $periodeSQL
                            AND EXISTS (
                                SELECT 1
                                FROM telp_custbisman t2
                                WHERE t2.idcustomer = t1.idcustomer
                                AND t2.tgltelp_custbisman < t1.tgltelp_custbisman
                            )
                        ");

                        $data = mysqli_fetch_array($query);
                        $total = $data['total_customer_lama'];
                        ?>
                        <p style="margin-top:-20px;font-size:30px;font-weight:700;margin-bottom:-1px;">
                            <span style="
                                        display:inline-flex;
                                        align-items:center;
                                        justify-content:center;
                                        width:45px;
                                        height:45px;
                                        background-color:#0d6efd;
                                        color:white;
                                        border-radius:50%;
                                        margin-right:10px;
                                        font-size:20px;
                                    ">
                                <i class="bi bi-people"></i>
                            </span>
                            <?= $total ?>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card shadow">
                    <p style="font-weight: 700;font-size: 20px;margin-left: 10px;margin-top: 10px;">Total Telp Customer</p>
                    <div class="card-body">
                        <?php
                        $query = mysqli_query($konek, "SELECT COUNT(idtelp_custbisman) AS total FROM telp_custbisman WHERE 1 
                               $periodeSQL");
                        $data = mysqli_fetch_array($query);
                        $total = $data['total'];
                        ?>
                        <p style="margin-top:-20px;font-size:30px;font-weight:700;margin-bottom:-1px;">
                            <span style="
                                        display:inline-flex;
                                        align-items:center;
                                        justify-content:center;
                                        width:45px;
                                        height:45px;
                                        background-color:#0d6efd;
                                        color:white;
                                        border-radius:50%;
                                        margin-right:10px;
                                        font-size:20px;
                                    ">
                                <i class="bi bi-telephone"></i>
                            </span>

                            <?= $total ?>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card shadow" style="background-color: #ff0000;">
                    <p style="font-weight: 700;font-size: 20px;margin-left: 10px;margin-top: 10px; color: white;">Hak Akses</p>
                    <div class="card-body">
                        <p style="margin-top:-20px;font-size:30px;font-weight:700;margin-bottom:-1px;color: white;">
                            <span style="
                                        display:inline-flex;
                                        align-items:center;
                                        justify-content:center;
                                        width:45px;
                                        height:45px;
                                        color:white;
                                        border-radius:50%;
                                        margin-right:10px;
                                        font-size:20px;
                                    ">
                                <i class="bi bi-key-fill"></i>
                            </span>

                            <?= $akses ?>
                        </p>
                    </div>
                </div>
            </div>
        </div>
        <br>
        <div class="row g-3">
            <div class="col">
                <?php
                $filterTipeSQL = "";
                if ($filterTipe != 'All') {
                    $filterTipeSQL = " AND sumber = '$filterTipe'";
                }

                $queryket = mysqli_query($konek, "SELECT ket_sumber, TRIM(sumber) as sumber
                                        FROM telp_custbisman 
                                        WHERE TRIM(ket_sumber) != '' 
                                        $filterTipeSQL
                                        $periodeSQL
                                    ");

                $data_totalket = [];
                $data_ketsumber = [];

                if ($filterTipe == 'All') {

                    // MODE ALL → langsung dari kolom sumber
                    $queryAll = mysqli_query($konek, "
                        SELECT TRIM(sumber) as sumber, COUNT(idtelp_custbisman) as total
                        FROM telp_custbisman
                        WHERE 1
                        $periodeSQL
                        GROUP BY TRIM(sumber)
                    ");

                    while ($rowAll = mysqli_fetch_assoc($queryAll)) {
                        $data_ketsumber[$rowAll['sumber']] = $rowAll['total'];
                    }
                } else {

                    while ($row = mysqli_fetch_assoc($queryket)) {

                        $sources = explode('/', $row['ket_sumber']);

                        foreach ($sources as $source) {

                            $source = trim($source);
                            if ($source == '')
                                continue;

                            // KHUSUS FILTER WA
                            if ($filterTipe == 'WA') {

                                $sources = explode('/', $row['ket_sumber']);

                                $hasil = [];

                                foreach ($sources as $item) {

                                    $item = trim($item);

                                    // buang email
                                    if (strpos($item, '@') !== false) {
                                        continue;
                                    }

                                    if ($item != '') {
                                        $hasil[] = $item;
                                    }
                                }

                                $label = implode(' / ', $hasil);

                                $data_ketsumber[$label] =
                                    ($data_ketsumber[$label] ?? 0) + 1;

                                break; // keluar dari foreach karena sudah diproses
                            }

                            // FILTER WEBSITE / EMAIL / TELP
                            if (strpos($source, '@') !== false) {

                                $tipe = 'Email';

                            } elseif (preg_match('/^[0-9 +()-]+$/', $source)) {

                                $tipe = 'Telp';

                            } else {

                                $tipe = 'Website';
                            }

                            if ($filterTipe == $tipe) {

                                $data_ketsumber[$source] =
                                    ($data_ketsumber[$source] ?? 0) + 1;
                            }
                        }
                    }
                }

                // Array untuk chart
                $labels_ketsumber = array_keys($data_ketsumber);
                $totals_ketsumber = array_values($data_ketsumber);

                // Total keseluruhan
                $total_ketsumber = array_sum($totals_ketsumber);
                ?>
                <div class="card shadow-sm" style="height: 100%;">
                    <div class="card-body">
                        <form id="filterKetSumber" method="GET" action="">
                            <input type="hidden" name="periode" value="<?= $filterPeriode ?>">
                            <input type="hidden" name="tgl_awal" value="<?= $_GET['tgl_awal'] ?? '' ?>">
                            <input type="hidden" name="tgl_akhir" value="<?= $_GET['tgl_akhir'] ?? '' ?>">
                            <p style="font-weight: 700; display:flex; justify-content:space-between;">
                                Grafik Sumber
                                <select name="tipe" id="filterTipe" class="form-select" style="width:200px;">
                                    <option value="All" <?= $filterTipe == 'All' ? 'selected' : '' ?>>All</option>
                                    <option value="WA" <?= $filterTipe == 'WA' ? 'selected' : '' ?>>WA</option>
                                    <option value="Website" <?= $filterTipe == 'Website' ? 'selected' : '' ?>>Website</option>
                                    <option value="Email" <?= $filterTipe == 'Email' ? 'selected' : '' ?>>Email</option>
                                    <option value="Telp" <?= $filterTipe == 'Telp' ? 'selected' : '' ?>>Telp</option>
                                </select>
                            </p>
                        </form>
                        <div>
                            <canvas id="grafikKetSumber"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col">
                <?php
                // $query = mysqli_query($konek, "SELECT 
                //                     CASE 
                //                         WHEN buat_penawaran = 1 THEN 'Telp + Penawaran'
                //                         ELSE 'Hanya Telp'
                //                     END AS kategori_telp,
                //                     CASE 
                //                         WHEN LOWER(keperluan) LIKE '%service%' THEN 'Service'
                //                         ELSE 'Penjualan'
                //                     END AS kategori_keperluan,
                //                     COUNT(*) AS totalkep
                //                 FROM telp_custbisman
                //                 WHERE 1
                //                     $periodeSQL
                //                 GROUP BY kategori_telp, kategori_keperluan
                //                 ORDER BY kategori_telp, kategori_keperluan");
                $query = mysqli_query($konek, "
                    SELECT
                        jenis_keperluan,
                        CASE
                            WHEN buat_penawaran = 1 THEN 'Telp + Penawaran'
                            ELSE 'Hanya Telp'
                        END AS kategori_telp,
                        COUNT(*) AS totalkep
                    FROM telp_custbisman
                    WHERE 1
                        $periodeSQL
                    GROUP BY jenis_keperluan, kategori_telp
                ");
                $data_keperluan = [];
                $data_totalkep = [];

                // while ($rows = mysqli_fetch_array($query)) {
                //     $data_keperluan[] = $rows["kategori_telp"] . " - " . $rows["kategori_keperluan"];
                //     $data_totalkep[] = $rows["totalkep"];
                // }
                while ($rows = mysqli_fetch_assoc($query)) {
                    $data_keperluan[] = $rows['jenis_keperluan'];
                    $data_totalkep[] = $rows['totalkep'];
                }
                ?>
                <div class="card">
                    <div class="card-body">
                        <p style="font-weight: 700;">Data Kategori Telp</p>
                        <div>
                            <canvas id="grafikKeperluan"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        document.getElementById('filterTipe').addEventListener('change', function() {
            document.getElementById('filterKetSumber').submit();
        });
        document.getElementById('filterPeriode').addEventListener('change', function() {
            document.getElementById('filterForm').submit();
        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>

    <script>
        const KetSumber = document.getElementById('grafikKetSumber');

        Chart.register(ChartDataLabels);

        new Chart(KetSumber, {
            type: 'bar',
            data: {
                labels: <?= json_encode($labels_ketsumber); ?>,
                datasets: [{
                    label: 'Total',
                    data: <?= json_encode($totals_ketsumber); ?>,
                    backgroundColor: [
                        '#dc3545',
                        '#007bff',
                        '#28a745',
                        '#ffc107',
                        '#6f42c1',
                        '#17a2b8'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    },
                    datalabels: {
                        color: '#fff',
                        anchor: 'center',
                        align: 'center',
                        textAlign: 'center',
                        font: {
                            weight: 'bold',
                            size: 12
                        },
                        formatter: function(value, context) {
                            const label = context.chart.data.labels[context.dataIndex];
                            return label + '\n(' + value + ')';
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    </script>
    <script>
        const keperluan = document.getElementById('grafikKeperluan');
        Chart.register(ChartDataLabels);
        new Chart(keperluan, {
            type: 'bar',
            data: {
                labels: <?= json_encode($data_keperluan); ?>,
                datasets: [{
                    data: <?= json_encode($data_totalkep); ?>,
                    backgroundColor: [
                        '#dc3545',
                        '#007bff',
                        '#28a745',
                        '#ffc107',
                        '#6f42c1',
                        '#17a2b8'
                    ],
                    borderWidth: 1
                }]
            },
            plugins: [ChartDataLabels],
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    },
                    datalabels: {
                        color: '#fff',
                        anchor: 'center',
                        align: 'center',
                        textAlign: 'center',
                        font: {
                            weight: 'bold',
                            size: 12
                        },
                        formatter: function(value, context) {
                            const label = context.chart.data.labels[context.dataIndex];
                            return label + '\n(' + value + ')';
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    </script>


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


</html>