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

// Initialize the response array
$response = ["error" => false];

// Get stockID and productID from the GET parameters
$stockID = isset($_GET["stockID"]) ? intval($_GET["stockID"]) : null;
$productID = isset($_GET["productID"]) ? intval($_GET["productID"]) : null;

// Validate input
if (!$stockID || !$productID) {
    echo json_encode([
        "error" => true,
        "message" => "Invalid or missing stockID or productID."
    ]);
    exit;
}

// Step 1: Fetch product details based on productID
$productQuery = "
    SELECT 
        id, 
        productPicture, 
        productCategory, 
        productName, 
        productColor, 
        productQuality, 
        productDescription, 
        date_added, 
        added_by, 
        productType 
    FROM products 
    WHERE id = ?
";

$stmtProduct = $connect->prepare($productQuery);
$stmtProduct->bind_param("i", $productID);
$stmtProduct->execute();
$productResult = $stmtProduct->get_result();

if ($productResult->num_rows > 0) {
    $productRow = $productResult->fetch_assoc();

    // Add product details to the response
    $response["productDetails"] = [
        "id" => $productRow["id"],
        "productPicture" => $productRow["productPicture"],
        "productCategory" => $productRow["productCategory"],
        "productName" => $productRow["productName"],
        "productColor" => $productRow["productColor"],
        "productQuality" => $productRow["productQuality"],
        "productDescription" => $productRow["productDescription"],
        "date_added" => $productRow["date_added"],
        "added_by" => $productRow["added_by"],
        "productType" => $productRow["productType"]
    ];
} else {
    echo json_encode([
        "error" => true,
        "message" => "No product details found for the given productID."
    ]);
    exit;
}

// Step 2: Fetch release records based on stockID
$releaseQuery = "
    SELECT 
        releaseRecords.id, 
        releaseRecords.stockID, 
        releaseRecords.quantity, 
        releaseRecords.releaseType, 
        releaseRecords._timestamp, 
        COALESCE(releaseRecords.name, 'N/A') AS releaseName, 
        COALESCE(releaseRecords.description, 'N/A') AS releaseDescription, 
        releaseRecords.releaseBy 
    FROM releaseRecords 
    WHERE releaseRecords.stockID = ? 
    ORDER BY releaseRecords.id DESC
";

$stmtRelease = $connect->prepare($releaseQuery);
$stmtRelease->bind_param("i", $stockID);
$stmtRelease->execute();
$releaseResult = $stmtRelease->get_result();

if ($releaseResult->num_rows > 0) {
    $releaseRecords = [];
    while ($releaseRow = $releaseResult->fetch_assoc()) {
        $releaseByID = $releaseRow["releaseBy"];

        // Step 3: Fetch user details for releaseBy
        $usersQuery = "
            SELECT name, email, phone 
            FROM users 
            WHERE id = ?
        ";
        $stmtUsers = $connect->prepare($usersQuery);
        $stmtUsers->bind_param("i", $releaseByID);
        $stmtUsers->execute();
        $usersResult = $stmtUsers->get_result();
        $user = $usersResult->num_rows > 0 ? $usersResult->fetch_assoc() : [
            "name" => "Unknown",
            "email" => "Unknown",
            "phone" => "Unknown"
        ];

        // Step 4: Fetch product details for stockID
        $storeStockQuery = "
            SELECT 
                store_stock.productID, 
                store_stock.size, 
                store_stock.store_price, 
                products.productName 
            FROM store_stock 
            JOIN products ON store_stock.productID = products.id 
            WHERE store_stock.id = ?
        ";
        $stmtStoreStock = $connect->prepare($storeStockQuery);
        $stmtStoreStock->bind_param("i", $releaseRow["stockID"]);
        $stmtStoreStock->execute();
        $storeStockResult = $stmtStoreStock->get_result();

        if ($storeStockResult->num_rows > 0) {
            $storeStockRow = $storeStockResult->fetch_assoc();
            $productName = $storeStockRow["productName"] . ' ' . $storeStockRow["size"];
            $productPrice = $storeStockRow["store_price"];

            // Calculate the total amount
            $amount = $releaseRow["quantity"] * $productPrice;

            // Add the release record to the array
            $releaseRecords[] = [
                "id" => $releaseRow["id"],
                "productName" => $productName,
                "productPrice" => $productPrice,
                "quantity" => $releaseRow["quantity"],
                "amount" => $amount,
                "releaseType" => $releaseRow["releaseType"],
                "_timestamp" => $releaseRow["_timestamp"],
                "releaseName" => $releaseRow["releaseName"],
                "releaseDescription" => $releaseRow["releaseDescription"],
                "releasedBy" => [
                    "name" => $user["name"],
                    "email" => $user["email"],
                    "phone" => $user["phone"]
                ]
            ];
        }
    }

    $response["releaseRecords"] = $releaseRecords;
} else {
    $response["releaseRecords"] = [];
}

// Output the response as JSON
echo json_encode($response);
?>
