<?php
include 'indexapoteker.php';

$queryEOQAlert = "SELECT 
    o.id_obat,
    o.nama_obat,
    o.satuan,
    o.lead_time_hari as lead_time,
    e.eoq,
    e.safety_stock,
    (SELECT COALESCE(SUM(jumlah), 0) FROM stok WHERE id_obat = o.id_obat) as stok_saat_ini
    FROM obat o
    LEFT JOIN eoq e ON o.id_obat = e.id_obat
    WHERE e.eoq IS NOT NULL 
    AND e.safety_stock IS NOT NULL
    AND (SELECT COALESCE(SUM(jumlah), 0) FROM stok WHERE id_obat = o.id_obat) <= e.safety_stock
    -- Filter: Jangan tampilkan jika sudah ada pembelian APPROVED atau RECEIVED
    AND o.id_obat NOT IN (
        SELECT DISTINCT pd.id_obat
        FROM pembelian_detail pd
        JOIN pembelian p ON pd.id_pembelian = p.id_pembelian
        WHERE p.status IN ('APPROVED', 'RECEIVED')
        AND DATE(p.tanggal_pembelian) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    )
    HAVING stok_saat_ini <= safety_stock
    ORDER BY (safety_stock - stok_saat_ini) DESC
    LIMIT 10";

$resultEOQAlert = mysqli_query($conn, $queryEOQAlert);

if (!$resultEOQAlert) {
    echo "<!-- Error: " . mysqli_error($conn) . " -->\n";
    $dataEOQAlert = [];
} else {
    $dataEOQAlert = [];
    while($row = mysqli_fetch_assoc($resultEOQAlert)) {
        $dataEOQAlert[] = $row;
    }
}

$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 pembelian pending approval
$queryPendingPembelian = "SELECT COUNT(*) as total 
                          FROM pembelian 
                          WHERE status = 'DRAFT'";
$resultPending = mysqli_query($conn, $queryPendingPembelian);
if (!$resultPending) {
    echo "<!-- Pending Error: " . mysqli_error($conn) . " -->\n";
    $totalPending = 0;
} else {
    $pendingData = mysqli_fetch_assoc($resultPending);
    $totalPending = $pendingData['total'] ?? 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">
        <div class="card">
            <div class="row">
                <div class="col-md-6 p-5">
                    <img src="assets/images/apoteker.svg" alt="Admin Illustration" class="img-fluid">
                </div>
                <div class="col-md-6 d-flex align-items-center">
                    <div>
                        <h4>Selamat Datang di Stockify, Apoteker <?= $_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 membuat pembelian berdasarkan perhitungan EOQ
                        </p>
                        <div class="mt-3">
                            <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>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-4">
                <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-4">
                <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-4">
                <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">Pembelian Pending</h6>
                                <h3 class="text-white mb-0"><?= $totalPending ?> <small>order</small></h3>
                            </div>
                            <div class="avtar avtar-lg bg-light-warning">
                                <i class="ti ti-clock text-warning" style="font-size: 1.5rem;"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Alert EOQ -->
        <?php if(count($dataEOQAlert) > 0): ?>
        <div class="row">
            <div class="col-12">
                <div class="card border-danger">
                    <div class="card-header bg-danger text-white">
                        <h5 class="mb-0">
                            <i class="ti ti-alert-triangle me-2"></i>
                            Perhatian! Obat Perlu Dipesan (<?= count($dataEOQAlert) ?> item)
                        </h5>
                    </div>
                    <div class="card-body">
                        <p class="text-muted mb-3">
                            <i class="ti ti-info-circle me-1"></i>
                            Berikut obat yang stoknya sudah mencapai atau di bawah safety stock berdasarkan perhitungan EOQ:
                        </p>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>No</th>
                                        <th>Nama Obat</th>
                                        <th>Stok Saat Ini</th>
                                        <th>Safety Stock</th>
                                        <th>Jumlah EOQ</th>
                                        <th>Lead Time</th>
                                        <th>Status</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $no = 1; foreach($dataEOQAlert as $item): ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><strong><?= htmlspecialchars($item['nama_obat']) ?></strong></td>
                                        <td>
                                            <span class="badge bg-danger">
                                                <?= number_format($item['stok_saat_ini']) ?> <?= $item['satuan'] ?>
                                            </span>
                                        </td>
                                        <td><?= number_format($item['safety_stock']) ?> <?= $item['satuan'] ?></td>
                                        <td>
                                            <span class="badge bg-primary">
                                                <?= number_format($item['eoq']) ?> <?= $item['satuan'] ?>
                                            </span>
                                        </td>
                                        <td><?= $item['lead_time'] ?> hari</td>
                                        <td>
                                            <?php 
                                            $selisih = $item['safety_stock'] - $item['stok_saat_ini'];
                                            if($selisih >= ($item['eoq']/2)): ?>
                                                <span class="badge bg-danger">Kritis</span>
                                            <?php else: ?>
                                                <span class="badge bg-warning">Perlu Pesan</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a href="pembelianapoteker.php?action=create&id_obat=<?= $item['id_obat'] ?>&qty=<?= $item['eoq'] ?>" 
                                               class="btn btn-sm btn-primary">
                                                <i class="ti ti-shopping-cart"></i> Pesan
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="alert alert-info mt-3 mb-0">
                            <i class="ti ti-bulb me-2"></i>
                            <strong>Tips:</strong> Segera buat pembelian untuk obat-obat di atas agar tidak kehabisan stok. 
                            Jumlah EOQ sudah dihitung optimal untuk meminimalkan biaya.
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php else: ?>
        <div class="row">
            <div class="col-12">
                <div class="alert alert-success" role="alert">
                    <h5 class="alert-heading">
                        <i class="ti ti-circle-check me-2"></i>
                        Stok Aman!
                    </h5>
                    <p class="mb-0">
                        Saat ini tidak ada obat yang perlu dipesan. Semua stok masih di atas safety stock.
                    </p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Charts Section -->
        <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="chartMutasiApoteker"></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 EOQ -->
        <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-info-circle text-primary me-2"></i>
                                    Tentang Economic Order Quantity (EOQ)
                                </h6>
                                <p class="mb-2 small">
                                    EOQ adalah jumlah pemesanan optimal yang meminimalkan total biaya persediaan. 
                                    Sistem menghitung EOQ berdasarkan permintaan tahunan, biaya pemesanan, dan biaya penyimpanan.
                                </p>
                                <div class="d-flex gap-4 mt-2">
                                    <div class="small">
                                        <strong>Rumus:</strong> EOQ = √[(2 × D × S) / H]
                                    </div>
                                    <div class="small">
                                        <strong>Safety Stock:</strong> Stok cadangan untuk mencegah kehabisan
                                    </div>
                                    <div class="small">
                                        <strong>Lead Time:</strong> Waktu tunggu dari pemesanan hingga barang datang
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
// JavaScript chart code tetap sama seperti sebelumnya
function initApotekerCharts() {
    if (typeof ApexCharts === 'undefined') {
        console.error('ApexCharts tidak ditemukan!');
        return;
    }

    // Destroy existing charts
    try {
        if (window.chartMutasiApoteker && typeof window.chartMutasiApoteker.destroy === 'function') {
            window.chartMutasiApoteker.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.chartMutasiApoteker = new ApexCharts(document.querySelector("#chartMutasiApoteker"), optionsMutasi);
        window.chartMutasiApoteker.render();
    } else {
        document.querySelector("#chartMutasiApoteker").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(initApotekerCharts, 500);
    });
} else {
    setTimeout(initApotekerCharts, 500);
}

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

<?php include 'footer.php' ?>