<?php
include 'indexapoteker.php';

// Query untuk total obat
$queryTotalObat = "SELECT COUNT(*) AS total FROM obat";
$resultTotalObat = mysqli_fetch_assoc(mysqli_query($conn, $queryTotalObat));
$totalObat = $resultTotalObat['total'] ?? 0;

// Query untuk total pembelian
$queryTotalPembelian = "SELECT COUNT(*) AS total FROM pembelian";
$resultTotalPembelian = mysqli_fetch_assoc(mysqli_query($conn, $queryTotalPembelian));
$totalPembelian = $resultTotalPembelian['total'] ?? 0;

// Query untuk total supplier
$queryTotalSupplier = "SELECT COUNT(*) AS total FROM supplier";
$resultTotalSupplier = mysqli_fetch_assoc(mysqli_query($conn, $queryTotalSupplier));
$totalSupplier = $resultTotalSupplier['total'] ?? 0;

// Query untuk total gudang
$queryTotalGudang = "SELECT COUNT(*) AS total FROM gudang";
$resultTotalGudang = mysqli_fetch_assoc(mysqli_query($conn, $queryTotalGudang));
$totalGudang = $resultTotalGudang['total'] ?? 0;

// Query untuk data chart pembelian per bulan (6 bulan terakhir)
$queryChartPembelian = "SELECT 
    DATE_FORMAT(tanggal_pembelian, '%b %Y') as bulan,
    COUNT(*) as total
    FROM pembelian 
    WHERE tanggal_pembelian >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
    GROUP BY MONTH(tanggal_pembelian), YEAR(tanggal_pembelian)
    ORDER BY tanggal_pembelian ASC";
$resultChartPembelian = mysqli_query($conn, $queryChartPembelian);
$dataPembelian = [];
while($row = mysqli_fetch_assoc($resultChartPembelian)) {
    $dataPembelian[] = $row;
}

// Query untuk top 5 obat dengan stok terbanyak
$queryTopObat = "SELECT o.nama_obat, COALESCE(SUM(s.jumlah), 0) as total_stok
                 FROM obat o
                 LEFT JOIN stok s ON o.id_obat = s.id_obat
                 GROUP BY o.id_obat
                 ORDER BY total_stok DESC
                 LIMIT 5";
$resultTopObat = mysqli_query($conn, $queryTopObat);
$dataTopObat = [];
while($row = mysqli_fetch_assoc($resultTopObat)) {
    $dataTopObat[] = $row;
}

// Query untuk mutasi stok per tipe (7 hari terakhir)
$queryMutasi = "SELECT 
    DATE(tanggal) as tanggal,
    SUM(CASE WHEN tipe='MASUK' THEN jumlah ELSE 0 END) as masuk,
    SUM(CASE WHEN tipe='KELUAR' THEN jumlah ELSE 0 END) as keluar
    FROM mutasi_stok 
    WHERE tanggal >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    GROUP BY DATE(tanggal)
    ORDER BY tanggal ASC";
$resultMutasi = mysqli_query($conn, $queryMutasi);
$dataMutasi = [];
while($row = mysqli_fetch_assoc($resultMutasi)) {
    $dataMutasi[] = $row;
}

// Query untuk status pembelian
$queryStatusPembelian = "SELECT status, COUNT(*) as total 
                         FROM pembelian 
                         GROUP BY status";
$resultStatusPembelian = mysqli_query($conn, $queryStatusPembelian);
$dataStatusPembelian = [];
while($row = mysqli_fetch_assoc($resultStatusPembelian)) {
    $dataStatusPembelian[] = $row;
}
?>
<div class="pc-container">
    <div class="pc-content">
        <div class="row">
            <div class="col-xl-3 col-md-6">
                <div class="card bg-primary-dark dashnum-card text-white overflow-hidden">
                    <span class="round small"></span>
                    <span class="round big"></span>
                    <div class="card-body">
                        <div class="row">
                            <div class="col">
                                <div class="avtar avtar-lg">
                                    <i class="text-white ti ti-pill"></i>
                                </div>
                            </div>
                        </div>
                        <span class="text-white d-block f-34 f-w-500 my-2"><?= $totalObat ?> <i class="ti ti-arrow-up-right-circle opacity-50"></i></span>
                        <p class="mb-0 opacity-50">Total Obat</p>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6">
                <div class="card bg-primary-dark dashnum-card text-white overflow-hidden">
                    <span class="round small"></span>
                    <span class="round big"></span>
                    <div class="card-body">
                        <div class="row">
                            <div class="col">
                                <div class="avtar avtar-lg">
                                    <i class="text-white ti ti-shopping-cart"></i>
                                </div>
                            </div>
                        </div>
                        <span class="text-white d-block f-34 f-w-500 my-2"><?= $totalPembelian ?> <i class="ti ti-arrow-up-right-circle opacity-50"></i></span>
                        <p class="mb-0 opacity-50">Total Pembelian</p>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6">
                <div class="card bg-primary-dark dashnum-card text-white overflow-hidden">
                    <span class="round small"></span>
                    <span class="round big"></span>
                    <div class="card-body">
                        <div class="row">
                            <div class="col">
                                <div class="avtar avtar-lg">
                                    <i class="text-white ti ti-building-store"></i>
                                </div>
                            </div>
                        </div>
                        <span class="text-white d-block f-34 f-w-500 my-2"><?= $totalSupplier ?> <i class="ti ti-arrow-up-right-circle opacity-50"></i></span>
                        <p class="mb-0 opacity-50">Total Supplier</p>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6">
                <div class="card bg-primary-dark dashnum-card text-white overflow-hidden">
                    <span class="round small"></span>
                    <span class="round big"></span>
                    <div class="card-body">
                        <div class="row">
                            <div class="col">
                                <div class="avtar avtar-lg">
                                    <i class="text-white ti ti-building-warehouse"></i>
                                </div>
                            </div>
                        </div>
                        <span class="text-white d-block f-34 f-w-500 my-2"><?= $totalGudang ?> <i class="ti ti-arrow-up-right-circle opacity-50"></i></span>
                        <p class="mb-0 opacity-50">Total Gudang</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="card">
            <div class="row">
                <div class="col-md-6 p-5">
                    <img src="assets/images/kepala.svg" alt="Admin Illustration" class="img-fluid">
                </div>
                <div class="col-md-6 d-flex align-items-center">
                    <div>
                        <h4>Selamat Datang di Stockify, Kepala Puskesmas <?= $_SESSION['username'] ?>!</h4>
                        <p>
                            Stockify adalah Sistem Informasi Ketersediaan Obat yang membantu Anda mengelola 
                            stok obat, pembelian, dan distribusi dengan mudah dan efisien.
                        </p>
                        <p>
                            Dashboard ini memberikan gambaran lengkap tentang kondisi persediaan obat, 
                            termasuk monitoring stok, pembelian, supplier, dan gudang. 
                            Gunakan menu navigasi untuk mengelola data lebih lanjut.
                        </p>
                        <div class="mt-3">
                            <a href="obatapoteker.php" class="btn btn-primary me-2">
                                <i class="ti ti-pill me-1"></i> Obat
                            </a>
                            <a href="pembelianapoteker.php" class="btn btn-success me-2">
                                <i class="ti ti-shopping-cart me-1"></i> Pembelian
                            </a>
                            <a href="stokapoteker.php" class="btn btn-info me-2">
                                <i class="ti ti-package me-1"></i> Stok
                            </a>
                            <a href="supplierapoteker.php" class="btn btn-warning">
                                <i class="ti ti-building-store me-1"></i> Supplier
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- EOQ Explanation Card -->
        <div class="card">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-12">
                        <h5 class="mb-3">
                            <i class="ti ti-info-circle text-primary me-2"></i>
                            Apa itu EOQ (Economic Order Quantity)?
                        </h5>
                        <p class="mb-2">
                            <strong>EOQ (Economic Order Quantity)</strong> adalah metode untuk menentukan jumlah pemesanan obat yang paling ekonomis, 
                            dengan meminimalkan total biaya pemesanan dan biaya penyimpanan persediaan.
                        </p>
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <div class="bg-white p-3 rounded shadow-sm">
                                    <h6 class="text-primary mb-2">
                                        <i class="ti ti-formula me-1"></i>
                                        Rumus EOQ:
                                    </h6>
                                    <div class="text-center my-3">
                                        <div class="bg-primary-light p-3 rounded" style="display: inline-block;">
                                            <span style="font-size: 1.2rem; font-weight: 600;">
                                                EOQ = √[(2 × D × S) / H]
                                            </span>
                                        </div>
                                    </div>
                                    <div class="mt-3 small">
                                        <div class="mb-1"><strong>D</strong> = Permintaan tahunan (unit/tahun)</div>
                                        <div class="mb-1"><strong>S</strong> = Biaya pemesanan per pesanan (Rp)</div>
                                        <div class="mb-1"><strong>H</strong> = Biaya penyimpanan per unit per tahun (Rp)</div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="bg-white p-3 rounded shadow-sm">
                                    <h6 class="text-success mb-2">
                                        <i class="ti ti-checks me-1"></i>
                                        Manfaat EOQ:
                                    </h6>
                                    <ul class="mb-0 small">
                                        <li class="mb-2">Mengoptimalkan jumlah pembelian obat</li>
                                        <li class="mb-2">Mengurangi biaya penyimpanan gudang</li>
                                        <li class="mb-2">Meminimalkan biaya pemesanan</li>
                                        <li class="mb-2">Mencegah kelebihan atau kekurangan stok</li>
                                        <li class="mb-0">Meningkatkan efisiensi cash flow</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="alert alert-primary mt-3 mb-0" role="alert">
                            <i class="ti ti-bulb me-2"></i>
                            <strong>Tips:</strong> Sistem Stockify dapat membantu Anda menghitung EOQ secara otomatis berdasarkan data historis pembelian dan stok obat Anda.
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>Trend Pembelian (6 Bulan Terakhir)</h5>
                    </div>
                    <div class="card-body">
                        <div id="myChartPembelian"></div>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>Status Pembelian</h5>
                    </div>
                    <div class="card-body">
                        <div id="myChartStatus"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5>Mutasi Stok (7 Hari Terakhir)</h5>
                    </div>
                    <div class="card-body">
                        <div id="myChartMutasi"></div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5>Top 5 Stok Obat</h5>
                    </div>
                    <div class="card-body">
                        <div id="myChartTopObat"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
function initMyCharts() {
    if (typeof ApexCharts === 'undefined') {
        console.error('ApexCharts library tidak ditemukan!');
        return;
    }

    // Cek apakah container ada
    const containers = ['#myChartPembelian', '#myChartStatus', '#myChartMutasi', '#myChartTopObat'];
    let allExists = true;
    containers.forEach(id => {
        if (!document.querySelector(id)) {
            console.error('Container ' + id + ' tidak ditemukan!');
            allExists = false;
        }
    });
    
    if (!allExists) return;

    // Destroy existing charts jika ada
    try {
        if (window.myChartPembelian && typeof window.myChartPembelian.destroy === 'function') {
            window.myChartPembelian.destroy();
        }
        if (window.myChartStatus && typeof window.myChartStatus.destroy === 'function') {
            window.myChartStatus.destroy();
        }
        if (window.myChartMutasi && typeof window.myChartMutasi.destroy === 'function') {
            window.myChartMutasi.destroy();
        }
        if (window.myChartTopObat && typeof window.myChartTopObat.destroy === 'function') {
            window.myChartTopObat.destroy();
        }
    } catch (e) {
        console.log('Error destroying charts:', e);
    }

    // Data dari PHP
    const dataPembelian = <?= json_encode($dataPembelian) ?>;
    const dataStatusPembelian = <?= json_encode($dataStatusPembelian) ?>;
    const dataMutasi = <?= json_encode($dataMutasi) ?>;
    const dataTopObat = <?= json_encode($dataTopObat) ?>;

    console.log('Data Pembelian:', dataPembelian);
    console.log('Data Status:', dataStatusPembelian);
    console.log('Data Mutasi:', dataMutasi);
    console.log('Data Top Obat:', dataTopObat);

    // Chart Pembelian - Area Chart
    if (dataPembelian && dataPembelian.length > 0) {
        var optionsPembelian = {
            series: [{
                name: 'Pembelian',
                data: dataPembelian.map(d => parseInt(d.total) || 0)
            }],
            chart: {
                type: 'area',
                height: 300,
                toolbar: { show: false },
                animations: { enabled: true }
            },
            colors: ['#0d6efd'],
            dataLabels: { enabled: false },
            stroke: {
                curve: 'smooth',
                width: 3
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.7,
                    opacityTo: 0.3,
                }
            },
            xaxis: {
                categories: dataPembelian.map(d => d.bulan)
            },
            tooltip: { theme: 'light' }
        };
        
        try {
            window.myChartPembelian = new ApexCharts(document.querySelector("#myChartPembelian"), optionsPembelian);
            window.myChartPembelian.render();
            console.log('Chart Pembelian berhasil di-render');
        } catch (e) {
            console.error('Error render Chart Pembelian:', e);
        }
    } else {
        document.querySelector("#myChartPembelian").innerHTML = '<div class="text-center p-4 text-muted">Tidak ada data pembelian</div>';
    }

    // Chart Status Pembelian - Donut Chart
    if (dataStatusPembelian && dataStatusPembelian.length > 0) {
        var optionsStatusPembelian = {
            series: dataStatusPembelian.map(d => parseInt(d.total) || 0),
            chart: {
                type: 'donut',
                height: 300
            },
            labels: dataStatusPembelian.map(d => d.status),
            colors: ['#6c757d', '#0d6efd', '#198754', '#dc3545'],
            legend: { position: 'bottom' },
            plotOptions: {
                pie: {
                    donut: {
                        size: '70%',
                        labels: {
                            show: true,
                            total: {
                                show: true,
                                label: 'Total',
                                fontSize: '16px',
                                fontWeight: 600
                            }
                        }
                    }
                }
            }
        };
        
        try {
            window.myChartStatus = new ApexCharts(document.querySelector("#myChartStatus"), optionsStatusPembelian);
            window.myChartStatus.render();
            console.log('Chart Status berhasil di-render');
        } catch (e) {
            console.error('Error render Chart Status:', e);
        }
    } else {
        document.querySelector("#myChartStatus").innerHTML = '<div class="text-center p-4 text-muted">Tidak ada data status</div>';
    }

    // Chart Mutasi Stok - Bar Chart
    if (dataMutasi && dataMutasi.length > 0) {
        var optionsMutasi = {
            series: [{
                name: 'Masuk',
                data: dataMutasi.map(d => parseInt(d.masuk) || 0)
            }, {
                name: 'Keluar',
                data: dataMutasi.map(d => parseInt(d.keluar) || 0)
            }],
            chart: {
                type: 'bar',
                height: 300,
                toolbar: { show: false }
            },
            colors: ['#198754', '#dc3545'],
            plotOptions: {
                bar: {
                    horizontal: false,
                    columnWidth: '55%',
                    borderRadius: 4
                },
            },
            dataLabels: { enabled: false },
            stroke: {
                show: true,
                width: 2,
                colors: ['transparent']
            },
            xaxis: {
                categories: dataMutasi.map(d => {
                    const date = new Date(d.tanggal);
                    return date.toLocaleDateString('id-ID', { day: '2-digit', month: 'short' });
                })
            },
            legend: { position: 'top' },
            fill: { opacity: 1 }
        };
        
        try {
            window.myChartMutasi = new ApexCharts(document.querySelector("#myChartMutasi"), optionsMutasi);
            window.myChartMutasi.render();
            console.log('Chart Mutasi berhasil di-render');
        } catch (e) {
            console.error('Error render Chart Mutasi:', e);
        }
    } else {
        document.querySelector("#myChartMutasi").innerHTML = '<div class="text-center p-4 text-muted">Tidak ada data mutasi</div>';
    }

    // Chart Top Obat - Radial Bar
    if (dataTopObat && dataTopObat.length > 0) {
        const maxStok = Math.max(...dataTopObat.map(d => parseInt(d.total_stok) || 0));
        
        var optionsTopObat = {
            series: dataTopObat.map(d => {
                const stok = parseInt(d.total_stok) || 0;
                return maxStok > 0 ? Math.round((stok / maxStok) * 100) : 0;
            }),
            chart: {
                height: 320,
                type: 'radialBar',
            },
            colors: ['#0d6efd', '#198754', '#ffc107', '#fd7e14', '#dc3545'],
            plotOptions: {
                radialBar: {
                    dataLabels: {
                        name: { fontSize: '14px' },
                        value: {
                            fontSize: '12px',
                            formatter: function(val, opts) {
                                const stok = dataTopObat[opts.seriesIndex].total_stok;
                                return stok + ' unit';
                            }
                        },
                        total: {
                            show: true,
                            label: 'Total',
                            formatter: function (w) {
                                return dataTopObat.reduce((sum, d) => sum + parseInt(d.total_stok || 0), 0);
                            }
                        }
                    }
                }
            },
            labels: dataTopObat.map(d => {
                const nama = d.nama_obat;
                return nama.length > 15 ? nama.substring(0, 15) + '...' : nama;
            }),
            legend: { show: false }
        };
        
        try {
            window.myChartTopObat = new ApexCharts(document.querySelector("#myChartTopObat"), optionsTopObat);
            window.myChartTopObat.render();
            console.log('Chart Top Obat berhasil di-render');
        } catch (e) {
            console.error('Error render Chart Top Obat:', e);
        }
    } else {
        document.querySelector("#myChartTopObat").innerHTML = '<div class="text-center p-4 text-muted">Tidak ada data stok</div>';
    }
}

// Tunggu hingga semua resource loaded
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(initMyCharts, 500);
    });
} else {
    setTimeout(initMyCharts, 500);
}

// Re-render saat resize
let resizeTimer;
window.addEventListener('resize', function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(initMyCharts, 300);
});

// Observer untuk sidebar toggle
const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.attributeName === 'class') {
            setTimeout(initMyCharts, 300);
        }
    });
});

if (document.body) {
    observer.observe(document.body, { attributes: true, attributeFilter: ['class'] });
}
</script>

<?php include 'footer.php' ?>