<?php
// Secure connection wrapper to db.php
require_once __DIR__ . '/../../includes/db.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->begin_transaction();
    
    try {
        // --- 1. CORE CLINICAL DATA ---
        $product_type_id      = isset($_POST['product_type_id']) ? (int)$_POST['product_type_id'] : 0;
        $category_id          = isset($_POST['category_id']) ? (int)$_POST['category_id'] : 0;
        $therapeutic_class_id = !empty($_POST['therapeutic_class_id']) ? (int)$_POST['therapeutic_class_id'] : null;
        $generic_name         = trim($conn->real_escape_string($_POST['generic_name'] ?? ''));
        $formulation_id       = !empty($_POST['formulation_id']) ? (int)$_POST['formulation_id'] : null;
        $strength_value       = !empty($_POST['strength_value']) ? trim($conn->real_escape_string($_POST['strength_value'])) : null;
        $strength_unit_id     = !empty($_POST['strength_unit_id']) ? (int)$_POST['strength_unit_id'] : null;
        $base_uom_id          = isset($_POST['base_uom_id']) ? (int)$_POST['base_uom_id'] : 0;
        $cash_price           = isset($_POST['cash_price']) ? (float)$_POST['cash_price'] : 0.00;
        $unit_of_pricing      = trim($conn->real_escape_string($_POST['unit_of_pricing'] ?? ''));

        // DYNAMIC DEPARTMENT FETCH (No Hardcoding)
        // Fetches the Pharmacy Department dynamically. Fallback to 1 if it doesn't exist.
        $deptQuery = $conn->query("SELECT id FROM departments WHERE department_name LIKE '%Pharmacy%' LIMIT 1");
        $dept_id = ($deptQuery && $deptQuery->num_rows > 0) ? (int)$deptQuery->fetch_object()->id : 1; 

        // --- 2. NHIS RULES ---
        $nhis_covered = isset($_POST['nhis_covered']) ? 1 : 0;
        $corp_covered = isset($_POST['corp_covered']) ? 1 : 0;
        
        $nhis_drug_code = null; $prescribing_level = null;
        $gdrg_tariff = 0.00; $is_copay_required = 0; $copay_amount = 0.00;

        if ($nhis_covered === 1) {
            $nhis_drug_code    = !empty($_POST['nhis_drug_code']) ? trim($conn->real_escape_string($_POST['nhis_drug_code'])) : null;
            $prescribing_level = !empty($_POST['prescribing_level']) ? trim($conn->real_escape_string($_POST['prescribing_level'])) : null;
            $gdrg_tariff       = (float)($_POST['gdrg_tariff'] ?? 0);
            $is_copay_required = isset($_POST['is_nhis_copay_required']) ? 1 : 0;
            $copay_amount      = $is_copay_required ? (float)$_POST['copay_amount'] : 0.00;
        }

        // --- 3. INSERT TIER 1: CLINICAL GENERIC (`products`) ---
        $stmtProd = $conn->prepare("
            INSERT INTO products 
            (product_type_id, category_id, therapeutic_class_id, generic_name, formulation_id, strength_value, strength_unit_id, base_uom_id, nhis_drug_code, gdrg_tariff, is_copay_required, copay_amount, prescribing_level, is_active) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
        ");
        
        // Corrected bind_param string: 13 placeholders matched exactly to their types
        $stmtProd->bind_param("iiisisiiisdid", 
            $product_type_id, 
            $category_id, 
            $therapeutic_class_id, 
            $generic_name, 
            $formulation_id, 
            $strength_value, 
            $strength_unit_id, 
            $base_uom_id, 
            $nhis_drug_code, 
            $gdrg_tariff, 
            $is_copay_required, 
            $copay_amount, 
            $prescribing_level
        );
        
        if (!$stmtProd->execute()) throw new Exception("Database Error (Products Master): " . $stmtProd->error);
        $product_id = $conn->insert_id;
        $stmtProd->close();

        // --- 4. INSERT TIER 2: COMMERCIAL BRANDS (`product_variants`) ---
        if (isset($_POST['brand_id_arr']) && is_array($_POST['brand_id_arr'])) {
            $stmtBrand = $conn->prepare("
                INSERT INTO product_variants 
                (product_id, brand_id, manufacturer_id, barcode, pack_size, purchase_price, selling_price, is_active) 
                VALUES (?, ?, ?, ?, ?, ?, ?, 1)
            ");

            for ($i = 0; $i < count($_POST['brand_id_arr']); $i++) {
                $b_id    = (int)$_POST['brand_id_arr'][$i];
                $m_id    = !empty($_POST['manufacturer_id_arr'][$i]) ? (int)$_POST['manufacturer_id_arr'][$i] : null;
                $barcode = !empty($_POST['barcode_arr'][$i]) ? trim($conn->real_escape_string($_POST['barcode_arr'][$i])) : null;
                $p_size  = (int)($_POST['pack_size_arr'][$i] ?? 1);
                $p_price = (float)($_POST['cost_price_arr'][$i] ?? 0.00);
                $s_price = (float)($_POST['selling_price_arr'][$i] ?? $cash_price);

                if ($b_id > 0) {
                    $stmtBrand->bind_param("iiisidd", $product_id, $b_id, $m_id, $barcode, $p_size, $p_price, $s_price);
                    if (!$stmtBrand->execute()) throw new Exception("Database Error (Brand Dictionary Link): " . $stmtBrand->error);
                }
            }
            $stmtBrand->close();
        }

        // --- 5. SYNC TIER 3: BILLING ROUTER (`service_catalog`) ---
        $service_name = $generic_name;
        if ($strength_value) $service_name .= " {$strength_value}";
        
        $stmtMaster = $conn->prepare("
            INSERT INTO service_catalog (
                category_id, department_id, service_name, service_type, 
                nhis_covered, corp_covered, nhis_drug_code, unit_of_pricing, 
                prescribing_level, cash_price_adult, cash_price_child, 
                tariff_adult, tariff_child, is_copay_required, copay_amount, is_active
            ) VALUES (?, ?, ?, 'Drug', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
        ");
        
        // Corrected bind_param string: 14 placeholders matched exactly to their types
        $stmtMaster->bind_param("iisiisssddddid", 
            $category_id, 
            $dept_id, 
            $service_name, 
            $nhis_covered, 
            $corp_covered, 
            $nhis_drug_code, 
            $unit_of_pricing, 
            $prescribing_level, 
            $cash_price, 
            $cash_price, 
            $gdrg_tariff, 
            $gdrg_tariff, 
            $is_copay_required, 
            $copay_amount
        );
        
        if (!$stmtMaster->execute()) throw new Exception("Database Error (Service Catalog Integration): " . $stmtMaster->error);
        $service_id = $conn->insert_id;
        $stmtMaster->close();

        // --- 6. CORPORATE TARIFF SYNC ---
        if ($corp_covered === 1 && !empty($_POST['corp_mapped'])) {
            $stmtCorp = $conn->prepare("INSERT INTO service_corporate_tariffs (service_id, insurance_type_id, tariff_amount, is_copay_required, copay_amount_adult, copay_amount_child) VALUES (?, ?, ?, ?, ?, ?)");
            
            foreach ($_POST['corp_mapped'] as $ins_id => $is_mapped) {
                if ($is_mapped == '1') {
                    $t_amt = (float)($_POST['corp_tariff'][$ins_id] ?? 0);
                    $c_req = isset($_POST['corp_copay_req'][$ins_id]) ? 1 : 0;
                    $c_amt = $c_req ? (float)($_POST['corp_copay_amt'][$ins_id] ?? 0) : 0.00;
                    
                    $stmtCorp->bind_param("iididd", $service_id, $ins_id, $t_amt, $c_req, $c_amt, $c_amt);
                    $stmtCorp->execute();
                }
            }
            $stmtCorp->close();
        }

        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => "Master Product <strong>{$service_name}</strong> defined successfully."]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}
?>