<?php
session_start();

// Database connection code here
require_once('shikanisha.kts.php');

$response = array(); // Response array to hold success/failure messages

if (isset($_POST['startDate']) && isset($_POST['endDate'])) {
    $startDate = $_POST['startDate'];
    $endDate = $_POST['endDate'];

    // Fetch data from the database based on the date range
    $sql = "SELECT ip.product_name, ip.quantity, ip.product_id
            FROM issued_products ip
            INNER JOIN issued i ON ip.issue_id = i.issue_id
            WHERE i.date_time BETWEEN ? AND ?";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $startDate, $endDate);
    $stmt->execute();
    $result = $stmt->get_result();

    $data = array();
    $issuedItems = array();

    while ($row = $result->fetch_assoc()) {
        $productID = $row['product_id'];

        // Check if the product has been processed before
        if (isset($issuedItems[$productID])) {
            // If yes, update the quantity
            $issuedItems[$productID]['quantity'] += $row['quantity'];
        } else {
            // If not, add the product to the issued items array
            $issuedItems[$productID] = array(
                'product_name' => $row['product_name'],
                'quantity' => $row['quantity'],
                'product_id' => $productID
            );
        }
    }

    // Close the database statement
    $stmt->close();

    // Convert the associative array to a simple numeric array
    $data = array_values($issuedItems);

    // Store data and date range in sessions
    $_SESSION['issued_items'] = $data;
    $_SESSION['dateRange'] = array('start' => $startDate, 'end' => $endDate);

    $response['success'] = true;
    $response['data'] = $data;
} else {
    $response['success'] = false;
    $response['message'] = "Invalid request parameters.";
}

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

// Close the database connection if necessary
$conn->close();
?>
