<?php
require("../connection.php");

if (isset($_GET['category'])) {
    // Get current and previous month and year
    $currentMonth = date('m');
    $currentYear = date('Y');
    $previousMonth = date('m', strtotime("-1 month"));
    $previousYear = date('Y', strtotime("-1 month"));

    $category = mysqli_real_escape_string($con, $_GET['category']);
    
    // Fetch descriptions for the current month and year
    $query = "SELECT category_description FROM item_master WHERE category = '$category' 
              AND MONTH(po_date) = '$currentMonth' AND YEAR(po_date) = '$currentYear'";
    $result = mysqli_query($con, $query);

    $descriptions = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $descriptions[] = $row;
    }

    // Fetch quantity for the previous month
    $previousMonthQuery = "SELECT SUM(quantity) AS prev_month_quantity 
                           FROM item_master 
                           WHERE category = '$category' 
                           AND MONTH(po_date) = '$previousMonth' 
                           AND YEAR(po_date) = '$previousYear'";
    $prevMonthResult = mysqli_query($con, $previousMonthQuery);
    $prevMonthQuantity = mysqli_fetch_assoc($prevMonthResult)['prev_month_quantity'] ?? 0;

    // Fetch quantity for the current month
    $currentMonthQuery = "SELECT SUM(quantity) AS current_month_quantity 
                          FROM item_master 
                          WHERE category = '$category' 
                          AND MONTH(po_date) = '$currentMonth' 
                          AND YEAR(po_date) = '$currentYear'";
    $currentMonthResult = mysqli_query($con, $currentMonthQuery);
    $currentMonthQuantity = mysqli_fetch_assoc($currentMonthResult)['current_month_quantity'] ?? 0;

    // Add the quantities to the response
    $response = array(
        'descriptions' => $descriptions,
        'prev_month_quantity' => $prevMonthQuantity,
        'current_month_quantity' => $currentMonthQuantity
    );

    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
}


?>
