 <?php
// Find selected shift object from $shifts array
$selectedShiftObj = null;
if (!empty($shifts) && !empty($selected_shift)) {
    foreach ($shifts as $s) {
        if ($s->id == $selected_shift) {
            $selectedShiftObj = $s;
            break;
        }
    }
}
?>

 <?php
                    // Explicit action: form index page ke modal aur add page dono jagah use hoti hai,
                    // is liye khali action (current URL) ki bajaye clearly /admin/tokens/add pe submit
                    // karni chahiye — warna index ki modal apne upar POST karke token create nahi karti.
                    $attributes = ['name' => 'formAdd', 'id' => 'formAdd', 'class' => 'form-validation'];
                    echo form_open_multipart('admin/tokens/add', $attributes);
                ?>
                <!-- Hidden shift_id (FK must match kns1_shifts.id) -->
                <input type="hidden" name="shift_id" value="<?= !empty($selectedShiftObj) ? $selectedShiftObj->id : '' ?>">

                <!-- Hidden token_number (auto-generated for this shift) -->
                <input type="hidden" name="token_number" value="<?= !empty($autoGeneratedToken) ? $autoGeneratedToken : '' ?>">
            <div class="patient-data">
                <div class="row">
                    <!-- Name -->
                    <div class="col-4">
                        <div class="form-group">
                            <label for="name">Name</label>
                            <input type="text" id="name" name="name" class="form-control" placeholder="Enter Name" required>
                        </div>
                    </div>
                    <!-- Contact Number -->
                    <div class="col-4">
                        <div class="form-group">
                            <label for="phone">Contact Number</label>
                            <input type="text" id="phone" name="phone" onkeyup="addDashes(this)" 
                                   class="form-control" minlength="12" maxlength="12" placeholder="Patient Contact">
                        </div>
                    </div>
                    <!-- Gender -->
                    <div class="col-2">
                        <div class="form-group">
                            <label for="gender">Gender</label>
                            <select id="gender" name="gender" class="form-control" required>
                                <option value="">Select Gender</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                    </div>
                    <!-- Age -->
                    <div class="col-2">
                        <div class="form-group">
                            <label for="age">Age</label>
                            <div class="input-group">
                                <input type="number" id="age" name="age" class="form-control" placeholder="Age" min="0" required>
                                <select id="age_unit" name="age_unit" class="form-control" style="max-width:120px;" required>
                                    <option value="Years">Years</option>
                                    <option value="Months">Months</option>
                                    <option value="Days">Days</option>
                                </select>
                            </div>
                            <!-- <small class="form-text text-muted">Enter age and select unit (Years/Months/Days)</small> -->
                        </div>
                    </div>
                </div>

                <div class="row py-2">
                    <div class="col-4">
                        <label for="departments" class="py-2">Select Departments</label>
                        <div class="form-group select-service">
                            
                            <div id="departments">
                                <?php foreach ($departments as $d): ?>
                                <div class="form-check">
                                        <input class="form-check-input dept-checkbox" type="checkbox" value="<?= $d->id ?>" id="dep<?= $d->id ?>">
                                        <label class="form-check-label" for="dep<?= $d->id ?>"><?= $d->name ?></label>
                                            </div>
                                <?php endforeach; ?>
                                </div>
                        </div>
                    </div>
                    <div class="col-4 px-0">
                        <label for="services" class="py-2">Select Consultants</label>
                        <div class="form-group select-service">
                            <div id="services"></div>
                        </div>
                    </div>
                    <div class="col-4">
                        <label for="sub_services" class="py-2">Select Services</label>
                        <div class="form-group select-service">
                            <input type="text" id="sub_service_search" class="form-control mb-2" placeholder="Search Sub-Services...">
                            <div id="sub_services"></div>
                        </div>
                    </div>
                </div>

                <div class="row py-2">
                    <!-- <div class="col-md-3">
                        <div class="form-check mb-2">
                            <input type="checkbox" class="form-check-input" id="toggle_panel" />
                            <label class="form-check-label" for="toggle_panel">Panel/Funded</label>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group" id="panel_group" style="display:none;">
                            <select id="panel_type" name="funded_by" class="form-control">
                                <option value="">Select Panel</option>
                                <option value="Jamia Masjid" data-discount="50">Jamia Masjid</option>
                            </select>
                        </div>
                    </div> -->
                    <div class="col-md-6">
                        <div class="form-check mb-2">
                            <input type="checkbox" class="form-check-input" id="toggle_panel">
                            <label class="form-check-label" for="toggle_panel">
                                Panel / Funded
                            </label>
                        </div>
                    </div>
                    <input type="hidden" name="funded_by" id="funded_by" value="">

                    <div class="col-md-3">
                         <div class="form-check mb-2">
                            <input type="checkbox" class="form-check-input" id="toggle_discount" />
                            <label class="form-check-label" for="toggle_discount">Apply Discount?</label>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group" id="discount_group" style="display:none;">
                            <input type="number" id="discount_type" name="discount_percent" class="form-control" value="0" min="0" max="100" step="0.01">
                        </div>
                    </div>
                    <input type="hidden" id="discount_amount" name="discount_amount" value="0">
                </div>
            </div>
            
            <div class="amount-summary row col-md-12">
                <div class="col-md-8">
                    <div class="form-group">

                        <table class="table table-bordered" id="feeTable">
    <thead>
        <tr>
            <th>#</th>
            <th>Service</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody></tbody>
    <tfoot>
        <tr>
            <th colspan="2" style="text-align:right;">Net Total:</th>
            <th id="netTotal" style="text-align:right;">Rs. 0</th>
        </tr>
        <tr>
            <th colspan="2" style="text-align:right;">Discount Applied: <span id="discountPercent">0%</span></th>
            <th id="discountValue" style="text-align:right;">Rs. 0</th>
        </tr>
        <tr>
            <th colspan="2" style="text-align:right;">Paid Amount:</th>
            <th id="paidValue" style="text-align:right;">Rs. 0</th>
        </tr>
        <tr>
            <th colspan="2" style="text-align:right;">Balance:</th>
            <th id="balanceValue" style="color:red; text-align:right;">Rs. 0</th>
        </tr>
    </tfoot>
</table>

                    </div>
                </div>

                <div class="col-md-4" style="background: #f4f4f4;border: 1px solid #e9e9e9;padding: 10px 30px;">
                    <div class="form-group">
                        <label for="paid_amount" class="py-1">Amount Paying Now</label>
                        <input type="number" id="paid_amount" name="paid_amount" class="form-control" placeholder="Enter amount paid now" min="0" step="0.01" required>
                        <small class="text-muted">Enter the amount patient is paying right now (partial allowed)</small>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-md-6">
                            <label for="paid_amount" class="py-1">Balance</label>
                            <h2 id="totalFeeCard">0</h2>
                        </div>
                        <div class="col-md-6"><button type="submit" class="btn btn-primary m-t-10">Submit</button></div>
                    </div>
                </div>
            </div>
            <?php echo form_close(); ?>






<style type="text/css">
    .form-group.select-service {
    border: 2px solid #dbe0e5;
    border-radius: 2px;
    padding\: 2;
    padding: 15px;
    min-height: 200px;
    max-height: 200px;
    overflow: auto;
}


</style>




<script>
function addDashes(element) {
    let val = element.value.replace(/-/g, '');
    if (val.length > 4) {
        val = val.slice(0, 4) + '-' + val.slice(4, 11);
    }
    element.value = val;
}

let autoFilled = false; // track autofill

document.getElementById('phone').addEventListener('blur', function () {

    let phone = this.value.trim();

    if (phone.length < 7) return; // kuch mat karo

    fetch('<?= base_url("admin/tokens/check_phone") ?>', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'phone=' + encodeURIComponent(phone)
    })
    .then(res => res.json())
    .then(data => {

        if (data.status === 'found') {
            document.getElementById('name').value   = data.name ?? '';
            document.getElementById('age').value    = data.age ?? '';
            document.getElementById('gender').value = data.gender ?? '';
            autoFilled = true;
        }

        // ❌ NO ELSE
        // ❌ NO CLEARING
    })
    .catch(err => console.error(err));
});
</script>




<!-- Onload Selected Depart Service and Sub Service -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
    // 1. Select all department checkboxes
    const deptCheckboxes = document.querySelectorAll('#departments input[type=checkbox]');
    if (deptCheckboxes.length > 0) {
        // Check first department checkbox
        deptCheckboxes[0].checked = true;
    }

    // Populate services based on selected departments (should create service checkboxes)
    populateServices();

    // 2. After populating services, check first service checkbox by default
    const serviceCheckboxes = document.querySelectorAll('#services input[type=checkbox]');
    if (serviceCheckboxes.length > 0) {
        serviceCheckboxes[0].checked = true;
    }

    // Populate sub-services based on selected services
    populateSubServices();

    // 3. After populating sub-services, check first sub-service checkbox by default
    const subServiceCheckboxes = document.querySelectorAll('#sub_services input[type=checkbox]');
    if (subServiceCheckboxes.length > 0) {
        subServiceCheckboxes[0].checked = true;
    }

    // 4. Update the fee table after selections
    updateFeeTable();
});

</script>

<!-- Sub-service Search Filter Script -->
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('sub_service_search');
    const subServiceDiv = document.getElementById('sub_services');

    searchInput.addEventListener('input', function() {
        const filter = this.value.toLowerCase();
        const checkboxes = subServiceDiv.querySelectorAll('.form-check');

        checkboxes.forEach(cbDiv => {
            const label = cbDiv.querySelector('label').innerText.toLowerCase();
            cbDiv.style.display = label.includes(filter) ? '' : 'none';
        });
    });
});
</script>

<!-- Panel Toggle (Auto Set Funded and Discount) -->
<script>
document.addEventListener('DOMContentLoaded', function () {
    const togglePanel  = document.getElementById('toggle_panel');
    const fundedBy     = document.getElementById('funded_by');
    const discountType = document.getElementById('discount_type');

    togglePanel.addEventListener('change', function () {
        if (this.checked) {
            fundedBy.value = 'Jamia Masjid';
            discountType.value = 50;
        } else {
            fundedBy.value = '';
            discountType.value = 0;
        }
        updateFeeTable();
    });
});
</script>

<!-- Show/Hide Discount and Panel Controls + Discount Logic -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const togglePanel = document.getElementById('toggle_panel');
    const panelGroup = document.getElementById('panel_group');
    const panelType = document.getElementById('panel_type');

    const toggleDiscount = document.getElementById('toggle_discount');
    const discountGroup = document.getElementById('discount_group');
    const discountType = document.getElementById('discount_type');
    const fundedBy = document.getElementById('funded_by');

    // Panel checkbox change (redundant but safe)
    togglePanel.addEventListener('change', function () {
        if (this.checked) {
            fundedBy.value = 'Jamia Masjid';
            discountType.value = 50;
        } else {
            fundedBy.value = '';
            discountType.value = 0;
        }
        updateFeeTable();
    });

    // Discount toggle show/hide
    toggleDiscount.addEventListener('change', function() {
        discountGroup.style.display = this.checked ? 'block' : 'none';
        if (!this.checked) {
            discountType.value = 0;
            updateFeeTable();
        }
    });

    // Apply discount based on panel type select (if panelType dropdown is used)
    panelType.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        const discount = selectedOption.getAttribute('data-discount');
        if (discount !== null) {
            discountType.value = discount;
            updateFeeTable();
        }
    });

    // Update fee table on manual discount input
    discountType.addEventListener('input', function() {
        updateFeeTable();
    });
});
</script>

<!-- Phone Input Formatting (Add Dashes Automatically) -->
<script>
function addDashes(f) {
    f.value = f.value.replace(/\D/g, '');
    if (f.value.length > 4) {
        f.value = f.value.substring(0, 4) + '-' + f.value.substring(4, 11);
    }
}
</script>

<!-- Data Variables Initialization (PHP to JS) -->
<script>
let services      = <?= json_encode($services ?? []); ?>;
let sub_services  = <?= json_encode($sub_services ?? []); ?>;
let departments   = <?= json_encode($departments ?? []); ?>;
let service_fees  = <?= json_encode($service_fees ?? []); ?>;
</script>

<!-- Helper Function to Get Checked Checkbox Values -->
<script>
function getCheckedValues(containerSelector) {
    return Array.from(document.querySelectorAll(containerSelector + " input:checked"))
                .map(cb => cb.value.toString());
}
</script>

<!-- Populate Services and Sub-Services Based on Selection -->
<script>
function populateServices() {
    const selectedDeps = getCheckedValues("#departments");
    const serviceDiv = document.getElementById('services');
    serviceDiv.innerHTML = '';

    services.forEach(s => {
        if (selectedDeps.includes(String(s.department_id))) {
            serviceDiv.innerHTML += `
                <div class="form-check">
                    <input class="form-check-input service-checkbox" type="checkbox" 
                           name="services[]" value="${s.id}" id="srv${s.id}" >
                    <label class="form-check-label" for="srv${s.id}">${s.name}</label>
                </div>`;
        }
    });

    populateSubServices();
}

function populateSubServices() {
    const selectedServices = getCheckedValues("#services");
    const subServiceDiv = document.getElementById('sub_services');
    subServiceDiv.innerHTML = '';

    sub_services.forEach(ss => {
        if (selectedServices.includes(String(ss.service_id))) {
            subServiceDiv.innerHTML += `
                <div class="form-check">
                    <input class="form-check-input subservice-checkbox" type="checkbox" 
                           name="sub_services[]" value="${ss.id}" id="sub${ss.id}" >
                    <label class="form-check-label" for="sub${ss.id}">${ss.name}</label>
                </div>`;
        }
    });

    updateFeeTable();
}
</script>

<!-- Main updateFeeTable() Function (Clean, with Summary Area Update) -->
<script>
    function generateServiceDescription(deptName, subServiceName, consultantName) {
    deptName = deptName.toLowerCase();

    if (deptName === 'opd') {
        return `OPD ${subServiceName} By ${consultantName}`;
    } else if (deptName === 'lab') {
        return `${subServiceName} By ${consultantName} Lab`;
    } else if (deptName === 'ultrasound') {
        return `${subServiceName} Ultrasound by ${consultantName}`;
    } else if (deptName === 'physiotherapy') {
        return `Physiotherapy ${subServiceName} by ${consultantName}`;
    } else if (deptName === 'clinical services') {
        return `${subServiceName}`;
    } else {
        return `${subServiceName} by ${consultantName} ${deptName}`;
    }
}

function updateFeeTable() {
    const tbody = document.querySelector('#feeTable tbody');
    tbody.innerHTML = '';
    let subtotal = 0.0;
    let count = 1;

    const selectedSubServices = getCheckedValues("#sub_services");
    const selectedServices = getCheckedValues("#services");

    // Assuming you have consultant info for each service or subservice:
    // For demo, I am using a placeholder, replace with actual data source
const getConsultantName = (serviceId) => {
    const service = services.find(s => s.id == serviceId);
    return service ? service.name : "Unknown Consultant";
}

// phir updateFeeTable ke andar jab description banayen:
// const consultantName = getConsultantName(service ? service.id : null);

    // Add selected sub-services
    selectedSubServices.forEach(ss_id => {
        const ss = sub_services.find(x => String(x.id) === ss_id);
        if (!ss) return;
        const service = services.find(x => x.id == ss.service_id);
        const dept = departments.find(x => x.id == (service ? service.department_id : 0));
        const consultantName = getConsultantName(service ? service.id : null);

        const feeObj = service_fees.find(f => f.sub_service_id != null && Number(f.sub_service_id) === Number(ss.id));
        const fee = feeObj ? parseFloat(feeObj.fee) : 0;
        const currency = feeObj ? feeObj.currency : '';

        subtotal += fee;

        const description = generateServiceDescription(dept ? dept.name : '', ss.name, consultantName);

        tbody.innerHTML += `<tr>
            <td>${count++}</td>
            <td>${description}</td>
            <td style="text-align:right;">${fee.toFixed(2)} ${currency}</td>
        </tr>`;
    });

    // Add services without selected sub-services
    selectedServices.forEach(sid => {
        const hasSelectedSub = selectedSubServices.some(ssid => {
            const ssObj = sub_services.find(x => String(x.id) === ssid);
            return ssObj && ssObj.service_id == sid;
        });
        if (hasSelectedSub) return;

        const service = services.find(x => String(x.id) === sid);
        if (!service) return;
        const dept = departments.find(x => x.id == service.department_id);
        const consultantName = getConsultantName(service.id);

        const feeObj = service_fees.find(f => {
            return (f.service_id != null && Number(f.service_id) === Number(service.id)) 
                    && (f.sub_service_id === null || f.sub_service_id === undefined);
        });
        const fee = feeObj ? parseFloat(feeObj.fee) : 0;
        const currency = feeObj ? feeObj.currency : '';

        subtotal += fee;

        // For services without sub-service, use service name instead of sub-service name
        const description = generateServiceDescription(dept ? dept.name : '', service.name, consultantName);

        tbody.innerHTML += `<tr>
            <td>${count++}</td>
            <td>${description}</td>
            <td style="text-align:right;">${fee.toFixed(2)} ${currency}</td>
        </tr>`;
    });

    // Apply discount if enabled
    const discountCheckbox = document.getElementById('toggle_discount');
    let discountPercent = 0;
    let discountAmount = 0;

    if (discountCheckbox && discountCheckbox.checked) {
        discountPercent = parseFloat(document.getElementById('discount_type').value) || 0;
        discountAmount = subtotal * (discountPercent / 100);
    }

    const totalAfterDiscount = subtotal - discountAmount;

    // Paid Amount logic
    const paidInput = document.getElementById('paid_amount');
    let paidAmount = parseFloat(paidInput?.value) || 0;

    if (paidAmount > totalAfterDiscount) {
        paidAmount = totalAfterDiscount;
        if (paidInput) paidInput.value = totalAfterDiscount.toFixed(2);
    }

    const remainingBalance = totalAfterDiscount - paidAmount;

    // Update the card totals or summary elements
    document.getElementById('totalFeeCard').innerText = remainingBalance.toFixed(2);
    document.getElementById('discount_amount').value = discountAmount.toFixed(2);

    if (document.getElementById('netTotal')) {
        document.getElementById('netTotal').innerText = subtotal.toFixed(2);
        document.getElementById('discountPercent').innerText = discountPercent + '%';
        document.getElementById('discountValue').innerText = discountAmount.toFixed(2);
        document.getElementById('paidValue').innerText = paidAmount.toFixed(2);
        document.getElementById('balanceValue').innerText = remainingBalance.toFixed(2);
    }
}

// Attach event listeners (if not already attached)
document.getElementById('discount_type').addEventListener('change', updateFeeTable);
document.getElementById('departments').addEventListener('change', populateServices);
document.getElementById('services').addEventListener('change', populateSubServices);
document.getElementById('sub_services').addEventListener('change', updateFeeTable);
document.getElementById('paid_amount').addEventListener('input', updateFeeTable);

// Initial population
populateServices();

</script>
