<?php  
session_start();
ini_set('display_errors', 0);
require_once '../../dripend/includes/db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cash & Carry Dispense | eRHAMS</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    body { background-color: #f8fafc; font-family: 'Inter', sans-serif; overflow-x: hidden; }
    .main-content-wrapper { margin-left: 260px; padding: 2rem; width: calc(100% - 260px); min-height: 100vh; }
    @media (max-width: 992px) { .main-content-wrapper { margin-left: 0; width: 100%; padding: 1.5rem; } }
    .desk-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;}
    .content-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.02); overflow:hidden;}
    .table thead th { background: #f8fafc; color: #475569; padding: 15px; font-weight: 800; font-size: 12px; text-transform: uppercase; border-bottom: 1px solid #e2e8f0;}
    .table tbody td { padding: 15px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
    .qty-input, .price-input { width: 100%; text-align: center; font-weight: 800; border-radius: 8px; border: 1px solid #cbd5e1; padding: 8px;}
    .price-input[readonly] { background: #e0f2fe; color: #0284c7; border-color: #bae6fd;}
</style>
</head>
<body>

<?php include '../../dripend/statpages/sidebar.php'; ?>

<div class="main-content-wrapper">
    <div class="desk-header">
        <h4><i class="fa-solid fa-bolt text-warning me-2"></i> OTC / Walk-In Cash Dispense</h4>
        <div class="d-flex align-items-center gap-3 bg-white px-4 py-2 rounded-pill border shadow-sm">
            <span class="fw-bold text-muted small text-uppercase">Dispensary:</span>
            <select id="active_dispensary" class="form-select form-select-sm fw-bold border-0 text-primary p-0" style="width:200px; box-shadow:none; cursor:pointer; font-size:14px;"></select>
        </div>
    </div>

    <div class="content-card p-4">
        <form id="frmDirectDispense">
            
            <!-- ADVANCED SEARCH -->
            <div class="row g-3 mb-4 border-bottom pb-4">
                <div class="col-12">
                    <label class="small fw-bold text-primary mb-1"><i class="fa-solid fa-search"></i> Search Registered Patient (Optional)</label>
                    <select id="registered_patient_search" class="form-select w-100"></select>
                </div>
            </div>

            <div class="row g-3 mb-4">
                <input type="hidden" name="patient_no" id="hidden_patient_no" value="WALK-IN">
                <div class="col-md-6">
                    <label class="small fw-bold text-dark mb-1">Walk-in Patient Name</label>
                    <input type="text" name="patient_name" id="pat_name" class="form-control fw-bold" placeholder="e.g. John Doe" required>
                </div>
                <div class="col-md-6">
                    <label class="small fw-bold text-dark mb-1">Mobile Number</label>
                    <input type="text" name="mobile" id="pat_mobile" class="form-control" placeholder="Optional">
                </div>
            </div>

            <div class="table-responsive border rounded-3 mb-4">
                <table class="table mb-0" id="tblOTC">
                    <thead>
                        <tr>
                            <th width="40%">Medication / Product</th>
                            <th width="15%">Unit Price</th>
                            <th width="15%">Quantity</th>
                            <th width="20%">Subtotal</th>
                            <th width="10%" class="text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody id="otc_body"></tbody>
                </table>
            </div>
            
            <div class="d-flex justify-content-between align-items-center bg-light p-3 rounded-3 border">
                <button type="button" class="btn btn-outline-dark fw-bold" onclick="addOtcRow()"><i class="fa-solid fa-plus"></i> Add Item Row</button>
                <div class="text-end">
                    <span class="small fw-bold text-muted text-uppercase d-block mb-1">Total Amount Due</span>
                    <h3 class="m-0 fw-bold text-dark" id="lblGrandTotal">GHS 0.00</h3>
                </div>
                <button type="submit" class="btn btn-success px-5 py-3 shadow-sm fw-bold fs-5" id="btnSubmitOTC"><i class="fa-solid fa-cash-register me-2"></i> Dispense & Bill Patient</button>
            </div>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    let otcDrugs = [];
    let rowCount = 0;
    const API_OTC = '/rimax/application/dripend/includes/dispensary/processDirectDrugDispense.php';
    
    $(document).ready(async function() {
        try {
            // Patient Search init
            $('#registered_patient_search').select2({
                placeholder: 'Type Name or ID to search Database...',
                allowClear: true,
                ajax: {
                    url: API_OTC, type: 'GET', dataType: 'json', delay: 250,
                    data: function (params) { return { action: 'search_patient', term: params.term }; },
                    processResults: function (data) { return { results: data.results }; }
                }
            }).on('select2:select', function(e) {
                let p = e.params.data;
                $('#pat_name').val(p.fname + ' ' + p.lname).attr('readonly', true);
                $('#pat_mobile').val(p.mobile).attr('readonly', true);
                $('#hidden_patient_no').val(p.id);
            }).on('select2:unselect', function(e) {
                $('#pat_name').val('').removeAttr('readonly');
                $('#pat_mobile').val('').removeAttr('readonly');
                $('#hidden_patient_no').val('WALK-IN');
            });

            // Load locations
            const fData = new FormData(); fData.append('action', 'fetch_dependencies');
            const res = await fetch('/rimax/application/dripend/includes/dispensary/processDrugDispense.php', { method: 'POST', body: fData });
            const json = await res.json();
            
            const locSelect = document.getElementById('active_dispensary');
            json.locations.forEach(loc => {
                let sel = (loc.location_name.includes('Cash & Carry') || loc.location_name.includes('Main')) ? 'selected' : '';
                locSelect.insertAdjacentHTML('beforeend', `<option value="${loc.id}" ${sel}>${loc.location_name}</option>`);
            });

            // Load products
            const pdRes = await fetch(API_OTC + '?action=get_products');
            const pdJson = await pdRes.json();
            otcDrugs = pdJson.data;

            addOtcRow();
        } catch(e) { console.error(e); }
    });

    function addOtcRow() {
        rowCount++;
        let opts = '<option value="">-- Select Product --</option>';
        otcDrugs.forEach(d => { opts += `<option value="${d.id}" data-price="${d.price}">${d.name}</option>`; });
        
        let row = `<tr id="row_${rowCount}">
            <td><select name="service_id[]" class="form-select select2-drug" onchange="updatePrice(${rowCount}, this)" required>${opts}</select></td>
            <td><input type="number" step="0.01" name="unit_price[]" id="price_${rowCount}" class="price-input" readonly value="0.00"></td>
            <td><input type="number" name="qty[]" id="qty_${rowCount}" class="qty-input" min="1" value="1" oninput="calcTotals()" required></td>
            <td><input type="text" id="sub_${rowCount}" class="price-input text-end" readonly value="0.00"></td>
            <td class="text-center"><button type="button" class="btn btn-sm btn-danger" onclick="$('#row_${rowCount}').remove(); calcTotals();"><i class="fa-solid fa-trash"></i></button></td>
        </tr>`;
        $('#otc_body').append(row);
        $('.select2-drug').select2({ theme: 'bootstrap-5' });
    }

    function updatePrice(id, sel) {
        let price = $(sel).find(':selected').data('price') || 0;
        $('#price_' + id).val(parseFloat(price).toFixed(2));
        calcTotals();
    }

    function calcTotals() {
        let grandTotal = 0;
        $('#otc_body tr').each(function() {
            let id = $(this).attr('id').split('_')[1];
            let p = parseFloat($('#price_' + id).val()) || 0;
            let q = parseInt($('#qty_' + id).val()) || 0;
            let sub = p * q;
            $('#sub_' + id).val(sub.toFixed(2));
            grandTotal += sub;
        });
        $('#lblGrandTotal').text('GHS ' + grandTotal.toFixed(2));
    }

    $('#frmDirectDispense').on('submit', async function(e) {
        e.preventDefault();
        let btn = $('#btnSubmitOTC');
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Processing...');
        
        let fd = new FormData(this);
        fd.append('action', 'process_otc_dispense');
        fd.append('location_id', $('#active_dispensary').val());

        try {
            const res = await fetch(API_OTC, { method: 'POST', body: fd });
            const json = await res.json();
            if(json.status === 'success') {
                alert("Successfully Dispensed! Invoice Number: " + json.invoice_no);
                location.reload();
            } else throw new Error(json.message);
        } catch(err) {
            alert(err.message);
            btn.prop('disabled', false).html('<i class="fa-solid fa-cash-register me-2"></i> Dispense & Bill Patient');
        }
    });
</script>
</body>
</html>