<?php
include 'koneksi.php';
include 'auth.php'; // Cek login
include 'akses_ditolak.php'; // Tambahkan ini

// Ambil bulan filter dari GET, default bulan ini
$filter_bulan = isset($_GET['bulan']) ? $_GET['bulan'] : date('Y-m');

// Query data orderan sesuai filter bulan
$sql = "SELECT * FROM orders WHERE DATE_FORMAT(tanggal, '%Y-%m') = ? ORDER BY tanggal ASC";
$stmt = $koneksi->prepare($sql);
$stmt->bind_param("s", $filter_bulan);
$stmt->execute();
$result = $stmt->get_result();

// Hitung total orderan selama periode
$sql_total = "SELECT SUM(total_orderan) as total_orderan_bulan FROM orders WHERE DATE_FORMAT(tanggal, '%Y-%m') = ?";
$stmt_total = $koneksi->prepare($sql_total);
$stmt_total->bind_param("s", $filter_bulan);
$stmt_total->execute();
$res_total = $stmt_total->get_result();
$total_orderan_bulan = $res_total->fetch_assoc()['total_orderan_bulan'];
if (!$total_orderan_bulan)
    $total_orderan_bulan = 0;
?>

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

<head>
    <meta charset="UTF-8" />
    <title>Catatan Total Orderan Harian</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/admin.css">
    <link rel="stylesheet" href="css/navbar.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>

    <h4>TOTAL ORDERAN</h4>

    <!-- Filter Bulan (tanpa tombol submit) -->
    <div class="filter">
        <input type="month" id="bulan" name="bulan" value="<?= htmlspecialchars($filter_bulan) ?>" />
    </div>

    <!-- Tombol Tambah Orderan -->
    <div style="margin-top:10px;">
        <button id="tambahOrderanBtn">+ Tambah Orderan</button>
    </div>

    <!-- Total Orderan Bulan -->
    <div style="  color: #fed054;
margin-bottom: 10px; margin-top: 10px; font-size: 18px; text-align: center;" class="total">
        <strong>Total Orderan <?= date('F', strtotime($filter_bulan . '-01')) ?>: [ <?= $total_orderan_bulan ?>
            ]</strong>
    </div>

    <div class="table-container">
        <table>
            <thead style="position: sticky; top: 0; z-index: 1;">
                <tr>
                    <th>Tanggal</th>
                    <th>Orderan</th>
                    <th>Driver</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($result->num_rows > 0): ?>
                    <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= date('d M', strtotime($row['tanggal'])) ?></td>
                            <td><?= $row['total_orderan'] ?></td>
                            <td><?= htmlspecialchars($row['total_driver']) ?></td>
                            <td>
                                <button style="width:20px; height:20px;" class="btn-aksi" data-id="<?= $row['id'] ?>" data-tanggal="<?= $row['tanggal'] ?>"
                                    data-total="<?= $row['total_orderan'] ?>"
                                    data-driver="<?= htmlspecialchars($row['total_driver']) ?>"></button>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="4">Tidak ada data untuk bulan ini.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php include 'navbar4.php'; ?>

    <script>
        document.querySelectorAll('.btn-aksi').forEach(button => {
            button.addEventListener('click', () => {
                const id = button.dataset.id;
                const tanggal = button.dataset.tanggal;
                const total = button.dataset.total;
                const driver = button.dataset.driver;

                Swal.fire({
                    title: 'Pilih Aksi',
                    showCancelButton: true,
                    showDenyButton: true,
                    confirmButtonText: 'Edit',
                    denyButtonText: 'Hapus',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // === EDIT LOGIC ===
                        Swal.fire({
                            title: 'Edit Orderan',
                            html:
                                `<input type="date" id="edit-tanggal" class="swal2-input" value="${tanggal}">` +
                                `<input type="number" id="edit-total" class="swal2-input" placeholder="Total Orderan" value="${total}">` +
                                `<input type="text" id="edit-driver" class="swal2-input" placeholder="Driver" value="${driver}">`,
                            focusConfirm: false,
                            preConfirm: () => {
                                return {
                                    tanggal: document.getElementById('edit-tanggal').value,
                                    total_orderan: document.getElementById('edit-total').value,
                                    driver: document.getElementById('edit-driver').value
                                }
                            }
                        }).then((editResult) => {
                            if (editResult.isConfirmed) {
                                const data = {
                                    id: id,
                                    tanggal: editResult.value.tanggal,
                                    total_orderan: editResult.value.total_orderan,
                                    total_driver: editResult.value.driver
                                };

                                fetch('edit_orderan.php', {
                                    method: 'POST',
                                    headers: { 'Content-Type': 'application/json' },
                                    body: JSON.stringify(data)
                                })
                                    .then(response => response.json())
                                    .then(res => {
                                        if (res.success) {
                                            Swal.fire('Berhasil', 'Data orderan berhasil diupdate', 'success').then(() => {
                                                location.reload();
                                            });
                                        } else {
                                            Swal.fire('Gagal', res.message || 'Terjadi kesalahan saat update data', 'error');
                                        }
                                    })
                                    .catch(() => {
                                        Swal.fire('Gagal', 'Terjadi kesalahan jaringan', 'error');
                                    });
                            }
                        });
                    } else if (result.isDenied) {
                        // === DELETE LOGIC ===
                        Swal.fire({
                            title: 'Apakah Anda yakin?',
                            text: "Data orderan akan dihapus permanen!",
                            icon: 'warning',
                            showCancelButton: true,
                            confirmButtonText: 'Ya, hapus!',
                            cancelButtonText: 'Batal'
                        }).then((deleteConfirm) => {
                            if (deleteConfirm.isConfirmed) {
                                fetch('hapus_orderan.php', {
                                    method: 'POST',
                                    headers: { 'Content-Type': 'application/json' },
                                    body: JSON.stringify({ id: id })
                                })
                                    .then(response => response.json())
                                    .then(res => {
                                        if (res.success) {
                                            Swal.fire('Terhapus!', 'Data orderan berhasil dihapus.', 'success').then(() => {
                                                location.reload();
                                            });
                                        } else {
                                            Swal.fire('Gagal', res.message || 'Terjadi kesalahan saat menghapus data', 'error');
                                        }
                                    })
                                    .catch(() => {
                                        Swal.fire('Gagal', 'Terjadi kesalahan jaringan', 'error');
                                    });
                            }
                        });
                    }
                });
            });
        });

    </script>
<script>
    document.getElementById('tambahOrderanBtn').addEventListener('click', () => {
        Swal.fire({
            title: 'Tambah Orderan',
            html: `
                <input type="date" id="tanggal" class="swal2-input" placeholder="Tanggal">
                <input type="number" id="total_orderan" class="swal2-input" placeholder="Total Orderan">
                <input type="number" id="total_driver" class="swal2-input" placeholder="Total Driver">`,
            focusConfirm: false,
            preConfirm: () => {
                const tanggal = document.getElementById('tanggal').value;
                const total_orderan = document.getElementById('total_orderan').value;
                const total_driver = document.getElementById('total_driver').value;

                if (!tanggal || !total_orderan || !total_driver) {
                    Swal.showValidationMessage('Semua field wajib diisi!');
                    return false;
                }

                return {
                    tanggal,
                    total_orderan,
                    total_driver
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                fetch('tambah_orderan.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(result.value)
                })
                .then(response => response.json())
                .then(res => {
                    if (res.success) {
                        Swal.fire('Berhasil', 'Orderan berhasil ditambahkan!', 'success').then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Gagal', res.message || 'Gagal menambahkan orderan.', 'error');
                    }
                })
                .catch(() => {
                    Swal.fire('Error', 'Terjadi kesalahan jaringan.', 'error');
                });
            }
        });
    });
    
    document.getElementById('bulan').addEventListener('change', function() {
    const selected = this.value;
    window.location.href = `?bulan=${selected}`;
});
</script>

</body>

</html>