<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

include('includes/db.php');
include('includes/header.php');

/* ================= AUTH ================= */
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$facility_id = $_SESSION['facility_id'] ?? null;
if (!$facility_id) {
    $_SESSION['flash'] = ['message'=>'No facility assigned to your account.','color'=>'#dc3545'];
    header("Location: dashboard.php");
    exit;
}

/* ================= CSRF ================= */
if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
$csrf = $_SESSION['csrf_token'];

/* ================= GET PRODUCT ================= */
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) die("Invalid product ID");
$product_id = (int)$_GET['id'];

$stmt = $pdo->prepare("SELECT * FROM products WHERE id=? AND facility_id=?");
$stmt->execute([$product_id, $facility_id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$product) die("Product not found");

/* ================= Product Categories ================= */
$categories = ["Drug","Medical Act","Consumable","Lab Test","Imaging Type"];

/* ================= Insurance Partners ================= */
$stmt = $pdo->prepare("SELECT * FROM insurance_partners WHERE status='enabled' AND facility_id=? ORDER BY name ASC");
$stmt->execute([$facility_id]);
$insurancePartners = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ================= Fetch names for all categories ================= */
$stmt = $pdo->prepare("SELECT id, drug_name FROM drugs WHERE status='enabled' AND facility_id=?"); $stmt->execute([$facility_id]); $drugs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare("SELECT id, consumable_name FROM consumables WHERE status='enabled' AND facility_id=?"); $stmt->execute([$facility_id]); $consumables = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare("SELECT id, lab_test_name FROM lab_test WHERE status='enabled' AND facility_id=?"); $stmt->execute([$facility_id]); $lab_tests = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare("SELECT id, name FROM medical_acts WHERE status='enabled' AND facility_id=?"); $stmt->execute([$facility_id]); $medical_acts = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ================= Fetch Imaging Types (UPDATED to match add page) ================= */
$stmt = $pdo->prepare("SELECT id, name FROM imaging WHERE status='enabled' AND facility_id=?");
$stmt->execute([$facility_id]);
$imaging_types = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ================= Fetch real product name and category (UPDATED for imaging) ================= */
$real_name = '';
$real_category = '';
switch($product['category_type']){
    case 'drug':
        $stmt = $pdo->prepare("SELECT drug_name FROM drugs WHERE id=? AND facility_id=?");
        $stmt->execute([$product['category_id'],$facility_id]);
        $real_name = $stmt->fetchColumn();
        $real_category = 'Drug';
        break;
    case 'consumable':
        $stmt = $pdo->prepare("SELECT consumable_name FROM consumables WHERE id=? AND facility_id=?");
        $stmt->execute([$product['category_id'],$facility_id]);
        $real_name = $stmt->fetchColumn();
        $real_category = 'Consumable';
        break;
    case 'lab_test':
        $stmt = $pdo->prepare("SELECT lab_test_name FROM lab_test WHERE id=? AND facility_id=?");
        $stmt->execute([$product['category_id'],$facility_id]);
        $real_name = $stmt->fetchColumn();
        $real_category = 'Lab Test';
        break;
    case 'medical_act':
        $stmt = $pdo->prepare("SELECT name FROM medical_acts WHERE id=? AND facility_id=?");
        $stmt->execute([$product['category_id'],$facility_id]);
        $real_name = $stmt->fetchColumn();
        $real_category = 'Medical Act';
        break;
    case 'imaging': // UPDATED: Changed from 'imaging_type' to 'imaging'
        $stmt = $pdo->prepare("SELECT name FROM imaging WHERE id=? AND facility_id=?");
        $stmt->execute([$product['category_id'],$facility_id]);
        $real_name = $stmt->fetchColumn();
        $real_category = 'Imaging Type';
        break;
}

/* ================= Fetch existing insurance prices ================= */
$stmt = $pdo->prepare("SELECT insurance_partner_id, price FROM product_insurance_prices WHERE product_id=?");
$stmt->execute([$product_id]);
$existingPrices = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

/* ================= HANDLE EDIT (UPDATED for imaging) ================= */
$errors = [];
if(isset($_POST['edit']) && $_POST['csrf']===$csrf){
    $category = $_POST['category'];
    $name = trim($_POST['product_name']);
    $category_id = null;

    if($category==='Drug') {
        foreach($drugs as $d) if($d['drug_name']===$name) $category_id=$d['id'];
    } elseif($category==='Consumable') {
        foreach($consumables as $c) if($c['consumable_name']===$name) $category_id=$c['id'];
    } elseif($category==='Lab Test') {
        foreach($lab_tests as $l) if($l['lab_test_name']===$name) $category_id=$l['id'];
    } elseif($category==='Medical Act') {
        foreach($medical_acts as $m) if($m['name']===$name) $category_id=$m['id'];
    } elseif($category==='Imaging Type') {
        foreach($imaging_types as $img) if($img['name']===$name) $category_id=$img['id']; // UPDATED: Changed from 'type_name' to 'name'
    }

    // UPDATED: Fixed category_enum mapping
    if($category==='Drug') $category_enum='drug';
    elseif($category==='Consumable') $category_enum='consumable';
    elseif($category==='Lab Test') $category_enum='lab_test';
    elseif($category==='Medical Act') $category_enum='medical_act';
    elseif($category==='Imaging Type') $category_enum='imaging';

    if(empty($errors)){
        $stmt = $pdo->prepare("UPDATE products SET name=?, category_id=?, category_type=? WHERE id=? AND facility_id=?");
        $stmt->execute([$name,$category_id,$category_enum,$product_id,$facility_id]);

        // Reset insurance prices
        $stmtDel = $pdo->prepare("DELETE FROM product_insurance_prices WHERE product_id=?");
        $stmtDel->execute([$product_id]);

        if(!empty($_POST['insurance_price'])){
            foreach($_POST['insurance_price'] as $row){
                $iid = $row['id'];
                $price = floatval($row['price']);
                $stmtIns = $pdo->prepare("INSERT INTO product_insurance_prices (product_id, insurance_partner_id, price) VALUES (?,?,?)");
                $stmtIns->execute([$product_id, $iid, $price]);
            }
        }

        $_SESSION['flash'] = ['message'=>'Product updated successfully','color'=>'#28a745'];
        header("Location: products.php"); exit;
    }

    $_SESSION['flash'] = ['message'=>implode(' | ',$errors),'color'=>'#dc3545'];
    header("Location: products.php"); exit;
}
?>

<!-- ================= PAGE DESIGN ================= -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
<?php include('includes/navbar.php'); ?>
</nav>
<div data-scroll-to-active="true" class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
<?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
<div class="content-wrapper">
<div class="col-xs-12">
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<h4 class="card-title">Edit Product Tariff</h4>
<a href="products.php" class="btn btn-outline-secondary btn-md"><i class="icon-arrow-left-circle"></i> Back</a>
</div>
<div class="card-body collapse in">
<div class="card-block card-dashboard">
<form method="post">
<input type="hidden" name="csrf" value="<?= $csrf ?>">

<div class="row">
<div class="col-md-6">
<label>Category *</label>
<select class="form-control" name="category" id="categorySelect" required>
<option value="">-- Select --</option>
<?php foreach($categories as $cat): ?>
<option value="<?= $cat ?>" <?= $cat==$real_category?'selected':'' ?>><?= $cat ?></option>
<?php endforeach; ?>
</select>
<div id="productNameDiv" style="margin-top:10px;"></div>
</div>

<div class="col-md-6">
<h5>Insurance Prices *</h5>
<div id="insuranceContainer"></div>
<button type="button" id="addInsuranceBtn" class="btn btn-primary btn-sm mt-2">+ Add Insurance</button>
</div>
</div>

<div class="mt-3">
<button type="submit" class="btn btn-primary btn-md btn-block" name="edit"><i class="icon-check"></i> Update Product Tariff</button>
<a href="products.php" class="btn btn-secondary btn-md btn-block">Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>

<?php include('includes/footer.php'); ?>

<script>
const drugs = <?= json_encode(array_column($drugs,'drug_name')) ?>;
const consumables = <?= json_encode(array_column($consumables,'consumable_name')) ?>;
const lab_tests = <?= json_encode(array_column($lab_tests,'lab_test_name')) ?>;
const medical_acts = <?= json_encode(array_column($medical_acts,'name')) ?>;
const imaging_types = <?= json_encode(array_column($imaging_types,'name')) ?>; // UPDATED: Changed from 'type_name' to 'name'
const insurancePartners = <?= json_encode($insurancePartners) ?>;
const existingPrices = <?= json_encode($existingPrices) ?>;
const currentCategory = "<?= $real_category ?>";
const currentName = "<?= addslashes($real_name) ?>";

let insuranceCount = 0;
const selectedInsurance = new Set();

// ---------- Product Name Dropdown ----------
function renderProductNameDropdown(category){
    let names = [];
    if(category==='Drug') names = drugs;
    else if(category==='Consumable') names = consumables;
    else if(category==='Lab Test') names = lab_tests;
    else if(category==='Medical Act') names = medical_acts;
    else if(category==='Imaging Type') names = imaging_types;

    let html = '<label>Product Name *</label><select class="form-control" id="productNameSelect" name="product_name" required>';
    html += '<option value="">-- Select --</option>';
    names.forEach(n=>{
        const selected = n === currentName ? 'selected' : '';
        html += `<option value="${n}" ${selected}>${n}</option>`;
    });
    html += '</select>';
    $('#productNameDiv').html(html);
    $('#productNameSelect').select2({placeholder:"Select a product",width:'100%'});
}

$('#categorySelect').on('change', function(){ renderProductNameDropdown($(this).val()); });
renderProductNameDropdown(currentCategory);

// ---------- Insurance Logic ----------
function addInsuranceRow(sel=null, val=null){
    insuranceCount++;
    if(sel) selectedInsurance.add(Number(sel));
    
    // Build options for insurance select
    let options = '<option value="">-- Select Insurance --</option>';
    insurancePartners.forEach(i => {
        const selected = sel==i.id ? 'selected' : '';
        const disabled = selectedInsurance.has(Number(i.id)) && sel!=i.id ? 'disabled' : '';
        options += `<option value="${i.id}" ${selected} ${disabled}>${i.name}${disabled ? ' (Already Selected)' : ''}</option>`;
    });
    
    const html = `<div class="mb-2" id="insuranceRow${insuranceCount}">
        <select class="form-control d-inline-block insuranceSelect" style="width:60%" name="insurance_price[${insuranceCount}][id]" required>${options}</select>
        <input type="number" step="0.01" class="form-control d-inline-block" style="width:35%" name="insurance_price[${insuranceCount}][price]" value="${val!==null?val:''}" placeholder="Price" required>
        <button type="button" class="btn btn-danger btn-sm" onclick="removeInsurance(${insuranceCount})">X</button>
    </div>`;
    $('#insuranceContainer').append(html);
}

function removeInsurance(id){
    const sel = $(`#insuranceRow${id} select`).val();
    if(sel) selectedInsurance.delete(Number(sel));
    $(`#insuranceRow${id}`).remove();
}

// Populate existing insurance prices
Object.keys(existingPrices).forEach(id=> addInsuranceRow(id, existingPrices[id]));

// Add new insurance dynamically
$('#addInsuranceBtn').on('click', function(){
    const available = insurancePartners.filter(i => !selectedInsurance.has(Number(i.id)));
    if(available.length===0){ 
        showToast("All insurance partners already added.", "#dc3545");
        return; 
    }
    addInsuranceRow();
});

// Prevent duplicate insurance selection
$(document).on('change','.insuranceSelect', function(){
    const prevVal = $(this).data('prev');
    if(prevVal) selectedInsurance.delete(Number(prevVal));
    const val = $(this).val();
    if(!val || val===''){ $(this).data('prev',null); return; }
    const valNum = Number(val);
    if(selectedInsurance.has(valNum)){ 
        showToast("Insurance already selected!", "#dc3545");
        $(this).val(''); 
        $(this).data('prev',null); 
        return; 
    }
    selectedInsurance.add(valNum);
    $(this).data('prev',val);
});

// ---------- Toast Function ----------
function showToast(message, color='#28a745'){
    const t = document.createElement('div');
    t.className = 'toast-message';
    t.style.background = color;
    t.innerText = message;
    document.body.appendChild(t);
    setTimeout(() => t.remove(), 4000);
}

// ---------- Show flash messages ----------
<?php if(isset($_SESSION['flash'])): ?>
showToast('<?= addslashes($_SESSION['flash']['message']) ?>', '<?= $_SESSION['flash']['color'] ?>');
<?php unset($_SESSION['flash']); endif; ?>
</script>

<style>
.toast-message {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 12px 20px;
    color: #fff;
    border-radius: 5px;
    z-index: 9999;
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    font-size: 14px;
    animation: fadein 0.5s, fadeout 0.5s 3.5s;
}
@keyframes fadein { from {opacity:0;} to {opacity:1;} }
@keyframes fadeout { from {opacity:1;} to {opacity:0;} }
</style>