<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'CHIEF_PHARMACIST', 'PHARMACIST', 'PHARMACY_TECH'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Get active inventory items
$inventory_sql = "SELECT inventory_id, item_code, item_name, generic_name, brand_name,
                         current_stock, unit_cost, selling_price, dosage_form, strength,
                         requires_prescription, batch_number, expiry_date
                  FROM pharmacy_inventory
                  WHERE is_active = 1 AND current_stock > 0
                  ORDER BY item_name ASC";
$inventory_items = $conn->query($inventory_sql);

// Get all registered patients for search
$patients_sql = "SELECT p.patient_id, p.patient_number, u.full_name, u.phone_primary, u.email,
                        u.date_of_birth, u.gender
                 FROM patients p
                 INNER JOIN users u ON p.user_id = u.user_id
                 WHERE u.status = 'ACTIVE'
                 ORDER BY u.full_name ASC";
$patients = $conn->query($patients_sql);

// Get insurance providers
$insurance_sql = "SELECT provider_id, provider_name FROM insurance_providers WHERE is_active = 1";
$insurance_providers = $conn->query($insurance_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pharmacy Dispensing')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <style>
        .patient-type-card {
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            padding: 1.5rem;
            cursor: pointer;
            transition: all 0.2s;
            background: white;
        }
        .patient-type-card:hover {
            border-color: #3b82f6;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .patient-type-card.active {
            border-color: #3b82f6;
            background: #eff6ff;
        }
        .patient-type-icon {
            font-size: 3rem;
            color: #3b82f6;
            margin-bottom: 1rem;
        }
        .form-section {
            display: none;
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            margin-top: 1rem;
            border: 1px solid #e5e7eb;
        }
        .form-section.active {
            display: block;
        }
        .medication-item {
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            padding: 1rem;
            margin-bottom: 0.75rem;
        }
        .medication-item:hover {
            background: #f3f4f6;
        }
        .remove-item-btn {
            color: #ef4444;
            cursor: pointer;
        }
        .summary-card {
            background: #f9fafb;
            border-radius: 8px;
            padding: 1.5rem;
            position: sticky;
            top: 20px;
        }
        .total-amount {
            font-size: 1.5rem;
            font-weight: 700;
            color: #3b82f6;
        }
        .select2-container {
            width: 100% !important;
        }
        .select2-selection {
            height: 38px !important;
            border: 1px solid #ced4da !important;
        }
        .select2-selection__rendered {
            line-height: 38px !important;
        }
        .prescription-badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
            font-weight: 600;
            border-radius: 0.25rem;
            margin-left: 0.5rem;
        }
        .prescription-badge.active {
            background-color: #dcfce7;
            color: #166534;
        }
        .prescription-badge.none {
            background-color: #fee2e2;
            color: #991b1b;
        }
        .prescription-list {
            max-height: 300px;
            overflow-y: auto;
        }
        .prescription-item {
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        .prescription-item:hover {
            background-color: #f3f4f6;
            border-color: #3b82f6;
        }
        .prescription-item.selected {
            background-color: #eff6ff;
            border-color: #3b82f6;
            border-width: 2px;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Pharmacy Dispensing</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="pharmacy_dashboard.php">Pharmacy</a></li>
                                        <li class="breadcrumb-item active">Dispensing</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Patient Type Selection -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <h5 class="mb-3">Select Patient Type</h5>
                        </div>
                        <div class="col-md-4">
                            <div class="patient-type-card" data-type="registered" onclick="selectPatientType('registered')">
                                <div class="text-center">
                                    <div class="patient-type-icon">
                                        <i class="ri-user-3-line"></i>
                                    </div>
                                    <h5>Registered Patient</h5>
                                    <p class="text-muted mb-0">Patient with hospital record</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="patient-type-card" data-type="walk_in" onclick="selectPatientType('walk_in')">
                                <div class="text-center">
                                    <div class="patient-type-icon">
                                        <i class="ri-walk-line"></i>
                                    </div>
                                    <h5>Walk-In Patient</h5>
                                    <p class="text-muted mb-0">Patient without hospital record</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="patient-type-card" data-type="referred" onclick="selectPatientType('referred')">
                                <div class="text-center">
                                    <div class="patient-type-icon">
                                        <i class="ri-hospital-line"></i>
                                    </div>
                                    <h5>Referred Patient</h5>
                                    <p class="text-muted mb-0">Patient from external facility</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <form id="dispensingForm" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="patient_type" id="patient_type">
                        <input type="hidden" name="patient_id" id="patient_id">
                        <input type="hidden" name="selected_prescription_id" id="selected_prescription_id">
                        <input type="hidden" name="dispensed_by" value="<?php echo $_SESSION['user_id']; ?>">

                        <div class="row">
                            <div class="col-lg-8">
                                <!-- Registered Patient Form -->
                                <div class="form-section" id="registered_form">
                                    <h5 class="mb-3"><i class="ri-user-3-line me-2"></i>Registered Patient Details</h5>
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-12">
                                            <label class="form-label">Search Patient <span class="text-danger">*</span></label>
                                            <select class="form-control select2" id="patient_search">
                                                <option value="">-- Search by patient name, number or phone --</option>
                                                <?php while ($patient = $patients->fetch_assoc()): ?>
                                                    <option value="<?php echo $patient['patient_id']; ?>" 
                                                            data-patient-number="<?php echo $patient['patient_number']; ?>"
                                                            data-name="<?php echo htmlspecialchars($patient['full_name']); ?>"
                                                            data-phone="<?php echo $patient['phone_primary']; ?>"
                                                            data-email="<?php echo $patient['email']; ?>"
                                                            data-dob="<?php echo $patient['date_of_birth']; ?>"
                                                            data-gender="<?php echo $patient['gender']; ?>">
                                                        <?php echo $patient['patient_number']; ?> - 
                                                        <?php echo htmlspecialchars($patient['full_name']); ?> - 
                                                        <?php echo $patient['phone_primary']; ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                    </div>

                                    <!-- Patient Info Display -->
                                    <div class="alert alert-info" id="patient_info" style="display: none;">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <strong>Patient Number:</strong> <span id="display_patient_number"></span><br>
                                                <strong>Name:</strong> <span id="display_patient_name"></span><br>
                                                <strong>Phone:</strong> <span id="display_patient_phone"></span>
                                            </div>
                                            <div class="col-md-6">
                                                <strong>Gender:</strong> <span id="display_patient_gender"></span><br>
                                                <strong>Date of Birth:</strong> <span id="display_patient_dob"></span><br>
                                                <strong>Email:</strong> <span id="display_patient_email"></span>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Available Prescriptions -->
                                    <div id="prescriptions_section" style="display: none;">
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <h6 class="mb-0">
                                                <i class="ri-file-list-3-line me-2"></i>Available Prescriptions
                                                <span class="prescription-badge active" id="prescription_count_badge">0</span>
                                            </h6>
                                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="clearPrescriptionSelection()">
                                                <i class="ri-close-line me-1"></i>Clear Selection
                                            </button>
                                        </div>
                                        <div class="prescription-list" id="prescription_list">
                                            <!-- Prescriptions will be loaded here -->
                                        </div>
                                        <div id="no_prescriptions" class="text-center py-3" style="display: none;">
                                            <i class="ri-file-list-3-line text-muted" style="font-size: 2rem;"></i>
                                            <p class="text-muted mt-2 mb-0">No active prescriptions found for this patient</p>
                                            <small class="text-muted">You can still dispense medications manually</small>
                                        </div>
                                    </div>
                                </div>

                                <!-- Walk-In Patient Form -->
                                <div class="form-section" id="walk_in_form">
                                    <h5 class="mb-3"><i class="ri-walk-line me-2"></i>Walk-In Patient Details</h5>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Patient Name <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" name="walk_in_name" placeholder="Enter full name">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Phone Number</label>
                                            <input type="text" class="form-control" name="walk_in_phone" placeholder="+254...">
                                        </div>
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Upload Prescription (Optional)</label>
                                            <input type="file" class="form-control" name="prescription_image" accept="image/*,.pdf">
                                            <small class="text-muted">Upload prescription from external doctor if available</small>
                                        </div>
                                    </div>
                                </div>

                                <!-- Referred Patient Form -->
                                <div class="form-section" id="referred_form">
                                    <h5 class="mb-3"><i class="ri-hospital-line me-2"></i>Referred Patient Details</h5>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Patient Name <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" name="referred_name" placeholder="Enter full name">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Phone Number</label>
                                            <input type="text" class="form-control" name="referred_phone" placeholder="+254...">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Referring Facility</label>
                                            <input type="text" class="form-control" name="referring_facility" placeholder="Hospital/Clinic name">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Referring Doctor</label>
                                            <input type="text" class="form-control" name="referring_doctor" placeholder="Doctor's name">
                                        </div>
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Upload Prescription/Referral Letter</label>
                                            <input type="file" class="form-control" name="prescription_image" accept="image/*,.pdf">
                                        </div>
                                    </div>
                                </div>

                                <!-- Medication Items Section -->
                                <div class="form-section active" id="medication_section">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h5 class="mb-0"><i class="ri-medicine-bottle-line me-2"></i>Medications</h5>
                                        <button type="button" class="btn btn-sm btn-primary" onclick="addMedicationItem()">
                                            <i class="ri-add-line me-1"></i>Add Item
                                        </button>
                                    </div>

                                    <div id="medication_items">
                                        <!-- Medication items will be added here dynamically -->
                                    </div>

                                    <div id="no_items_message" class="text-center py-4">
                                        <i class="ri-medicine-bottle-line text-muted" style="font-size: 3rem;"></i>
                                        <p class="text-muted mt-2">No items added yet. Click "Add Item" to start.</p>
                                    </div>
                                </div>

                                <!-- Payment Details - ALWAYS VISIBLE -->
                                <div class="form-section active" id="payment_section">
                                    <h5 class="mb-3"><i class="ri-money-dollar-circle-line me-2"></i>Payment Details</h5>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Payment Method <span class="text-danger">*</span></label>
                                            <select class="form-control" name="payment_method" id="payment_method" required>
                                                <option value="">Select Payment Method</option>
                                                <option value="CASH">Cash</option>
                                                <option value="MPESA">M-Pesa</option>
                                                <option value="CARD">Card</option>
                                                <option value="BANK_TRANSFER">Bank Transfer</option>
                                                <option value="INSURANCE">Insurance</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3" id="insurance_provider_div" style="display: none;">
                                            <label class="form-label">Insurance Provider <span class="text-danger">*</span></label>
                                            <select class="form-control" name="insurance_provider_id" id="insurance_provider_id">
                                                <option value="">Select Insurance Provider</option>
                                                <?php 
                                                // Reset pointer
                                                $insurance_providers->data_seek(0);
                                                while ($provider = $insurance_providers->fetch_assoc()): 
                                                ?>
                                                    <option value="<?php echo $provider['provider_id']; ?>">
                                                        <?php echo htmlspecialchars($provider['provider_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-12 mb-3">
                                            <div class="alert alert-warning" id="insurance_notice" style="display: none;">
                                                <i class="ri-information-line me-2"></i>
                                                <strong>Insurance Payment:</strong> Payment will be marked as PENDING. An invoice and dispensing note will be generated for the patient. Payment will be completed during insurance reconciliation.
                                            </div>
                                        </div>
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Notes (Optional)</label>
                                            <textarea class="form-control" name="notes" rows="2" placeholder="Any special notes..."></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Summary Sidebar -->
                            <div class="col-lg-4">
                                <div class="summary-card">
                                    <h5 class="mb-3">Order Summary</h5>
                                    
                                    <div class="mb-3">
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Total Items:</span>
                                            <strong id="summary_total_items">0</strong>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Subtotal:</span>
                                            <strong>KES <span id="summary_subtotal">0.00</span></strong>
                                        </div>
                                        <hr>
                                        <div class="d-flex justify-content-between">
                                            <span>Total Amount:</span>
                                            <div class="total-amount">KES <span id="summary_total">0.00</span></div>
                                        </div>
                                    </div>

                                    <div class="d-grid gap-2 mt-4">
                                        <button type="submit" class="btn btn-success btn-lg" id="submitBtn">
                                            <i class="ri-check-line me-2"></i>Process Dispensing
                                        </button>
                                        <a href="pharmacy_dashboard.php" class="btn btn-light">Cancel</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>

                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
    let itemCounter = 0;
    let inventoryData = <?php echo json_encode($inventory_items->fetch_all(MYSQLI_ASSOC)); ?>;
    let selectedPatientId = null;

    $(document).ready(function() {
        // Initialize Select2
        $('.select2').select2({
            placeholder: "Search by patient name, number or phone",
            allowClear: true
        });
        
        // Handle patient selection
        $('#patient_search').on('change', function() {
            const selectedOption = $(this).find(':selected');
            const patientId = selectedOption.val();
            
            if (patientId) {
                selectedPatientId = patientId;
                $('#patient_id').val(patientId);
                
                // Display patient info
                $('#display_patient_number').text(selectedOption.data('patient-number'));
                $('#display_patient_name').text(selectedOption.data('name'));
                $('#display_patient_phone').text(selectedOption.data('phone'));
                $('#display_patient_email').text(selectedOption.data('email') || 'N/A');
                $('#display_patient_gender').text(selectedOption.data('gender'));
                $('#display_patient_dob').text(selectedOption.data('dob'));
                $('#patient_info').show();
                
                // Load prescriptions for this patient
                loadPatientPrescriptions(patientId);
            } else {
                selectedPatientId = null;
                $('#patient_id').val('');
                $('#patient_info').hide();
                $('#prescriptions_section').hide();
            }
        });

        // Handle payment method change
        $('#payment_method').on('change', function() {
            if ($(this).val() === 'INSURANCE') {
                $('#insurance_provider_div').show();
                $('#insurance_notice').show();
                $('#insurance_provider_id').attr('required', true);
            } else {
                $('#insurance_provider_div').hide();
                $('#insurance_notice').hide();
                $('#insurance_provider_id').attr('required', false);
            }
        });
    });

    function selectPatientType(type) {
        // Update UI
        $('.patient-type-card').removeClass('active');
        $(`.patient-type-card[data-type="${type}"]`).addClass('active');
        
        // Show appropriate form
        $('.form-section').not('#medication_section, #payment_section').removeClass('active');
        $(`#${type}_form`).addClass('active');
        
        // Set hidden input
        $('#patient_type').val(type.toUpperCase());
        
        // Reset patient selection if switching away from registered
        if (type !== 'registered') {
            $('#patient_search').val('').trigger('change');
            selectedPatientId = null;
        }
    }

    function loadPatientPrescriptions(patientId) {
        $.ajax({
            url: 'get_patient_prescriptions.php',
            type: 'POST',
            data: { patient_id: patientId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    const prescriptions = response.prescriptions;
                    $('#prescription_list').empty();
                    
                    if (prescriptions.length > 0) {
                        $('#prescription_count_badge').text(prescriptions.length);
                        
                        prescriptions.forEach(function(prescription) {
                            const prescriptionHtml = `
                                <div class="prescription-item" onclick="selectPrescription(${prescription.prescription_id}, this)">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <strong>${prescription.prescription_number}</strong>
                                            <span class="badge bg-primary ms-2">${prescription.medication_type}</span>
                                            <p class="mb-1 mt-1"><strong>${prescription.medication_name}</strong></p>
                                            <small class="text-muted">
                                                <i class="ri-stethoscope-line me-1"></i>${prescription.doctor_name}<br>
                                                <i class="ri-calendar-line me-1"></i>${prescription.prescribed_date}
                                            </small>
                                        </div>
                                        <div class="text-end">
                                            <small class="text-muted">Dosage</small>
                                            <p class="mb-0"><strong>${prescription.dosage}</strong></p>
                                            <small class="text-muted">${prescription.frequency}</small>
                                        </div>
                                    </div>
                                    <div class="mt-2">
                                        <small class="text-muted"><strong>Duration:</strong> ${prescription.duration}</small>
                                        ${prescription.quantity ? `<small class="text-muted ms-3"><strong>Qty:</strong> ${prescription.quantity}</small>` : ''}
                                    </div>
                                </div>
                            `;
                            $('#prescription_list').append(prescriptionHtml);
                        });
                        
                        $('#no_prescriptions').hide();
                        $('#prescription_list').show();
                    } else {
                        $('#prescription_count_badge').text('0');
                        $('#prescription_list').hide();
                        $('#no_prescriptions').show();
                    }
                    
                    $('#prescriptions_section').show();
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load prescriptions'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to load prescriptions'
                });
            }
        });
    }

    function selectPrescription(prescriptionId, element) {
        // Remove previous selection
        $('.prescription-item').removeClass('selected');
        
        // Add selection to clicked item
        $(element).addClass('selected');
        
        // Set hidden input
        $('#selected_prescription_id').val(prescriptionId);
        
        // Show success message
        Swal.fire({
            icon: 'success',
            title: 'Prescription Selected',
            text: 'The prescription has been linked to this dispensing. You can now add medications.',
            timer: 2000,
            showConfirmButton: false
        });
    }

    function clearPrescriptionSelection() {
        $('.prescription-item').removeClass('selected');
        $('#selected_prescription_id').val('');
        
        Swal.fire({
            icon: 'info',
            title: 'Selection Cleared',
            text: 'No prescription will be linked to this dispensing',
            timer: 2000,
            showConfirmButton: false
        });
    }

    function addMedicationItem() {
        itemCounter++;
        const itemHtml = `
            <div class="medication-item" id="item_${itemCounter}">
                <div class="row align-items-end">
                    <div class="col-md-5 mb-2">
                        <label class="form-label">Medication</label>
                        <select class="form-control medication-select" name="medication[]" 
                                onchange="updateItemPrice(${itemCounter})" required>
                            <option value="">Select Medication</option>
                            ${inventoryData.map(item => `
                                <option value="${item.inventory_id}" 
                                        data-price="${item.selling_price}"
                                        data-stock="${item.current_stock}"
                                        data-name="${item.item_name}">
                                    ${item.item_name} (${item.strength || ''}) - 
                                    Stock: ${item.current_stock} - 
                                    KES ${parseFloat(item.selling_price).toFixed(2)}
                                </option>
                            `).join('')}
                        </select>
                    </div>
                    <div class="col-md-2 mb-2">
                        <label class="form-label">Quantity</label>
                        <input type="number" class="form-control" name="quantity[]" 
                               min="1" value="1" onchange="calculateItemTotal(${itemCounter})" required>
                    </div>
                    <div class="col-md-2 mb-2">
                        <label class="form-label">Unit Price</label>
                        <input type="text" class="form-control unit-price" 
                               name="unit_price[]" readonly>
                    </div>
                    <div class="col-md-2 mb-2">
                        <label class="form-label">Total</label>
                        <input type="text" class="form-control item-total" readonly>
                    </div>
                    <div class="col-md-1 mb-2">
                        <button type="button" class="btn btn-sm btn-soft-danger remove-item-btn" 
                                onclick="removeItem(${itemCounter})">
                            <i class="ri-delete-bin-line"></i>
                        </button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-12">
                        <textarea class="form-control form-control-sm" name="dosage_instructions[]" 
                                  rows="1" placeholder="Dosage instructions (optional)"></textarea>
                    </div>
                </div>
            </div>
        `;
        
        $('#medication_items').append(itemHtml);
        $('#no_items_message').hide();
        updateSummary();
    }

    function updateItemPrice(itemId) {
        const select = $(`#item_${itemId} .medication-select`);
        const selectedOption = select.find(':selected');
        const price = selectedOption.data('price') || 0;
        const stock = selectedOption.data('stock') || 0;
        
        $(`#item_${itemId} .unit-price`).val(parseFloat(price).toFixed(2));
        
        // Validate stock
        const quantity = parseInt($(`#item_${itemId} input[name="quantity[]"]`).val()) || 1;
        if (quantity > stock) {
            Swal.fire({
                icon: 'warning',
                title: 'Insufficient Stock',
                text: `Only ${stock} units available in stock`,
            });
            $(`#item_${itemId} input[name="quantity[]"]`).val(stock);
        }
        
        calculateItemTotal(itemId);
    }

    function calculateItemTotal(itemId) {
        const quantity = parseInt($(`#item_${itemId} input[name="quantity[]"]`).val()) || 0;
        const unitPrice = parseFloat($(`#item_${itemId} .unit-price`).val()) || 0;
        const total = quantity * unitPrice;
        
        $(`#item_${itemId} .item-total`).val(total.toFixed(2));
        updateSummary();
    }

    function removeItem(itemId) {
        $(`#item_${itemId}`).remove();
        if ($('#medication_items .medication-item').length === 0) {
            $('#no_items_message').show();
        }
        updateSummary();
    }

    function updateSummary() {
        let totalItems = 0;
        let totalAmount = 0;
        
        $('.medication-item').each(function() {
            const quantity = parseInt($(this).find('input[name="quantity[]"]').val()) || 0;
            const itemTotal = parseFloat($(this).find('.item-total').val()) || 0;
            
            totalItems += quantity;
            totalAmount += itemTotal;
        });
        
        $('#summary_total_items').text(totalItems);
        $('#summary_subtotal').text(totalAmount.toFixed(2));
        $('#summary_total').text(totalAmount.toFixed(2));
    }

    // Form submission with AJAX
    $('#dispensingForm').on('submit', function(e) {
        e.preventDefault();
        
        const patientType = $('#patient_type').val();
        
        if (!patientType) {
            Swal.fire({
                icon: 'warning',
                title: 'Patient Type Required',
                text: 'Please select a patient type before proceeding',
            });
            return false;
        }
        
        // For registered patients, ensure patient is selected
        if (patientType === 'REGISTERED' && !selectedPatientId) {
            Swal.fire({
                icon: 'warning',
                title: 'Patient Required',
                text: 'Please search and select a patient',
            });
            return false;
        }
        
        if ($('#medication_items .medication-item').length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'No Medications',
                text: 'Please add at least one medication item',
            });
            return false;
        }
        
        // Disable submit button
        $('#submitBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Processing...');
        
        // Create FormData object
        const formData = new FormData(this);
        
        // Send AJAX request
        $.ajax({
            url: 'pharmacy_dispense_process.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: response.message,
                        showCancelButton: response.payment_status === 'PENDING',
                        confirmButtonText: response.payment_status === 'PENDING' ? 'Download Invoice' : 'OK',
                        cancelButtonText: 'View History'
                    }).then((result) => {
                        if (result.isConfirmed && response.payment_status === 'PENDING') {
                            // Download invoice for insurance patients
                            window.open('generate_dispensing_invoice.php?id=' + response.dispensing_id, '_blank');
                            window.location.href = 'pharmacy_dispensing_history.php';
                        } else if (result.dismiss === Swal.DismissReason.cancel) {
                            window.location.href = 'pharmacy_dispensing_history.php';
                        } else {
                            window.location.href = 'pharmacy_dashboard.php';
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message
                    });
                    $('#submitBtn').prop('disabled', false).html('<i class="ri-check-line me-2"></i>Process Dispensing');
                }
            },
            error: function(xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred while processing the dispensing. Please try again.'
                });
                $('#submitBtn').prop('disabled', false).html('<i class="ri-check-line me-2"></i>Process Dispensing');
            }
        });
        
        return false;
    });
    </script>
</body>
</html>