<?php
require_once dirname(__DIR__, 2) . '/includes/db.php';

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

$action = $_GET['action'] ?? '';

try {
    if ($action === 'locations') {
        $type = $_GET['type'] ?? 'Store';
        $data = [];
        
        if ($type === 'Store') {
            $res = $conn->query("SELECT id, store_name as name FROM stores WHERE is_active = 1 ORDER BY store_name ASC");
        } elseif ($type === 'Department') {
            $res = $conn->query("SELECT id, department_name as name FROM departments WHERE is_active = 1 ORDER BY department_name ASC");
        } elseif ($type === 'Dispensary') {
            $res = $conn->query("SELECT id, location_name as name FROM inventory_locations WHERE is_active = 1 AND location_type = 'Dispensary' ORDER BY location_name ASC");
        } else {
            throw new Exception("Invalid Location Type Selected.");
        }
        
        if ($res) {
            while ($row = $res->fetch_assoc()) { $data[] = $row; }
        }
        ob_end_clean();
        echo json_encode(['status' => 'success', 'data' => $data]);
    } 
    
    elseif ($action === 'products') {
        $data = [];
        // CRITICAL FIX: Pulling directly from service_catalog to match Dispensing Desk IDs
        $res = $conn->query("SELECT id, service_name as generic_name, cash_price_adult as selling_price FROM service_catalog WHERE service_type = 'Drug' AND is_active = 1 ORDER BY service_name ASC");
        while ($row = $res->fetch_assoc()) { $data[] = $row; }
        ob_end_clean();
        echo json_encode(['status' => 'success', 'data' => $data]);
    }

    elseif ($action === 'variants') {
        $product_id = (int)$_GET['product_id'];
        $data = [];
        // CRITICAL FIX: Pulling brands from item_brands that match the service_catalog
        $query = "
            SELECT id as variant_id, brand_name, 0 as purchase_price, 
            (SELECT cash_price_adult FROM service_catalog WHERE id = ?) as selling_price 
            FROM item_brands WHERE service_id = ? AND is_active = 1
        ";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ii", $product_id, $product_id);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) { $data[] = $row; }
        $stmt->close();
        ob_end_clean();
        echo json_encode(['status' => 'success', 'data' => $data]);
    }
} catch (Exception $e) {
    ob_end_clean();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>