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

if (isset($_POST['id'])) {
    $product_id = $_POST['id'];

    // Query to get product details and units
    $query = $conn->prepare("
        SELECT 
            p.name AS product_name, 
            p.id AS product_id,
            p.category_id,
            v.default_purchase_price AS purchase_price,
            v.dpp_inc_tax AS unit_cost_before_tax,
            v.profit_percent AS profit_margin,
            v.sell_price_inc_tax AS sell_price,
            p.unit_id AS unit_id
        FROM products p
        INNER JOIN variations v ON p.id = v.product_id
        WHERE business_id = 3 AND p.id = ?
    ");
    $query->execute([$product_id]);
    $product = $query->fetch();

    if ($product) {
        // Query to get units
        $unitQuery = $conn->prepare("
            SELECT `id`, `business_id`, `actual_name`, `short_name`
            FROM units
            WHERE `business_id` = 3 AND `id` = ?
        ");
        $unitQuery->execute([$product['unit_id']]);
        $units = $unitQuery->fetchAll();

        // Build response
        $response = [
            'product_name' => $product['product_name'],
            'product_id' => $product['product_id'],
            'sell_price' => $product['sell_price'],
            'category_id' => $product['category_id'],
            'units' => array_map(function ($unit) {
                return [
                    'actual_name' => $unit['actual_name'],
                    'short_name' => $unit['short_name'],
                ];
            }, $units),
        ];

        header('Content-Type: application/json');
        echo json_encode($response);
    } else {
        echo json_encode(['error' => 'Product not found']);
    }
}
?>
