<?php
include 'indexapoteker.php';

// Query untuk mutasi stok hari ini
$queryMutasiHariIni = "SELECT 
    SUM(CASE WHEN tipe='MASUK' THEN jumlah ELSE 0 END) as total_masuk,
    SUM(CASE WHEN tipe='KELUAR' THEN jumlah ELSE 0 END) as total_keluar
    FROM mutasi_stok 
    WHERE DATE(tanggal) = CURDATE()";
    
$resultMutasiHariIni = mysqli_query($conn, $queryMutasiHariIni);
if (!$resultMutasiHariIni) {
    echo "<!-- Mutasi Error: " . mysqli_error($conn) . " -->\n";
    $mutasiMasuk = 0;
    $mutasiKeluar = 0;
} else {
    $mutasiData = mysqli_fetch_assoc($resultMutasiHariIni);
    $mutasiMasuk = $mutasiData['total_masuk'] ?? 0;
    $mutasiKeluar = $mutasiData['total_keluar'] ?? 0;
}

// Query untuk total stok semua obat
$queryTotalStok = "SELECT 
    COUNT(DISTINCT id_obat) as total_jenis_obat,
    COALESCE(SUM(jumlah), 0) as total_unit_stok
    FROM stok";

$resultTotalStok = mysqli_query($conn, $queryTotalStok);
if (!$resultTotalStok) {
    $totalJenisObat = 0;
    $totalUnitStok = 0;
} else {
    $totalData = mysqli_fetch_assoc($resultTotalStok);
    $totalJenisObat = $totalData['total_jenis_obat'] ?? 0;
    $totalUnitStok = $totalData['total_unit_stok'] ?? 0;
}

// Query untuk mutasi stok 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 = [];
if ($resultMutasi) {
    while($row = mysqli_fetch_assoc($resultMutasi)) {
        $dataMutasi[] = $row;
    }
} else {
    echo "<!-- Mutasi 7 Days Error: " . mysqli_error($conn) . " -->\n";
}

// Query untuk distribusi stok per gudang
$queryStokGudang = "SELECT 
    g.nama_gudang,
    COUNT(DISTINCT s.id_obat) as jumlah_obat,
    COALESCE(SUM(s.jumlah), 0) as total_stok
    FROM gudang g
    LEFT JOIN stok s ON g.id_gudang = s.id_gudang
    GROUP BY g.id_gudang, g.nama_gudang
    ORDER BY total_stok DESC";
    
$resultStokGudang = mysqli_query($conn, $queryStokGudang);
$dataStokGudang = [];
if ($resultStokGudang) {
    while($row = mysqli_fetch_assoc($resultStokGudang)) {
        $dataStokGudang[] = $row;
    }
} else {
    echo "<!-- Gudang Error: " . mysqli_error($conn) . " -->\n";
}
?>

<div class="pc-container">
    <div class="pc-content">
        <!-- Header Welcome -->
        <div class="card">
            <div class="row">
                <div class="col-md-6 p-5">
                    <img src="assets/images/petugas.svg" alt="Admin Illustration" class="img-fluid">
                </div>
                <div class="col-md-6 d-flex align-items-center">
                    <div>
                        <h4>Selamat Datang di Stockify, Petugas <?= $_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 membantu Anda mengelola mutasi stok dan distribusi obat di gudang
                        </p>
                        <div class="mt-3">
                            <a href="pengeluaranapoteker.php" class="btn btn-success me-2">
                                <i class="ti ti-adjustments-alt me-1"></i> Mutasi
                            </a>
                            <a href="stokapoteker.php" class="btn btn-info me-2">
                                <i class="ti ti-package me-1"></i> Stok
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h6 class="text-white mb-1 opacity-75">Mutasi Masuk Hari Ini</h6>
                                <h3 class="text-white mb-0"><?= number_format($mutasiMasuk) ?> <small>unit</small></h3>
                            </div>
                            <div class="avtar avtar-lg bg-light-success">
                                <i class="ti ti-arrow-down text-success" style="font-size: 1.5rem;"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-danger text-white">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h6 class="text-white mb-1 opacity-75">Mutasi Keluar Hari Ini</h6>
                                <h3 class="text-white mb-0"><?= number_format($mutasiKeluar) ?> <small>unit</small></h3>
                            </div>
                            <div class="avtar avtar-lg bg-light-danger">
                                <i class="ti ti-arrow-up text-danger" style="font-size: 1.5rem;"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h6 class="text-white mb-1 opacity-75">Total Jenis Obat</h6>
                                <h3 class="text-white mb-0"><?= $totalJenisObat ?> <small>jenis</small></h3>
                            </div>
                            <div class="avtar avtar-lg bg-light-info">
                                <i class="ti ti-inbox text-info" style="font-size: 1.5rem;"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h6 class="text-white mb-1 opacity-75">Total Unit Stok</h6>
                                <h3 class="text-white mb-0"><?= number_format($totalUnitStok) ?> <small>unit</small></h3>
                            </div>
                            <div class="avtar avtar-lg bg-light-warning">
                                <i class="ti ti-box text-warning" style="font-size: 1.5rem;"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <!-- Chart Mutasi Stok -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5>
                            <i class="ti ti-chart-bar me-2"></i>
                            Mutasi Stok (7 Hari Terakhir)
                        </h5>
                    </div>
                    <div class="card-body">
                        <div id="chartMutasiPetugas"></div>
                    </div>
                </div>
            </div>
            
            <!-- Chart Distribusi Stok per Gudang -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5>
                            <i class="ti ti-building-warehouse me-2"></i>
                            Distribusi Stok per Gudang
                        </h5>
                    </div>
                    <div class="card-body">
                        <div id="chartStokGudang"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Info Manajemen Stok -->
        <div class="row">
            <div class="col-12">
                <div class="card bg-light">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col-12">
                                <h6 class="mb-2">
                                    <i class="ti ti-check text-primary me-2"></i>
                                    Panduan Tugas Petugas Gudang
                                </h6>
                                <p class="mb-2 small">
                                    Sebagai petugas gudang, tugas Anda adalah mengelola mutasi stok dan distribusi obat. 
                                    Pastikan semua transaksi stok tercatat dengan baik dan stok selalu terpantau.
                                </p>
                                <div class="d-flex gap-4 mt-2">
                                    <div class="small">
                                        <strong>Mutasi Masuk:</strong> Penerimaan barang dari pembelian atau penyerahan
                                    </div>
                                    <div class="small">
                                        <strong>Mutasi Keluar:</strong> Pengeluaran barang untuk distribusi atau pemakaian
                                    </div>
                                    <div class="small">
                                        <strong>Monitoring Stok:</strong> Pastikan stok tidak jatuh di bawah safety stock
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

    // Destroy existing charts
    try {
        if (window.chartMutasiPetugas && typeof window.chartMutasiPetugas.destroy === 'function') {
            window.chartMutasiPetugas.destroy();
        }
        if (window.chartStokGudang && typeof window.chartStokGudang.destroy === 'function') {
            window.chartStokGudang.destroy();
        }
    } catch (e) {
        console.log('Error destroying charts:', e);
    }

    // Data dari PHP
    const dataMutasi = <?= json_encode($dataMutasi) ?>;
    const dataStokGudang = <?= json_encode($dataStokGudang) ?>;

    // 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: 320,
                toolbar: { show: false }
            },
            colors: ['#198754', '#dc3545'],
            plotOptions: {
                bar: {
                    horizontal: false,
                    columnWidth: '60%',
                    borderRadius: 6
                },
            },
            dataLabels: { 
                enabled: true,
                style: {
                    colors: ['#fff']
                }
            },
            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' });
                })
            },
            yaxis: {
                title: {
                    text: 'Jumlah (unit)'
                }
            },
            legend: { 
                position: 'top',
                horizontalAlign: 'right'
            },
            fill: { opacity: 1 },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " unit"
                    }
                }
            }
        };
        
        window.chartMutasiPetugas = new ApexCharts(document.querySelector("#chartMutasiPetugas"), optionsMutasi);
        window.chartMutasiPetugas.render();
    } else {
        document.querySelector("#chartMutasiPetugas").innerHTML = '<div class="text-center p-4 text-muted">Tidak ada data mutasi</div>';
    }

    // Chart Stok per Gudang - Donut Chart
    if (dataStokGudang && dataStokGudang.length > 0) {
        var optionsStokGudang = {
            series: dataStokGudang.map(d => parseInt(d.total_stok) || 0),
            chart: {
                type: 'donut',
                height: 320
            },
            labels: dataStokGudang.map(d => d.nama_gudang),
            colors: ['#0d6efd', '#198754', '#ffc107', '#fd7e14', '#dc3545'],
            legend: { 
                position: 'bottom',
                horizontalAlign: 'center'
            },
            plotOptions: {
                pie: {
                    donut: {
                        size: '65%',
                        labels: {
                            show: true,
                            name: {
                                show: true,
                                fontSize: '14px'
                            },
                            value: {
                                show: true,
                                fontSize: '20px',
                                fontWeight: 600,
                                formatter: function (val) {
                                    return val + ' unit'
                                }
                            },
                            total: {
                                show: true,
                                label: 'Total Stok',
                                fontSize: '14px',
                                fontWeight: 600,
                                formatter: function (w) {
                                    return dataStokGudang.reduce((sum, d) => sum + parseInt(d.total_stok || 0), 0) + ' unit';
                                }
                            }
                        }
                    }
                }
            },
            dataLabels: {
                enabled: true,
                formatter: function (val, opts) {
                    return Math.round(val) + '%'
                }
            },
            tooltip: {
                y: {
                    formatter: function (val, opts) {
                        const gudang = dataStokGudang[opts.seriesIndex];
                        return val + ' unit (' + gudang.jumlah_obat + ' jenis obat)';
                    }
                }
            }
        };
        
        window.chartStokGudang = new ApexCharts(document.querySelector("#chartStokGudang"), optionsStokGudang);
        window.chartStokGudang.render();
    } else {
        document.querySelector("#chartStokGudang").innerHTML = '<div class="text-center p-4 text-muted">Tidak ada data gudang</div>';
    }
}

// Initialize charts
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(initPetugasCharts, 500);
    });
} else {
    setTimeout(initPetugasCharts, 500);
}

// Re-render on resize
let resizeTimer;
window.addEventListener('resize', function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(initPetugasCharts, 300);
});
</script>

<?php include 'footer.php' ?>