<?php  
require_once('includes/load.php');  
page_require_level(3);  
  
// Tangkap bulan dan tahun dari parameter GET, dengan default ke bulan dan tahun saat ini  
$month = isset($_GET['month']) ? intval($_GET['month']) : date('m');  
$year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');  
  
function calculate_material_consumption($month, $year) {  
    global $db;  
  
    $consumptions = [];  
  
    // Ambil data dari production_output termasuk part_number dan production_date  
    $sql_production = "SELECT id, part_number, quantity_produced, production_date FROM production_output  
                       WHERE MONTH(production_date) = '{$month}' AND YEAR(production_date) = '{$year}'";  
    $result_production = $db->query($sql_production);  
  
    if (!$result_production) return;  
  
    while ($row_production = $db->fetch_assoc($result_production)) {  
        $production_id = $row_production['id'];  
        $part_number = $db->escape($row_production['part_number']);  
        $quantity_produced = intval($row_production['quantity_produced']);  
        $production_date = $row_production['production_date'];  
  
        // Hitung kebutuhan komponen  
        $sql_bom = "SELECT child_bom, qty FROM bom_level WHERE parent_bom = '{$part_number}'";  
        $result_bom = $db->query($sql_bom);  
  
        if ($result_bom) {  
            while ($row_bom = $db->fetch_assoc($result_bom)) {  
                $component = $row_bom['child_bom'];  
                if ($component === 'cml-aquades') {  
                    continue; // Skip this component  
                }  
                $quantity_needed = $row_bom['qty'] * $quantity_produced; // Kebutuhan total berdasarkan jumlah produksi  
                $quantity_needed = number_format($quantity_needed, 1, '.', ''); // Format dengan 1 angka desimal  
  
                // Ambil informasi tambahan dari produk  
                $sql_product = "SELECT new_code, name, uom FROM products WHERE part_number = '{$component}'";  
                $result_product = $db->query($sql_product);  
                $product_info = $db->fetch_assoc($result_product);  
  
                $new_code = $product_info['new_code'];  
                $name = $product_info['name'];  
                $uom = $product_info['uom'];  
  
                // Simpan hasil perhitungan dalam array, termasuk part_number dan production_date  
                $consumptions[] = [  
                    'production_output_id' => $production_id,  
                    'part_number' => $part_number,  
                    'component' => $component,  
                    'new_code' => $new_code,  
                    'name' => $name,  
                    'uom' => $uom,  
                    'quantity' => $quantity_needed,  
                    'production_date' => $production_date // Tambahkan production_date di sini  
                ];  
            }  
        }  
    }  
  
    return $consumptions;  
}  
  
// Hitung konsumsi material  
$consumptions = calculate_material_consumption($month, $year);  
  
// Aggregate total quantity needed for each component  
$component_totals = [];  
foreach ($consumptions as $row) {  
    $component = $row['component'];  
    $uom = $row['uom'];  
    if (!isset($component_totals[$component])) {  
        $component_totals[$component] = [  
            'quantity' => 0,  
            'uom' => $uom // Store UOM  
        ];  
    }  
    $component_totals[$component]['quantity'] += $row['quantity'];  
}  
  
// Sort components by total quantity and get the top 10  
arsort($component_totals);  
$top_components = array_slice($component_totals, 0, 10, true);  
  
include_once('layouts/header.php');  
?>  
  
<div class="row">  
    <div class="col-md-12">  
        <!-- Formulir untuk memilih bulan dan tahun -->  
        <form action="consume_output_chart.php" method="get" class="form-inline">  
            <div class="form-group">  
                <label for="month">Month:</label>  
                <select name="month" id="month" class="form-control">  
                    <?php for ($m = 1; $m <= 12; $m++) : ?>  
                        <option value="<?php echo $m; ?>" <?php echo ($month == $m) ? 'selected' : ''; ?>>  
                            <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>  
                        </option>  
                    <?php endfor; ?>  
                </select>  
            </div>  
            <div class="form-group">  
                <label for="year">Year:</label>  
                <select name="year" id="year" class="form-control">  
                    <?php for ($y = date('Y'); $y >= 2000; $y--) : ?>  
                        <option value="<?php echo $y; ?>" <?php echo ($year == $y) ? 'selected' : ''; ?>>  
                            <?php echo $y; ?>  
                        </option>  
                    <?php endfor; ?>  
                </select>  
            </div>  
            <button type="submit" class="btn btn-primary">Filter</button>  
        </form>  
    </div>  
</div>  
  
<div class="row">  
    <div class="col-md-12">  
        <div class="panel panel-info">  
            <div class="panel-heading">Total Material Consumption Chart</div>  
            <div class="panel-body">  
                <canvas id="consumptionChart" width="400" height="200"></canvas>  
            </div>  
        </div>  
    </div>  
</div>  
  
<div class="row">  
    <div class="col-md-12">  
        <div class="panel panel-info">  
            <div class="panel-heading">Top 10 Components</div>  
            <div class="panel-body">  
                <table class="table table-bordered mt-3">  
                    <thead>  
                        <tr>  
                            <th>Component</th>  
                            <th>Total Quantity Needed</th>  
                            <th>UOM</th> <!-- Added UOM column -->  
                        </tr>  
                    </thead>  
                    <tbody>  
                        <?php if (!empty($top_components)) : ?>  
                            <?php foreach ($top_components as $component => $data) : ?>  
                                <tr>  
                                    <td><?php echo remove_junk($component); ?></td>  
                                    <td><?php echo number_format($data['quantity'], 1, '.', ','); ?></td> <!-- Format with thousands separator and 1 decimal -->  
                                    <td><?php echo remove_junk($data['uom']); ?></td> <!-- Display UOM -->  
                                </tr>  
                            <?php endforeach; ?>  
                        <?php else : ?>  
                            <tr>  
                                <td colspan="3">No data available for this month and year.</td>  
                            </tr>  
                        <?php endif; ?>  
                    </tbody>  
                </table>  
            </div>  
        </div>  
    </div>  
</div>  
  
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>  
<script>  
    // Data dari PHP  
    var componentData = <?php echo json_encode($top_components); ?>;  
  
    // Labels dan data untuk chart  
    var labels = Object.keys(componentData);  
    var data = Object.values(componentData).map(item => parseFloat(item.quantity)); // Get quantities for chart  
  
    // Konfigurasi chart  
    var config = {  
        type: 'bar',  
        data: {  
            labels: labels,  
            datasets: [{  
                label: 'Total Quantity Needed',  
                data: data,  
                backgroundColor: 'rgba(75, 192, 192, 0.2)',  
                borderColor: 'rgba(75, 192, 192, 1)',  
                borderWidth: 1  
            }]  
        },  
        options: {  
            scales: {  
                y: {  
                    beginAtZero: true,  
                    ticks: {  
                        callback: function(value) {  
                            return value.toLocaleString(); // Format y-axis labels with thousands separator  
                        }  
                    }  
                }  
            }  
        }  
    };  
  
    // Render chart  
    var ctx = document.getElementById('consumptionChart').getContext('2d');  
    var consumptionChart = new Chart(ctx, config);  
</script>  
  
<?php include_once('layouts/footer.php'); ?>  
