<?php
// Config and DB are dynamically included via the SPA framework
require_once dirname(__DIR__, 3) . '/dripend/config/config.php';
require_once dirname(__DIR__, 3) . '/dripend/includes/db.php';

if (!isset($conn) && isset($db)) { $conn = $db; }

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

// Fetch Dropdown Dependencies
$insurances = $conn->query("SELECT id, insurance_name FROM insurance_type WHERE LOWER(insurance_name) NOT IN ('nhis', 'cash') AND is_active = 1 ORDER BY insurance_name ASC")->fetch_all(MYSQLI_ASSOC);
$formulations = $conn->query("SELECT id, formulation_name, formulation_symbol FROM drug_formulations WHERE is_active = 1 ORDER BY formulation_name ASC")->fetch_all(MYSQLI_ASSOC);
$units = $conn->query("SELECT id, unit_name, unit_symbol FROM units_of_measure WHERE is_active = 1 ORDER BY unit_name ASC")->fetch_all(MYSQLI_ASSOC);
$prescribe_levels = $conn->query("SELECT level_code, description FROM prescribing_levels WHERE is_active = 1 ORDER BY level_code ASC")->fetch_all(MYSQLI_ASSOC);
$categories = $conn->query("SELECT id, category_name FROM item_categories WHERE is_active = 1 ORDER BY id ASC")->fetch_all(MYSQLI_ASSOC);
$product_types = $conn->query("SELECT id, type_name FROM product_types WHERE is_active = 1 ORDER BY id ASC")->fetch_all(MYSQLI_ASSOC);
$therapeutic_classes = $conn->query("SELECT id, class_name FROM therapeutic_classes WHERE is_active = 1 ORDER BY class_name ASC")->fetch_all(MYSQLI_ASSOC) ?? [];
$manufacturers = $conn->query("SELECT id, manufacturer_name FROM manufacturers WHERE is_active = 1 ORDER BY manufacturer_name ASC")->fetch_all(MYSQLI_ASSOC) ?? [];
$brands = $conn->query("SELECT id, brand_name FROM brand_dictionary WHERE is_active = 1 ORDER BY brand_name ASC")->fetch_all(MYSQLI_ASSOC) ?? [];
?>

<style>
    /* UI STYLES */
    #enterpriseProductUpdateForm { font-family: 'Inter', system-ui, sans-serif; color: #1e293b; background-color: #ffffff; border-radius: 12px; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05); }
    #enterpriseProductUpdateForm .section-title { font-size: 1.15rem; font-weight: 700; padding-bottom: 0.75rem; margin-bottom: 1.5rem; border-bottom: 2px solid #f1f5f9; display: flex; align-items: center; }
    #enterpriseProductUpdateForm .form-label { font-size: 0.75rem; font-weight: 700; text-transform: uppercase; color: #64748b; margin-bottom: 0.5rem; }
    #enterpriseProductUpdateForm .form-control, #enterpriseProductUpdateForm .form-select { border: 1px solid #cbd5e1; border-radius: 8px; padding: 0.65rem 1rem; font-size: 0.9rem; background-color: #f8fafc; }
    #enterpriseProductUpdateForm .form-control:focus, #enterpriseProductUpdateForm .form-select:focus { background-color: #ffffff; border-color: #f59e0b; box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.15); outline: none; }
    .rimax-switch { height: 1.5rem !important; width: 3rem !important; cursor: pointer; }
    .rimax-table th { background-color: #f8fafc; font-size: 0.75rem; text-transform: uppercase; color: #475569; padding: 1rem; font-weight: 700; }
    .theme-box { border-radius: 12px; padding: 1.5rem; margin-bottom: 2rem; border: 1px solid; }
    .box-clinical { background-color: #ffffff; border-color: #e2e8f0; }
    .box-nhis { background-color: #fffbeb; border-color: #fde68a; }
    .box-corp { background-color: #f0f9ff; border-color: #bae6fd; }
</style>

<template id="tmpl-brands">
    <option value="" selected disabled>-- Select Brand --</option>
    <?php foreach($brands as $b): ?>
        <option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['brand_name']) ?></option>
    <?php endforeach; ?>
</template>

<template id="tmpl-manufacturers">
    <option value="" selected disabled>-- Select Manufacturer --</option>
    <?php foreach($manufacturers as $m): ?>
        <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['manufacturer_name']) ?></option>
    <?php endforeach; ?>
</template>

<!-- TRIGGER SPA JS LOAD -->
<img src="x" onerror="if(typeof window.initUpdateProduct === 'function') window.initUpdateProduct(<?= $product_id ?>); this.remove();" style="display:none;">

<div class="container-fluid py-4 px-4">
    <div class="d-flex justify-content-between align-items-center mb-4 pb-3 border-bottom">
        <div>
            <h2 class="h3 text-dark fw-bold m-0"><i class="fa-solid fa-pen-to-square text-warning me-2"></i>Modify Product Properties</h2>
            <p class="text-muted small m-0 mt-1">Adjust clinical core, commercial variants, and billing rules.</p>
        </div>
        <a href="?cat=products&page=product/listProducts.php" class="btn btn-light border fw-bold text-secondary shadow-sm rounded-pill"><i class="fa-solid fa-arrow-left me-2"></i> Discard Changes</a>
    </div>

    <div id="responseMessage" class="d-none alert shadow-sm mb-4 rounded-3 border-0"></div>

    <form id="enterpriseProductUpdateForm" novalidate>
        <input type="hidden" name="id" value="<?= $product_id ?>">
        
        <div class="theme-box box-clinical border-warning">
            <h5 class="section-title text-warning"><i class="fa-solid fa-flask text-warning me-2"></i> 1. Clinical Base Definition</h5>
            <div class="row g-4 mb-4">
                <div class="col-md-4">
                    <label class="form-label">Product Type <span class="text-danger">*</span></label>
                    <select name="product_type_id" id="upd_product_type_id" class="form-select border-warning" required>
                        <option value="" selected disabled>-- Select Type --</option>
                        <?php foreach($product_types as $pt): ?>
                            <option value="<?= $pt['id'] ?>"><?= htmlspecialchars($pt['type_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Item Category <span class="text-danger">*</span></label>
                    <select name="category_id" id="upd_category_id" class="form-select border-warning" required onchange="toggleCategoryFieldsUpd()">
                        <option value="" selected disabled>-- Select Category --</option>
                        <?php foreach($categories as $cat): 
                            $cat_name = strtolower($cat['category_name']);
                            $is_drug = (strpos($cat_name, 'drug') !== false || strpos($cat_name, 'medicine') !== false || strpos($cat_name, 'pharm') !== false) ? 'true' : 'false';
                        ?>
                            <option value="<?= $cat['id'] ?>" data-is-drug="<?= $is_drug ?>"><?= htmlspecialchars($cat['category_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label id="upd_name_label" class="form-label">Clinical Generic Name <span class="text-danger">*</span></label>
                    <input type="text" name="generic_name" id="upd_generic_name" class="form-control fw-bold" required>
                </div>

                <div id="upd_drug_fields_block" class="col-12 row g-3 bg-light p-3 rounded-3 border ms-1">
                    <div class="col-md-3">
                        <label class="form-label">Therapeutic Class</label>
                        <select name="therapeutic_class_id" id="upd_therapeutic_class_id" class="form-select">
                            <option value="">-- Select Class --</option>
                            <?php foreach($therapeutic_classes as $tc): ?>
                                <option value="<?= $tc['id'] ?>"><?= htmlspecialchars($tc['class_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Formulation</label>
                        <select name="formulation_id" id="upd_formulation_id" class="form-select">
                            <option value="">-- Select Formulation --</option>
                            <?php foreach($formulations as $f): ?>
                                <option value="<?= $f['id'] ?>"><?= htmlspecialchars($f['formulation_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Strength Value</label>
                        <input type="text" name="strength_value" id="upd_strength_value" class="form-control">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Strength Unit</label>
                        <select name="strength_unit_id" id="upd_strength_unit_id" class="form-select">
                            <option value="">-- Select Unit --</option>
                            <?php foreach($units as $u): ?>
                                <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['unit_symbol']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Base Dispensing Unit <span class="text-danger">*</span></label>
                    <select name="base_uom_id" id="upd_base_uom_id" class="form-select" required onchange="syncPricingUnitUpd()">
                        <option value="" data-name="">-- Select Base Unit --</option>
                        <?php foreach($units as $u): ?>
                            <option value="<?= $u['id'] ?>" data-name="<?= htmlspecialchars($u['unit_symbol']) ?>"><?= htmlspecialchars($u['unit_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input type="hidden" name="unit_of_pricing" id="upd_unit_of_pricing_hidden">
                </div>
                
                <div class="col-md-8">
                    <label class="form-label">Universal Base Cash Price (GH₵) <span class="text-danger">*</span></label>
                    <input type="number" name="cash_price" id="upd_master_cash_price" step="0.01" min="0" class="form-control fw-bold text-success" required>
                </div>
            </div>

            <div class="border-top pt-4">
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <label class="form-label m-0 fs-6 text-dark fw-bold">Commercial Brands Architecture</label>
                    <button type="button" class="btn btn-sm btn-success fw-bold shadow-sm rounded-pill px-3" onclick="addBrandRowUpd()"><i class="fa-solid fa-plus me-1"></i> Add Brand Link</button>
                </div>
                <div class="table-responsive">
                    <table class="table rimax-table align-middle">
                        <thead>
                            <tr>
                                <th style="width: 25%;">Brand Name <span class="text-danger">*</span></th>
                                <th style="width: 20%;">Manufacturer <span class="text-danger">*</span></th>
                                <th style="width: 15%;">Barcode (Opt)</th>
                                <th style="width: 10%;">Pack Size</th>
                                <th style="width: 10%;">Cost (GH₵)</th>
                                <th style="width: 12%;">Selling (GH₵)</th>
                                <th class="text-center">Drop</th>
                            </tr>
                        </thead>
                        <tbody id="upd_brandTableBody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="theme-box box-nhis">
            <div class="d-flex align-items-center justify-content-between mb-4">
                <h5 class="section-title text-warning m-0 border-0"><i class="fa-solid fa-file-prescription text-warning me-2"></i> 2. Unified Insurance (NHIS) Rules</h5>
                <div class="form-check form-switch m-0 d-flex align-items-center gap-2">
                    <input class="form-check-input rimax-switch bg-warning border-warning" type="checkbox" name="nhis_covered" id="upd_nhis_cov_main" value="1" onchange="toggleNhisBlockUpd()">
                    <label class="form-check-label fw-bold text-dark fs-6" for="upd_nhis_cov_main">Covered by NHIS</label>
                </div>
            </div>
            <div id="upd_nhis_logic_block" class="row g-4 bg-white p-4 rounded-3 border shadow-sm">
                <div class="col-md-4">
                    <label class="form-label">NHIS Drug / Item Code</label>
                    <input type="text" name="nhis_drug_code" id="upd_nhis_drug_code" class="form-control upd-nhis-input">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Prescribing Level</label>
                    <select name="prescribing_level" id="upd_prescribing_level" class="form-select upd-nhis-input">
                        <option value="">-- Select Level --</option>
                        <?php foreach($prescribe_levels as $l): ?>
                            <option value="<?= htmlspecialchars($l['level_code']) ?>"><?= htmlspecialchars($l['level_code']) ?> - <?= htmlspecialchars($l['description']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label text-success">Universal GDRG Tariff (GH₵)</label>
                    <input type="number" name="gdrg_tariff" id="upd_gdrg_tariff" step="0.01" class="form-control border-success upd-nhis-input fw-bold">
                </div>
                <div class="col-12 mt-4 pt-4 border-top d-flex align-items-center gap-4">
                    <div class="form-check form-switch d-flex align-items-center gap-2 m-0">
                        <input class="form-check-input rimax-switch bg-danger border-danger upd-nhis-input" type="checkbox" name="is_nhis_copay_required" id="upd_nhis_copay_chk" value="1" onchange="toggleNhisCopayUpd()">
                        <label class="form-check-label text-danger fw-bold" for="upd_nhis_copay_chk">Requires Patient Co-Payment</label>
                    </div>
                    <div class="w-25">
                        <input type="number" name="copay_amount" id="upd_nhis_copay_amt" step="0.01" class="form-control border-danger fw-bold" placeholder="Amount (GH₵)" disabled>
                    </div>
                </div>
            </div>
        </div>

        <div class="theme-box box-corp">
             <div class="d-flex align-items-center justify-content-between mb-4">
                <h5 class="section-title text-info m-0 border-0"><i class="fa-solid fa-building-shield text-info me-2"></i> 3. Private / Corporate Matrix</h5>
                <div class="form-check form-switch m-0 d-flex align-items-center gap-2">
                    <input class="form-check-input rimax-switch upd-corp-switch" type="checkbox" name="corp_covered" id="upd_corp_cov_main" value="1" onchange="toggleCorpBlockUpd()">
                    <label class="form-check-label fw-bold text-dark fs-6" for="upd_corp_cov_main">Covered by HMO</label>
                </div>
            </div>
            <div id="upd_corp_logic_block" class="table-responsive">
                <table class="table rimax-table">
                    <thead>
                        <tr>
                            <th class="w-25">Insurance Provider</th>
                            <th>Agreed HMO Tariff (GH₵)</th>
                            <th class="text-center">Co-Payment Rule</th>
                            <th>Co-Pay Amount (GH₵)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($insurances as $ins): $id = $ins['id']; ?>
                        <tr>
                            <td>
                                <div class="form-check form-switch d-flex align-items-center gap-2 m-0">
                                    <input class="form-check-input upd-corp-switch upd-corp-master-chk" type="checkbox" name="corp_mapped[<?= $id ?>]" id="upd_map_<?= $id ?>" value="1" onchange="toggleCorpRowUpd('<?= $id ?>')" disabled>
                                    <label class="form-check-label fw-bold text-primary" for="upd_map_<?= $id ?>"><?= htmlspecialchars($ins['insurance_name']) ?></label>
                                </div>
                            </td>
                            <td><input type="number" name="corp_tariff[<?= $id ?>]" id="upd_tar_<?= $id ?>" step="0.01" class="form-control fw-bold text-success" disabled></td>
                            <td class="text-center">
                                <div class="form-check form-switch d-inline-flex align-items-center gap-2 m-0">
                                    <input class="form-check-input rimax-switch bg-danger border-danger" type="checkbox" name="corp_copay_req[<?= $id ?>]" id="upd_req_<?= $id ?>" value="1" onchange="toggleCorpCopayUpd('<?= $id ?>')" disabled>
                                </div>
                            </td>
                            <td><input type="number" name="corp_copay_amt[<?= $id ?>]" id="upd_amt_<?= $id ?>" step="0.01" class="form-control text-danger fw-bold" disabled></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="d-flex justify-content-end gap-3 pt-3 mt-4 border-top">
            <button type="submit" id="btnUpdateForm" class="btn btn-warning px-5 fw-bold btn-lg shadow-sm text-dark">
                <i class="fa-solid fa-cloud-arrow-up me-2"></i> Save Updates & Distribute
            </button>
        </div>
    </form>
</div>

<!-- Includes the specific external controller for Update logic -->
<script src="<?php echo BASE_URL; ?>application/assets/js/updateProduct.js?v=<?= time() ?>"></script>