<?php    
$page_title = 'Production Output Comparison by Day';    
require_once('includes/load.php');    
require 'vendor/autoload.php'; // Include PhpSpreadsheet    
use PhpOffice\PhpSpreadsheet\Spreadsheet;    
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;    
  
page_require_level(3); // Only level 3 access is allowed    
  
// Start output buffering    
ob_start();    
  
include_once('layouts/header.php');    
  
// Function to get the number of days in a month    
function get_days_in_month($year, $month) {    
    return date('t', strtotime("$year-$month-01"));    
}    
  
// Get current month and previous month    
$current_year = date('Y');    
$current_month = date('m');    
$previous_month = ($current_month == 1) ? 12 : $current_month - 1;    
$previous_year = ($current_month == 1) ? $current_year - 1 : $current_year;    
  
// Get the number of days in the current and previous months    
$current_month_days = get_days_in_month($current_year, $current_month);    
$previous_month_days = get_days_in_month($previous_year, $previous_month);    
  
// Initialize arrays to store daily production data    
$current_month_data = [];    
$previous_month_data = [];    
  
// Retrieve production output data for each day of the current month    
for ($day = 1; $day <= $current_month_days; $day++) {    
    $current_date = date('Y-m-d', strtotime("$current_year-$current_month-$day"));    
    $sql_current_day = "    
        SELECT SUM(quantity_produced) AS total_quantity    
        FROM production_output    
        WHERE production_date = '$current_date'";    
    $result_current_day = $db->query($sql_current_day);    
    $current_day_data = $result_current_day->fetch_assoc();    
    $current_month_data[$day] = $current_day_data['total_quantity'] ?? 0;    
}    
  
// Retrieve production output data for each day of the previous month    
for ($day = 1; $day <= $previous_month_days; $day++) {    
    $previous_date = date('Y-m-d', strtotime("$previous_year-$previous_month-$day"));    
    $sql_previous_day = "    
        SELECT SUM(quantity_produced) AS total_quantity    
        FROM production_output    
        WHERE production_date = '$previous_date'";    
    $result_previous_day = $db->query($sql_previous_day);    
    $previous_day_data = $result_previous_day->fetch_assoc();    
    $previous_month_data[$day] = $previous_day_data['total_quantity'] ?? 0;    
}    
  
// Handle success and error messages    
if (isset($_GET['error'])) {    
    echo '<div class="alert alert-danger">Failed to retrieve production output data.</div>';    
}    
?>    
  
<div class="row">    
    <div class="col-md-12">    
        <div class="panel panel-default">    
            <div class="panel-heading">    
                <h3 class="panel-title">Production Output Comparison by Day</h3>    
            </div>    
            <div class="panel-body">    
                <div class="alert alert-info">    
                    <strong>Comparison of Production Output by Day:</strong>    
                </div>    
                <table class="table table-bordered table-striped">    
                    <thead>    
                        <tr>    
                            <th>Day</th>    
                            <th>Current Month (<?php echo date('F Y', strtotime("$current_year-$current_month-01")); ?>)</th>    
                            <th>Previous Month (<?php echo date('F Y', strtotime("$previous_year-$previous_month-01")); ?>)</th>    
                            <th>Balance</th> <!-- New Balance Column -->    
                        </tr>    
                    </thead>    
                    <tbody>    
                        <?php    
                        // Determine the maximum number of days to display    
                        $max_days = max($current_month_days, $previous_month_days);    
                        for ($day = 1; $day <= $max_days; $day++) {    
                            $current_quantity = $current_month_data[$day] ?? 0;    
                            $previous_quantity = $previous_month_data[$day] ?? 0;    
                            $balance = $current_quantity - $previous_quantity; // Calculate balance    
                            echo "<tr>    
                                    <td>$day</td>    
                                    <td>$current_quantity</td>    
                                    <td>$previous_quantity</td>    
                                    <td>$balance</td> <!-- Display Balance -->    
                                  </tr>";    
                        }    
                        ?>    
                    </tbody>    
                </table>    
  
                <!-- Chart Section -->    
                <canvas id="productionChart" width="400" height="200"></canvas>    
            </div>    
        </div>    
    </div>    
</div>    
  
<!-- Include Chart.js Library -->    
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>    
<script>    
    // Prepare data for the chart    
    const currentMonthData = <?php echo json_encode(array_values($current_month_data)); ?>;    
    const previousMonthData = <?php echo json_encode(array_values($previous_month_data)); ?>;    
    const days = <?php echo json_encode(range(1, max($current_month_days, $previous_month_days))); ?>;    
  
    // Create the chart    
    const ctx = document.getElementById('productionChart').getContext('2d');    
    const productionChart = new Chart(ctx, {    
        type: 'bar',  // Changed to bar chart    
        data: {    
            labels: days,    
            datasets: [    
                {    
                    label: 'Current Month',    
                    data: currentMonthData,    
                    backgroundColor: 'rgba(54, 162, 235, 0.6)',  // Blue with 60% opacity    
                    borderColor: 'rgba(54, 162, 235, 1)',      // Solid blue    
                    borderWidth: 1    
                },    
                {    
                    label: 'Previous Month',    
                    data: previousMonthData,    
                    backgroundColor: 'rgba(255, 99, 132, 0.6)', // Red with 60% opacity    
                    borderColor: 'rgba(255, 99, 132, 1)',     // Solid red    
                    borderWidth: 1    
                }    
            ]    
        },    
        options: {    
            scales: {    
                y: {    
                    beginAtZero: true    
                }    
            }    
        }    
    });    
</script>    
  
<?php include_once('layouts/footer.php'); ?>    
