<?php
// =========================================================================
// UNIFIED PRODUCT ATTRIBUTES ENGINE
// Dynamically manages Brands, Manufacturers, Categories, UOMs, etc.
// =========================================================================
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ob_start();

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

$action = $_POST['action'] ?? '';
$type = $_POST['type'] ?? '';

// Master routing table mapping 'type' to physical database tables
$tables = [
    'brand'        => ['table' => 'brand_dictionary',    'col_name' => 'brand_name'],
    'manufacturer' => ['table' => 'manufacturers',       'col_name' => 'manufacturer_name'],
    'type'         => ['table' => 'product_types',       'col_name' => 'type_name'],
    'category'     => ['table' => 'item_categories',     'col_name' => 'category_name'],
    'uom'          => ['table' => 'units_of_measure',    'col_name' => 'unit_name'],
    'therapeutic'  => ['table' => 'therapeutic_classes', 'col_name' => 'class_name'],
    'formulation'  => ['table' => 'drug_formulations',   'col_name' => 'formulation_name'],
    'prescribing'  => ['table' => 'prescribing_levels',  'col_name' => 'level_code']
];

if (!isset($tables[$type])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid attribute dictionary type requested.']);
    exit;
}

$tConfig = $tables[$type];
$tableName = $tConfig['table'];
$colName = $tConfig['col_name'];

try {
    // ---------------------------------------------------------
    // 1. FETCH DATATABLE RECORDS
    // ---------------------------------------------------------
    if ($action === 'fetch') {
        $res = $conn->query("SELECT * FROM $tableName ORDER BY $colName ASC");
        $data = [];
        if ($res) while ($r = $res->fetch_assoc()) $data[] = $r;
        
        ob_end_clean();
        echo json_encode(['status' => 'success', 'data' => $data]);
        exit;
    }

    // ---------------------------------------------------------
    // 2. TOGGLE ACTIVE/INACTIVE STATUS
    // ---------------------------------------------------------
    if ($action === 'toggle_status') {
        $id = (int)$_POST['id'];
        $conn->query("UPDATE $tableName SET is_active = IF(is_active=1, 0, 1) WHERE id = $id");
        
        ob_end_clean();
        echo json_encode(['status' => 'success', 'message' => 'Status updated successfully.']);
        exit;
    }

    // ---------------------------------------------------------
    // 3. DYNAMIC SAVE / UPDATE RECORD
    // ---------------------------------------------------------
    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = null;

        if ($type === 'brand') {
            $name = trim($_POST['brand_name']);
            if($id > 0) $stmt = $conn->prepare("UPDATE brand_dictionary SET brand_name=? WHERE id=?");
            else $stmt = $conn->prepare("INSERT INTO brand_dictionary (brand_name) VALUES (?)");
            if($id>0) $stmt->bind_param("si", $name, $id); else $stmt->bind_param("s", $name);
        }
        elseif ($type === 'manufacturer') {
            $name = trim($_POST['manufacturer_name']);
            $country = trim($_POST['country_of_origin'] ?? '');
            if($id > 0) $stmt = $conn->prepare("UPDATE manufacturers SET manufacturer_name=?, country_of_origin=? WHERE id=?");
            else $stmt = $conn->prepare("INSERT INTO manufacturers (manufacturer_name, country_of_origin) VALUES (?, ?)");
            if($id>0) $stmt->bind_param("ssi", $name, $country, $id); else $stmt->bind_param("ss", $name, $country);
        }
        elseif ($type === 'type') {
            $name = trim($_POST['type_name']);
            if($id > 0) $stmt = $conn->prepare("UPDATE product_types SET type_name=? WHERE id=?");
            else $stmt = $conn->prepare("INSERT INTO product_types (type_name) VALUES (?)");
            if($id>0) $stmt->bind_param("si", $name, $id); else $stmt->bind_param("s", $name);
        }
        elseif ($type === 'category') {
            $name = trim($_POST['category_name']);
            $desc = trim($_POST['description'] ?? '');
            if($id > 0) $stmt = $conn->prepare("UPDATE item_categories SET category_name=?, description=? WHERE id=?");
            else $stmt = $conn->prepare("INSERT INTO item_categories (category_name, description) VALUES (?, ?)");
            if($id>0) $stmt->bind_param("ssi", $name, $desc, $id); else $stmt->bind_param("ss", $name, $desc);
        }
        elseif ($type === 'uom') {
            $name = trim($_POST['unit_name']);
            $sym = trim($_POST['unit_symbol'] ?? '');
            if($id > 0) $stmt = $conn->prepare("UPDATE units_of_measure SET unit_name=?, unit_symbol=? WHERE id=?");
            else $stmt = $conn->prepare("INSERT INTO units_of_measure (unit_name, unit_symbol) VALUES (?, ?)");
            if($id>0) $stmt->bind_param("ssi", $name, $sym, $id); else $stmt->bind_param("ss", $name, $sym);
        }
        elseif ($type === 'therapeutic') {
            $name = trim($_POST['class_name']);
            if($id > 0) $stmt = $conn->prepare("UPDATE therapeutic_classes SET class_name=? WHERE id=?");
            else $stmt = $conn->prepare("INSERT INTO therapeutic_classes (class_name) VALUES (?)");
            if($id>0) $stmt->bind_param("si", $name, $id); else $stmt->bind_param("s", $name);
        }
        elseif ($type === 'formulation') {
            $name = trim($_POST['formulation_name']);
            $sym = trim($_POST['formulation_symbol'] ?? '');
            $desc = trim($_POST['description'] ?? '');
            if($id > 0) $stmt = $conn->prepare("UPDATE drug_formulations SET formulation_name=?, formulation_symbol=?, description=? WHERE id=?");
            else $stmt = $conn->prepare("INSERT INTO drug_formulations (formulation_name, formulation_symbol, description) VALUES (?, ?, ?)");
            if($id>0) $stmt->bind_param("sssi", $name, $sym, $desc, $id); else $stmt->bind_param("sss", $name, $sym, $desc);
        }
        elseif ($type === 'prescribing') {
            $code = trim($_POST['level_code']);
            $desc = trim($_POST['description'] ?? '');
            if($id > 0) $stmt = $conn->prepare("UPDATE prescribing_levels SET level_code=?, description=? WHERE id=?");
            else $stmt = $conn->prepare("INSERT INTO prescribing_levels (level_code, description) VALUES (?, ?)");
            if($id>0) $stmt->bind_param("ssi", $code, $desc, $id); else $stmt->bind_param("ss", $code, $desc);
        }

        $stmt->execute();
        ob_end_clean();
        echo json_encode(['status' => 'success', 'message' => 'Dictionary attribute saved successfully.']);
        exit;
    }

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