<?php
include 'koneksi.php';
session_start();
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

$selected_tipe = $_GET['tipe'] ?? 'motor';
$selected_area = isset($_GET['area']) ? intval($_GET['area']) : 0;

// Pisahkan tanggal mentah untuk keperluan input form
$raw_start = $_GET['start_date'] ?? '';
$raw_end = $_GET['end_date'] ?? '';

// Tambahkan waktu untuk query filter yang akurat
$start_date = !empty($raw_start) ? $raw_start . ' 00:00:00' : '';
$end_date = !empty($raw_end) ? $raw_end . ' 23:59:59' : '';

$area_list = $conn->query("SELECT * FROM tbl_area ORDER BY nama_area");


function getChartData($conn, $tipe, $area = 0, $start_date = '', $end_date = '')
{
    $query = "SELECT merek, SUM(jumlah) as total FROM tbl_kendaraan WHERE 1=1";
    $params = [];
    $types = '';

    if ($tipe !== 'semua') {
        $query .= " AND tipe = ?";
        $params[] = $tipe;
        $types .= 's';
    }

    if ($area > 0) {
        $query .= " AND id_area = ?";
        $params[] = $area;
        $types .= 'i';
    }

    if (!empty($start_date) && !empty($end_date)) {
        $query .= " AND date_created BETWEEN ? AND ?";
        $params[] = $start_date;
        $params[] = $end_date;
        $types .= 'ss';
    }

    $query .= " GROUP BY merek ORDER BY merek";
    $stmt = $conn->prepare($query);
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

function getTotalCount($conn, $tipe, $area = 0, $start_date = '', $end_date = '')
{
    $query = "SELECT SUM(jumlah) as total FROM tbl_kendaraan WHERE 1=1";
    $params = [];
    $types = '';

    if ($tipe !== 'semua') {
        $query .= " AND tipe = ?";
        $params[] = $tipe;
        $types .= 's';
    }

    if ($area > 0) {
        $query .= " AND id_area = ?";
        $params[] = $area;
        $types .= 'i';
    }

    if (!empty($start_date) && !empty($end_date)) {
        $query .= " AND date_created BETWEEN ? AND ?";
        $params[] = $start_date;
        $params[] = $end_date;
        $types .= 'ss';
    }

    $stmt = $conn->prepare($query);
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    return $result['total'] ?? 0;
}

$data_motor = getChartData($conn, 'motor', $selected_area, $start_date, $end_date);
$data_mobil = getChartData($conn, 'mobil', $selected_area, $start_date, $end_date);
$data_semua = getChartData($conn, 'semua', $selected_area, $start_date, $end_date);

$total_motor = getTotalCount($conn, 'motor', $selected_area, $start_date, $end_date);
$total_mobil = getTotalCount($conn, 'mobil', $selected_area, $start_date, $end_date);
$total_semua = getTotalCount($conn, 'semua', $selected_area, $start_date, $end_date);

$chart_data = ($selected_tipe == 'motor') ? $data_motor : (($selected_tipe == 'mobil') ? $data_mobil : $data_semua);
?>

<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <title>Statistik Kendaraan</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>

<body class="bg-light">
    <div class="container mt-5">
        <h3 class="text-center mb-4">Statistik Jumlah Kendaraan per Merek</h3>

        <ul class="nav nav-tabs mb-3 justify-content-center">
            <li class="nav-item">
                <a class="nav-link <?= ($selected_tipe == 'motor') ? 'active' : '' ?>" href="?tipe=motor&area=<?= $selected_area ?>&start_date=<?= $start_date ?>&end_date=<?= $end_date ?>">Motor</a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?= ($selected_tipe == 'mobil') ? 'active' : '' ?>" href="?tipe=mobil&area=<?= $selected_area ?>&start_date=<?= $start_date ?>&end_date=<?= $end_date ?>">Mobil</a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?= ($selected_tipe == 'semua') ? 'active' : '' ?>" href="?tipe=semua&area=<?= $selected_area ?>&start_date=<?= $start_date ?>&end_date=<?= $end_date ?>">Semua</a>
            </li>
        </ul>

        <form method="GET" class="row g-3 mb-4">
            <input type="hidden" name="tipe" value="<?= $selected_tipe ?>">
            <div class="col-md-3">
                <label>Filter Area:</label>
                <select name="area" class="form-select">
                    <option value="0">Semua Area</option>
                    <?php $area_list->data_seek(0);
                    while ($ar = $area_list->fetch_assoc()): ?>
                        <option value="<?= $ar['id_area'] ?>" <?= ($selected_area == $ar['id_area']) ? 'selected' : '' ?>>
                            <?= $ar['nama_area'] ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label>Dari Tanggal:</label>
                <input type="date" name="start_date" class="form-control" value="<?= $raw_start ?>">
            </div>
            <div class="col-md-3">
                <label>Sampai Tanggal:</label>
                <input type="date" name="end_date" class="form-control" value="<?= $raw_end ?>">
            </div>
            <div class="col-md-3 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">Terapkan</button>
            </div>
        </form>

        <div class="mb-4">
            <canvas id="chartKendaraan"></canvas>
        </div>

        <div class="mb-3">
            <strong>Total Motor:</strong> <?= $total_motor ?> |
            <strong>Total Mobil:</strong> <?= $total_mobil ?> |
            <strong>Total Semua:</strong> <?= $total_semua ?>
        </div>

        <div class="mb-3 d-flex justify-content-end gap-2">
            <a href="#" class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#modalTambahArea">+ Tambah Area</a>
            <a href="per_reguler.php" class="btn btn-primary btn-sm">Per Reguler</a>
            <a href="#" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#modalTambahKendaraan">+ Tambah Kendaraan</a>
            <a href="cetak_pdf.php?tipe=<?= $selected_tipe ?>&area=<?= $selected_area ?>&start_date=<?= $start_date ?>&end_date=<?= $end_date ?>" class="btn btn-outline-secondary" target="_blank">Cetak PDF</a>
            <a href="logout.php" class="btn btn-outline-danger btn-sm">Logout</a>
        </div>

        <table class="table table-bordered table-striped">
            <thead class="table-dark text-center">
                <tr>
                    <th>No</th>
                    <th>Reguler</th>
                    <th>Merek</th>
                    <th>Tipe</th>
                    <th>Area</th>
                    <th>Jumlah</th>
                    <th>Kontrol</th>
                    <th>User</th>
                    <th>Tanggal Input</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $sql = "SELECT k.id, k.merek, k.tipe, a.nama_area, r.nama_reguler, k.jumlah, u.username, k.date_created
                FROM tbl_kendaraan k
                JOIN tbl_area a ON k.id_area = a.id_area
                LEFT JOIN tbl_reguler r ON k.id_reguler = r.id_reguler
                LEFT JOIN tbl_user u ON k.id_user = u.id_user";
                $where = [];
                if ($selected_tipe != 'semua') {
                    $where[] = "k.tipe = '" . $conn->real_escape_string($selected_tipe) . "'";
                }
                if ($selected_area > 0) {
                    $where[] = "k.id_area = $selected_area";
                }
                if (!empty($start_date) && !empty($end_date)) {
                    $where[] = "k.date_created BETWEEN '" . $conn->real_escape_string($start_date) . "' AND '" . $conn->real_escape_string($end_date) . "'";
                }
                if (!empty($where)) {
                    $sql .= " WHERE " . implode(" AND ", $where);
                }
                $sql .= " ORDER BY k.date_created DESC";
                $res = $conn->query($sql);
                $no = 1;
                while ($row = $res->fetch_assoc()): ?>
                    <tr class="text-center">
                        <td><?= $no++ ?></td>
                        <td><?= $row['nama_reguler'] ?></td>
                        <td><?= htmlspecialchars($row['merek']) ?></td>
                        <td><?= ucfirst($row['tipe']) ?></td>
                        <td><?= htmlspecialchars($row['nama_area']) ?></td>
                        <td id="count-<?= $row['id']; ?>"><?= $row['jumlah']; ?></td>
                        <td>
                            <button class="btn btn-success btn-sm counter-btn" onclick="updateCount(<?= $row['id']; ?>, 'plus')">+</button>
                            <button class="btn btn-danger btn-sm counter-btn" onclick="updateCount(<?= $row['id']; ?>, 'minus')">-</button>
                        </td>
                        <td><?= htmlspecialchars($row['username'] ?? '-') ?></td>
                        <td><?= date('d-m-Y', strtotime($row['date_created'])) ?></td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>

    <!-- Modal Tambah Area -->
    <div class="modal fade" id="modalTambahArea" tabindex="-1">
        <div class="modal-dialog">
            <form id="formTambahArea">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Tambah Area</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="text" name="nama_area" class="form-control" placeholder="Nama Area" required>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success">Simpan</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal Tambah Kendaraan -->
    <div class="modal fade" id="modalTambahKendaraan" tabindex="-1">
        <div class="modal-dialog">
            <form action="tambah.php" method="POST">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Tambah Kendaraan</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="text" name="merek" class="form-control mb-2" placeholder="Merek Kendaraan" required>
                        <select name="tipe" class="form-select mb-2" required>
                            <option value="">-- Pilih Tipe --</option>
                            <option value="motor">Motor</option>
                            <option value="mobil">Mobil</option>
                        </select>
                        <select name="id_area" class="form-select mb-2" required>
                            <option value="">-- Pilih Area --</option>
                            <?php
                            $area = $conn->query("SELECT * FROM tbl_area ORDER BY nama_area");
                            while ($a = $area->fetch_assoc()): ?>
                                <option value="<?= $a['id_area'] ?>"><?= $a['nama_area'] ?></option>
                            <?php endwhile; ?>
                        </select>
                        <select name="id_reguler" class="form-select mb-2" required>
                            <option value="">-- Pilih Reguler --</option>
                            <?php
                            $reguler = $conn->query("SELECT * FROM tbl_reguler ORDER BY nama_reguler");
                            while ($r = $reguler->fetch_assoc()):
                            ?>
                                <option value="<?= $r['id_reguler']; ?>"><?= $r['nama_reguler']; ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Tambah</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        const ctx = document.getElementById('chartKendaraan').getContext('2d');
        const tipe = "<?= $selected_tipe ?>";

        let chartData = {};

        <?php
        // Ambil semua merek gabungan dan urutkan
        $motor_labels = array_column($data_motor, 'merek');
        $mobil_labels = array_column($data_mobil, 'merek');
        $all_labels = array_unique(array_merge($motor_labels, $mobil_labels));
        sort($all_labels);

        // Buat fungsi untuk mengambil jumlah berdasarkan label
        function getJumlah($label, $data)
        {
            foreach ($data as $d) {
                if ($d['merek'] === $label) return (int)$d['total'];
            }
            return 0;
        }

        $motor_data = [];
        $mobil_data = [];
        foreach ($all_labels as $label) {
            $motor_data[] = getJumlah($label, $data_motor);
            $mobil_data[] = getJumlah($label, $data_mobil);
        }
        ?>

        if (tipe === "motor") {
            chartData = {
                labels: <?= json_encode($motor_labels) ?>,
                datasets: [{
                    label: "Motor",
                    data: <?= json_encode(array_column($data_motor, 'total')) ?>,
                    backgroundColor: 'rgba(54, 162, 235, 0.6)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 1
                }]
            };
        } else if (tipe === "mobil") {
            chartData = {
                labels: <?= json_encode($mobil_labels) ?>,
                datasets: [{
                    label: "Mobil",
                    data: <?= json_encode(array_column($data_mobil, 'total')) ?>,
                    backgroundColor: 'rgba(255, 99, 132, 0.6)',
                    borderColor: 'rgba(255, 99, 132, 1)',
                    borderWidth: 1
                }]
            };
        } else {
            chartData = {
                labels: <?= json_encode($all_labels) ?>,
                datasets: [{
                        label: "Motor",
                        data: <?= json_encode($motor_data) ?>,
                        backgroundColor: 'rgba(54, 162, 235, 0.6)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    },
                    {
                        label: "Mobil",
                        data: <?= json_encode($mobil_data) ?>,
                        backgroundColor: 'rgba(255, 99, 132, 0.6)',
                        borderColor: 'rgba(255, 99, 132, 1)',
                        borderWidth: 1
                    }
                ]
            };
        }

        new Chart(ctx, {
            type: 'bar',
            data: chartData,
            options: {
                indexAxis: 'y',
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top'
                    }
                },
                scales: {
                    x: {
                        beginAtZero: true
                    },
                    y: {
                        ticks: {
                            align: 'center',
                            padding: 10
                        }
                    }
                }
            }
        });

        $('#formTambahArea').on('submit', function(e) {
            e.preventDefault();
            const nama_area = $('input[name="nama_area"]').val();
            $.post('tambah_area.php', {
                nama_area: nama_area
            }, function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.message);
                }
            }, 'json');
        });

        function updateCount(id, action) {
            fetch('update.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: `id=${id}&action=${action}`
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById(`count-${id}`).innerText = data.new_count;
                    } else {
                        alert(data.message);
                    }
                });
        }
    </script>
</body>

</html>