<?php
require('config.php');

$response = [];

try {
   
    // Product summary query
    $productSummaryQuery = "
        SELECT 
            products.productName,
            products.productPicture AS productImage, /* Adding product image */
            store_stock.size,
            store_stock.quantity,
            store_stock.productPrice,
            COALESCE(store_stock.quantity * store_stock.productPrice, 0) AS totalValue
        FROM products
        JOIN store_stock ON products.id = store_stock.productID ORDER BY RAND()
    ";

    $productSummaryResult = $connect->query($productSummaryQuery);

    // Check if query execution failed
    if ($productSummaryResult === false) {
        throw new Exception("Error executing product summary query: " . $connect->error);
    }

    $response['error'] = 'false';
    $response['message'] = [];

    while ($row = $productSummaryResult->fetch_assoc()) {
        $response['message'][] = [
            'productName' => $row['productName'],
            'productImage' => $row['productImage'], // Including product image in the response
            'size' => $row['size'],
            'quantity' => (string)$row['quantity'],
            'productPrice' => (string)$row['productPrice'],
            'totalValue' => (string)$row['totalValue']
        ];
    }

} catch (Exception $e) {
    $response['error'] = 'true';
    $response['message'] = $e->getMessage();
} finally {
    // Ensure the database connection is closed
    if (isset($connect) && $connect instanceof mysqli) {
        $connect->close();
    }
}

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