<?php
include 'includes/config.php';

header('Content-Type: application/json');

try {
    if (isset($_POST['product_id'])) {
        $productId = intval($_POST['product_id']);

        $stmt = $conn->prepare("SELECT id, name FROM products WHERE id = :productId");
        $stmt->execute(['productId' => $productId]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($product) {
            $stmt = $conn->prepare("SELECT SUM(quantity) as total_purchased FROM purchase_lines WHERE product_id = :productId");
            $stmt->execute(['productId' => $productId]);
            $purchaseData = $stmt->fetch(PDO::FETCH_ASSOC);

            $stmt = $conn->prepare("SELECT quantity as stock_setting FROM stock_setting WHERE product_id = :productId");
            $stmt->execute(['productId' => $productId]);
            $stockSettingData = $stmt->fetch(PDO::FETCH_ASSOC);

            $stmt = $conn->prepare("SELECT SUM(sale_qty) as total_sold FROM stock_sale WHERE product_id = :productId");
            $stmt->execute(['productId' => $productId]);
            $saleData = $stmt->fetch(PDO::FETCH_ASSOC);

            $overallStock = $purchaseData['total_purchased'] ?? 0;
            $currentStockFromSetting = $stockSettingData['stock_setting'] ?? 0;
            $totalSold = $saleData['total_sold'] ?? 0;

            $currentStockFinal = $overallStock - $currentStockFromSetting - $totalSold;

            $response = [
                'name' => $product['name'],
                'overallStock' => $overallStock,
                'OpeningStock' => $currentStockFromSetting,
                'currentStock' => $currentStockFinal
            ];

            echo json_encode($response);
        } else {
            echo json_encode(['error' => 'Product not found']);
        }
    } else {
        echo json_encode(['error' => 'No product ID provided']);
    }
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>
