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

session_start();

/* ================= Session Timeout (12 hours) ================= */
$SESSION_TIMEOUT = 43200;

if (isset($_SESSION['LAST_ACTIVITY'])) {
    if (time() - $_SESSION['LAST_ACTIVITY'] > $SESSION_TIMEOUT) {
        session_unset();
        session_destroy();
        header("Location: login.php?timeout=1");
        exit;
    }
}
$_SESSION['LAST_ACTIVITY'] = time();

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'];

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

/* ================= Insurance Partners (facility only) ================= */
$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 Per Facility ================= */
$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);

// Add Imaging Types query
$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);

/* ================= Existing Products (facility only) ================= */
$stmt = $pdo->prepare("
    SELECT name, category_id, category_type
    FROM products
    WHERE facility_id=?
");
$stmt->execute([$facility_id]);
$existingProducts = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ================= ADD PRODUCT ================= */
$errors = [];

if (isset($_POST['add']) && $_POST['csrf'] === $csrf) {

    /* -------- Insurance Prices -------- */
    $insurance_prices_array = [];

    if (!empty($_POST['insurance_price'])) {
        foreach ($_POST['insurance_price'] as $row) {
            $id    = $row['id'] ?? null;
            $price = $row['price'] ?? null;

            if (!$id || $price === '') {
                $errors[] = "Insurance and price are required for all rows.";
                continue;
            }

            if (isset($insurance_prices_array[$id])) {
                $errors[] = "Duplicate insurance partner selected.";
                continue;
            }

            $insurance_prices_array[$id] = $price;
        }
    }

    /* -------- Category Mapping -------- */
    $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'];
        $category_enum = 'drug';
    } elseif ($category === 'Consumable') {
        foreach ($consumables as $c) if ($c['consumable_name'] === $name) $category_id = $c['id'];
        $category_enum = 'consumable';
    } elseif ($category === 'Lab Test') {
        foreach ($lab_tests as $l) if ($l['lab_test_name'] === $name) $category_id = $l['id'];
        $category_enum = 'lab_test';
    } elseif ($category === 'Medical Act') {
        foreach ($medical_acts as $m) if ($m['name'] === $name) $category_id = $m['id'];
        $category_enum = 'medical_act';
    } elseif ($category === 'Imaging Type') {
        foreach ($imaging_types as $i) if ($i['name'] === $name) $category_id = $i['id'];
        $category_enum = 'imaging';
    }

    /* -------- DUPLICATE CHECK (facility only) -------- */
    if (empty($errors)) {

        $stmt = $pdo->prepare("
            SELECT id
            FROM products
            WHERE name=? AND category_id=? AND facility_id=?
        ");
        $stmt->execute([$name, $category_id, $facility_id]);
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($products as $p) {
            $priceStmt = $pdo->prepare("
                SELECT insurance_partner_id, price
                FROM product_insurance_prices
                WHERE product_id=?
            ");
            $priceStmt->execute([$p['id']]);
            $existingPrices = $priceStmt->fetchAll(PDO::FETCH_KEY_PAIR);

            if (count($existingPrices) === count($insurance_prices_array)) {
                $match = true;
                foreach ($insurance_prices_array as $iid => $price) {
                    if (!isset($existingPrices[$iid]) || (float)$existingPrices[$iid] !== (float)$price) {
                        $match = false;
                        break;
                    }
                }
                if ($match) {
                    $errors[] = "Product already exists for this facility.";
                    break;
                }
            }
        }
    }

    /* -------- INSERT -------- */
    if (empty($errors)) {

        $stmt = $pdo->prepare("
            INSERT INTO products (facility_id, name, category_id, category_type, price)
            VALUES (?, ?, ?, ?, 0.00)
        ");
        $stmt->execute([$facility_id, $name, $category_id, $category_enum]);

        $product_id = $pdo->lastInsertId();

        $stmt = $pdo->prepare("
            INSERT INTO product_insurance_prices (product_id, insurance_partner_id, price)
            VALUES (?, ?, ?)
        ");
        foreach ($insurance_prices_array as $iid => $price) {
            $stmt->execute([$product_id, $iid, $price]);
        }

        $_SESSION['flash'] = [
            'message' => 'Product & insurance prices added 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">Add New Product Tarrif</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 ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <div id="productNameDiv" style="margin-top:10px;"></div>
                            </div>

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

                        <div class="mt-3">
                            <button type="submit" class="btn btn-primary btn-md btn-block" name="add">
                                <i class="icon-plus-circle"></i> Add Product Tarrif
                            </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'); ?>

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

<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')) ?>;
const insurancePartners = <?= json_encode($insurancePartners) ?>;
const existingProducts = <?= json_encode($existingProducts) ?>;

$('#categorySelect').on('change', function(){
    const val = $(this).val();
    let html = '<label>Product Name *</label><select class="form-control" id="productNameSelect" name="product_name" required><option value="">-- Select --</option>';

    let names = [];
    let categoryField = '';
    
    if(val==='Drug') {
        names = drugs;
        categoryField = 'drug_name';
    } else if(val==='Consumable') {
        names = consumables;
        categoryField = 'consumable_name';
    } else if(val==='Lab Test') {
        names = lab_tests;
        categoryField = 'lab_test_name';
    } else if(val==='Medical Act') {
        names = medical_acts;
        categoryField = 'name';
    } else if(val==='Imaging Type') {
        names = imaging_types;
        categoryField = 'name';
    }

    // Disable already added products - FIXED FOR ALL CATEGORIES
    const disabledNames = existingProducts
        .filter(p => {
            // Map category display name to ENUM value
            let enumValue = '';
            if (val === 'Drug') enumValue = 'drug';
            else if (val === 'Consumable') enumValue = 'consumable';
            else if (val === 'Lab Test') enumValue = 'lab_test';
            else if (val === 'Medical Act') enumValue = 'medical_act';
            else if (val === 'Imaging Type') enumValue = 'imaging';
            
            return p.category_type === enumValue;
        })
        .map(p => p.name);

    names.forEach(n => {
        const disabled = disabledNames.includes(n) ? 'disabled' : '';
        html += `<option value="${n}" ${disabled}>${n}${disabled ? ' (Already Added)' : ''}</option>`;
    });

    html += '</select>';
    $('#productNameDiv').html(html);
    $('#productNameSelect').select2({ placeholder: "Select a product", width: '100%' });
});

// ---------- Insurance Logic ----------
let insuranceCount = 0;
let selectedInsurance = new Set();

function buildInsuranceOptions() {
    const available = insurancePartners.filter(i => !selectedInsurance.has(Number(i.id)));
    if (available.length === 0) return null;
    let options = '<option value="">-- Select Insurance --</option>';
    available.forEach(i => { options += `<option value="${i.id}">${i.name}</option>`; });
    return options;
}

$('#addInsuranceBtn').on('click', function(){
    const options = buildInsuranceOptions();
    if (!options) {
        showToast("All insurance partners already added.", "#dc3545");
        return;
    }
    insuranceCount++;
    const rowId = `insuranceRow${insuranceCount}`;
    const html = `<div class="mb-2" id="${rowId}">
        <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]" 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();
}

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