<?php
require_once 'config/database.php';
require_once 'includes/auth.php';

// Cek akses (hanya memberi peringatan jika belum login)
//check_access();

// Hitung total data
$total_barang = $conn->query("SELECT COUNT(*) as total FROM pdta_inventaris_barang")->fetch_assoc()['total'];
$total_jenis = $conn->query("SELECT COUNT(*) as total FROM pdta_jenis_barang")->fetch_assoc()['total'];
$total_lokasi = $conn->query("SELECT COUNT(*) as total FROM pdta_lokasi")->fetch_assoc()['total'];
$total_pengguna = $conn->query("SELECT COUNT(*) as total FROM pdta_pengguna")->fetch_assoc()['total'];

// Ambil data statistik kondisi barang
$kondisi_stats = $conn->query("
    SELECT 
        SUM(CASE WHEN kondisi = 'Baik' THEN 1 ELSE 0 END) as baik,
        SUM(CASE WHEN kondisi = 'Rusak Ringan' THEN 1 ELSE 0 END) as rusak_ringan,
        SUM(CASE WHEN kondisi = 'Rusak Berat' THEN 1 ELSE 0 END) as rusak_berat
    FROM pdta_inventaris_barang
")->fetch_assoc();

// Ambil data barang terbaru
$barang_terbaru = $conn->query("
    SELECT ib.*, jb.nama_jenis, l.nama_lokasi 
    FROM pdta_inventaris_barang ib
    JOIN pdta_jenis_barang jb ON ib.id_jenis = jb.id_jenis
    JOIN pdta_lokasi l ON ib.id_lokasi = l.id_lokasi
    ORDER BY ib.created_at DESC LIMIT 5
");
?>

<?php include 'includes/header.php'; ?>
<?php include 'includes/navbar.php'; ?>

<div class="container mt-4">
    <h3 class="mb-4">Dashboard</h3>
    
    <?php display_flash_message(); ?>
    
    <!-- Bagian Card Statistik -->
    <div class="row mb-4">
        <!-- Card Total Barang -->
        <div class="col-md-3">
            <div class="card bg-primary text-white shadow">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="card-title">Total Barang</h5>
                            <h2 class="mb-0"><?= number_format($total_barang) ?></h2>
                        </div>
                        <i class="bi bi-box-seam" style="font-size: 2rem;"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Card Jenis Barang -->
        <div class="col-md-3">
            <div class="card bg-success text-white shadow">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="card-title">Jenis Barang</h5>
                            <h2 class="mb-0"><?= number_format($total_jenis) ?></h2>
                        </div>
                        <i class="bi bi-tags" style="font-size: 2rem;"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Card Lokasi -->
        <div class="col-md-3">
            <div class="card bg-info text-white shadow">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="card-title">Lokasi</h5>
                            <h2 class="mb-0"><?= number_format($total_lokasi) ?></h2>
                        </div>
                        <i class="bi bi-geo-alt" style="font-size: 2rem;"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Card Pengguna -->
        <div class="col-md-3">
            <div class="card bg-warning text-dark shadow">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="card-title">Pengguna</h5>
                            <h2 class="mb-0"><?= number_format($total_pengguna) ?></h2>
                        </div>
                        <i class="bi bi-people" style="font-size: 2rem;"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-8">
            <div class="card shadow mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">Barang Terbaru</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Kode Barang</th>
                                    <th>Nama Barang</th>
                                    <th>Jenis</th>
                                    <th>Lokasi</th>
                                    <th>Tanggal</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($row = $barang_terbaru->fetch_assoc()): ?>
                                <tr>
                                    <td><?= htmlspecialchars($row['kode_barang']) ?></td>
                                    <td><?= htmlspecialchars($row['nama_barang']) ?></td>
                                    <td><?= htmlspecialchars($row['nama_jenis']) ?></td>
                                    <td><?= htmlspecialchars($row['nama_lokasi']) ?></td>
                                    <td><?= date('d M Y', strtotime($row['created_at'])) ?></td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="text-end mt-3">
                        <a href="modules/inventaris/index.php" class="btn btn-primary">Lihat Semua Barang</a>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="card shadow">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">Statistik Kondisi Barang</h5>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height:250px; width:100%">
                        <canvas id="kondisiChart"></canvas>
                    </div>
                    <div class="chart-legend mt-3 text-center">
                        <ul class="list-inline mb-0">
                            <li class="list-inline-item me-3">
                                <span class="badge bg-success me-1"></span> Baik: <?= number_format($kondisi_stats['baik']) ?>
                            </li>
                            <li class="list-inline-item me-3">
                                <span class="badge bg-warning me-1"></span> Rusak Ringan: <?= number_format($kondisi_stats['rusak_ringan']) ?>
                            </li>
                            <li class="list-inline-item">
                                <span class="badge bg-danger me-1"></span> Rusak Berat: <?= number_format($kondisi_stats['rusak_berat']) ?>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Pastikan urutan loading script benar -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/chart.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Data untuk chart
    const chartData = {
        labels: ['Baik', 'Rusak Ringan', 'Rusak Berat'],
        datasets: [{
            data: [
                <?= $kondisi_stats['baik'] ?>,
                <?= $kondisi_stats['rusak_ringan'] ?>,
                <?= $kondisi_stats['rusak_berat'] ?>
            ],
            backgroundColor: [
                'rgba(40, 167, 69, 0.8)',
                'rgba(255, 193, 7, 0.8)',
                'rgba(220, 53, 69, 0.8)'
            ],
            borderColor: [
                'rgba(40, 167, 69, 1)',
                'rgba(255, 193, 7, 1)',
                'rgba(220, 53, 69, 1)'
            ],
            borderWidth: 1
        }]
    };

    // Konfigurasi chart
    const config = {
        type: 'doughnut',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        boxWidth: 12,
                        padding: 20,
                        usePointStyle: true
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.label || '';
                            let value = context.raw || 0;
                            let total = context.dataset.data.reduce((a, b) => a + b, 0);
                            let percentage = Math.round((value / total) * 100);
                            return `${label}: ${value} (${percentage}%)`;
                        }
                    }
                }
            },
            cutout: '70%'
        }
    };

    // Inisialisasi chart
    const ctx = document.getElementById('kondisiChart').getContext('2d');
    new Chart(ctx, config);
});
</script>

<?php include 'includes/footer.php'; ?>