<?php
// edit_payment_allocation.php - Edit Draft Payment Allocation
include 'layouts/session.php';
include 'layouts/dbconn.php';

$allocation_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($allocation_id === 0) {
    header("Location: list_payment_allocations.php");
    exit();
}

// Get allocation details - only if DRAFT
$allocation_sql = "SELECT pa.*, bp.payment_number, bp.total_amount as bulk_total,
                   esp.provider_name, esp.provider_code, esp.default_commission_rate
                   FROM payment_allocations pa
                   JOIN bulk_payments bp ON pa.bulk_payment_id = bp.bulk_payment_id
                   JOIN external_service_providers esp ON pa.provider_id = esp.provider_id
                   WHERE pa.allocation_id = ? AND pa.allocation_status = 'DRAFT'";
$stmt = $conn->prepare($allocation_sql);
$stmt->bind_param('i', $allocation_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Allocation not found or cannot be edited";
    header("Location: list_payment_allocations.php");
    exit();
}

$allocation = $result->fetch_assoc();

// Get doctors for dropdown
$doctors_sql = "SELECT d.doctor_id, u.full_name, d.specialization, d.commission_rate 
                FROM doctors d 
                JOIN users u ON d.user_id = u.user_id 
                WHERE d.is_active = 1 
                ORDER BY u.full_name";
$doctors = $conn->query($doctors_sql);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->begin_transaction();
    
    try {
        $service_date = $_POST['service_date'];
        $patient_reference = trim($_POST['patient_reference']);
        $service_description = trim($_POST['service_description']);
        $service_category = $_POST['service_category'];
        $total_service_cost = floatval($_POST['total_service_cost']);
        $allocation_type = $_POST['allocation_type'];
        
        $doctor_id = null;
        $doctor_allocation = 0.00;
        $doctor_commission_rate = 0.00;
        $facility_allocation = 0.00;
        $facility_percentage = 0.00;
        
        // Calculate allocations based on type
        if ($allocation_type === 'DOCTOR_ONLY') {
            $doctor_id = intval($_POST['doctor_id']);
            $doctor_commission_rate = floatval($_POST['doctor_commission_rate']);
            $doctor_allocation = $total_service_cost * ($doctor_commission_rate / 100);
        } elseif ($allocation_type === 'FACILITY_ONLY') {
            $facility_percentage = 100.00;
            $facility_allocation = $total_service_cost;
        } else { // DOCTOR_AND_FACILITY
            $doctor_id = intval($_POST['doctor_id']);
            $doctor_commission_rate = floatval($_POST['doctor_commission_rate']);
            $facility_percentage = floatval($_POST['facility_percentage']);
            $doctor_allocation = $total_service_cost * ($doctor_commission_rate / 100);
            $facility_allocation = $total_service_cost * ($facility_percentage / 100);
        }
        
        $tax_withheld = floatval($_POST['tax_withheld'] ?? 0);
        $other_deductions = floatval($_POST['other_deductions'] ?? 0);
        $notes = trim($_POST['notes'] ?? '');
        
        // Update allocation
        $update_sql = "UPDATE payment_allocations SET
                       service_date = ?, patient_reference = ?, service_description = ?,
                       service_category = ?, total_service_cost = ?, allocation_type = ?,
                       doctor_id = ?, doctor_allocation = ?, doctor_commission_rate = ?,
                       facility_allocation = ?, facility_percentage = ?,
                       tax_withheld = ?, other_deductions = ?, notes = ?,
                       updated_at = CURRENT_TIMESTAMP
                       WHERE allocation_id = ? AND allocation_status = 'DRAFT'";
        
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param('ssssdsiidddddsi',
            $service_date, $patient_reference, $service_description,
            $service_category, $total_service_cost, $allocation_type,
            $doctor_id, $doctor_allocation, $doctor_commission_rate,
            $facility_allocation, $facility_percentage,
            $tax_withheld, $other_deductions, $notes,
            $allocation_id
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Failed to update allocation: " . $stmt->error);
        }
        
        // Log activity
        $activity_sql = "INSERT INTO activity_logs (user_id, action, description, ip_address)
                         VALUES (?, 'UPDATE_ALLOCATION', ?, ?)";
        $stmt = $conn->prepare($activity_sql);
        $description = "Updated payment allocation: {$allocation['allocation_number']}";
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $user_id = $_SESSION['user_id'];
        $stmt->bind_param('iss', $user_id, $description, $ip_address);
        $stmt->execute();
        
        $conn->commit();
        
        $_SESSION['success_message'] = "Allocation updated successfully!";
        header("Location: view_payment_allocation.php?id=" . $allocation_id);
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = $e->getMessage();
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Allocation')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .info-box {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
        }
        
        .allocation-type-selector {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .type-option {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .type-option:hover {
            border-color: #667eea;
            background: #f8fafc;
        }
        
        .type-option.active {
            border-color: #667eea;
            background: #eef2ff;
        }
        
        .type-option input[type="radio"] {
            display: none;
        }
        
        .type-option i {
            font-size: 2rem;
            color: #667eea;
            margin-bottom: 0.5rem;
        }
        
        .type-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .type-desc {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .calculation-box {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            border-radius: 8px;
            padding: 1.5rem;
            margin-top: 1rem;
        }
        
        .calculation-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            font-size: 1rem;
        }
        
        .calculation-row.total {
            border-top: 2px solid #22c55e;
            margin-top: 0.5rem;
            padding-top: 1rem;
            font-weight: 700;
            font-size: 1.125rem;
            color: #047857;
        }
        
        .hidden {
            display: none;
        }
    </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 Header -->
                    <div class="page-header">
                        <div class="row align-items-center">
                            <div class="col">
                                <h3 class="mb-2"><i class="ri-edit-line me-2"></i>Edit Payment Allocation</h3>
                                <p class="mb-0 opacity-75">Update allocation details - <?php echo htmlspecialchars($allocation['allocation_number']); ?></p>
                            </div>
                            <div class="col-auto">
                                <a href="view_payment_allocation.php?id=<?php echo $allocation_id; ?>" class="btn btn-light">
                                    <i class="ri-arrow-left-line me-1"></i>Back to View
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line me-2"></i><?php echo htmlspecialchars($error_message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>
                    
                    <form method="POST" action="" id="allocationForm">
                        
                        <!-- Bulk Payment Info (Read-only) -->
                        <div class="form-card">
                            <div class="section-title">
                                <i class="ri-bank-line"></i>Bulk Payment Details (Read-only)
                            </div>
                            
                            <div class="info-box">
                                <div class="row">
                                    <div class="col-md-6">
                                        <small class="text-muted">Payment Number:</small>
                                        <div class="fw-bold"><?php echo htmlspecialchars($allocation['payment_number']); ?></div>
                                    </div>
                                    <div class="col-md-6">
                                        <small class="text-muted">Provider:</small>
                                        <div class="fw-bold"><?php echo htmlspecialchars($allocation['provider_name']); ?></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Service Details -->
                        <div class="form-card">
                            <div class="section-title">
                                <i class="ri-file-text-line"></i>Service Details
                            </div>
                            
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Service Date <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control datepicker" name="service_date" 
                                           value="<?php echo htmlspecialchars($allocation['service_date']); ?>" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Patient Reference</label>
                                    <input type="text" class="form-control" name="patient_reference" 
                                           value="<?php echo htmlspecialchars($allocation['patient_reference']); ?>"
                                           placeholder="Provider's patient reference number">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Service Category <span class="text-danger">*</span></label>
                                    <select class="form-select" name="service_category" required>
                                        <option value="">Select category...</option>
                                        <option value="CONSULTATION" <?php echo $allocation['service_category'] === 'CONSULTATION' ? 'selected' : ''; ?>>Consultation</option>
                                        <option value="PROCEDURE" <?php echo $allocation['service_category'] === 'PROCEDURE' ? 'selected' : ''; ?>>Procedure</option>
                                        <option value="SURGERY" <?php echo $allocation['service_category'] === 'SURGERY' ? 'selected' : ''; ?>>Surgery</option>
                                        <option value="DIAGNOSTIC" <?php echo $allocation['service_category'] === 'DIAGNOSTIC' ? 'selected' : ''; ?>>Diagnostic</option>
                                        <option value="EMERGENCY" <?php echo $allocation['service_category'] === 'EMERGENCY' ? 'selected' : ''; ?>>Emergency</option>
                                        <option value="FOLLOW_UP" <?php echo $allocation['service_category'] === 'FOLLOW_UP' ? 'selected' : ''; ?>>Follow-up</option>
                                        <option value="OTHER" <?php echo $allocation['service_category'] === 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                    </select>
                                </div>
                                <div class="col-md-12">
                                    <label class="form-label">Service Description <span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="service_description" rows="3" required><?php echo htmlspecialchars($allocation['service_description']); ?></textarea>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Total Service Cost <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" name="total_service_cost" 
                                           id="totalServiceCost" step="0.01" min="0" 
                                           value="<?php echo $allocation['total_service_cost']; ?>" required>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Allocation Type -->
                        <div class="form-card">
                            <div class="section-title">
                                <i class="ri-git-branch-line"></i>Allocation Type
                            </div>
                            
                            <div class="allocation-type-selector">
                                <label class="type-option <?php echo $allocation['allocation_type'] === 'DOCTOR_ONLY' ? 'active' : ''; ?>" for="doctorOnly">
                                    <input type="radio" name="allocation_type" id="doctorOnly" value="DOCTOR_ONLY" 
                                           <?php echo $allocation['allocation_type'] === 'DOCTOR_ONLY' ? 'checked' : ''; ?>>
                                    <i class="ri-user-heart-line"></i>
                                    <div class="type-title">Doctor Only</div>
                                    <div class="type-desc">Allocate entire amount to doctor</div>
                                </label>
                                
                                <label class="type-option <?php echo $allocation['allocation_type'] === 'FACILITY_ONLY' ? 'active' : ''; ?>" for="facilityOnly">
                                    <input type="radio" name="allocation_type" id="facilityOnly" value="FACILITY_ONLY"
                                           <?php echo $allocation['allocation_type'] === 'FACILITY_ONLY' ? 'checked' : ''; ?>>
                                    <i class="ri-building-2-line"></i>
                                    <div class="type-title">Facility Only</div>
                                    <div class="type-desc">Allocate entire amount to Prodigy</div>
                                </label>
                                
                                <label class="type-option <?php echo $allocation['allocation_type'] === 'DOCTOR_AND_FACILITY' ? 'active' : ''; ?>" for="doctorAndFacility">
                                    <input type="radio" name="allocation_type" id="doctorAndFacility" value="DOCTOR_AND_FACILITY"
                                           <?php echo $allocation['allocation_type'] === 'DOCTOR_AND_FACILITY' ? 'checked' : ''; ?>>
                                    <i class="ri-share-forward-line"></i>
                                    <div class="type-title">Split Allocation</div>
                                    <div class="type-desc">Split between doctor and facility</div>
                                </label>
                            </div>
                            
                            <!-- Doctor Allocation Fields -->
                            <div id="doctorFields" class="<?php echo in_array($allocation['allocation_type'], ['DOCTOR_ONLY', 'DOCTOR_AND_FACILITY']) ? '' : 'hidden'; ?>">
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Select Doctor <span class="text-danger">*</span></label>
                                        <select class="form-select" name="doctor_id" id="doctorSelect">
                                            <option value="">Choose doctor...</option>
                                            <?php while ($doctor = $doctors->fetch_assoc()): ?>
                                                <option value="<?php echo $doctor['doctor_id']; ?>"
                                                        data-commission="<?php echo $doctor['commission_rate']; ?>"
                                                        <?php echo $allocation['doctor_id'] == $doctor['doctor_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($doctor['full_name']); ?>
                                                    <?php if ($doctor['specialization']): ?>
                                                        - <?php echo htmlspecialchars($doctor['specialization']); ?>
                                                    <?php endif; ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Doctor Commission Rate (%) <span class="text-danger">*</span></label>
                                        <input type="number" class="form-control" name="doctor_commission_rate" 
                                               id="doctorCommissionRate" step="0.01" min="0" max="100"
                                               value="<?php echo $allocation['doctor_commission_rate']; ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Facility Percentage for Split -->
                            <div id="facilityFields" class="<?php echo $allocation['allocation_type'] === 'DOCTOR_AND_FACILITY' ? '' : 'hidden'; ?> mt-3">
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Facility Percentage (%) <span class="text-danger">*</span></label>
                                        <input type="number" class="form-control" name="facility_percentage" 
                                               id="facilityPercentage" step="0.01" min="0" max="100"
                                               value="<?php echo $allocation['facility_percentage']; ?>">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Deductions -->
                        <div class="form-card">
                            <div class="section-title">
                                <i class="ri-subtract-line"></i>Deductions (Optional)
                            </div>
                            
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Tax Withheld (KES)</label>
                                    <input type="number" class="form-control" name="tax_withheld" 
                                           id="taxWithheld" step="0.01" min="0" 
                                           value="<?php echo $allocation['tax_withheld']; ?>">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Other Deductions (KES)</label>
                                    <input type="number" class="form-control" name="other_deductions" 
                                           id="otherDeductions" step="0.01" min="0"
                                           value="<?php echo $allocation['other_deductions']; ?>">
                                </div>
                            </div>
                        </div>
                        
                        <!-- Calculation Summary -->
                        <div class="form-card">
                            <div class="section-title">
                                <i class="ri-calculator-line"></i>Allocation Summary
                            </div>
                            
                            <div class="calculation-box">
                                <div class="calculation-row">
                                    <span>Total Service Cost:</span>
                                    <strong id="displayServiceCost">KES <?php echo number_format($allocation['total_service_cost'], 2); ?></strong>
                                </div>
                                <div class="calculation-row" id="doctorAllocationRow">
                                    <span>Doctor Allocation:</span>
                                    <span class="text-primary" id="displayDoctorAllocation">KES <?php echo number_format($allocation['doctor_allocation'], 2); ?></span>
                                </div>
                                <div class="calculation-row" id="facilityAllocationRow">
                                    <span>Facility Allocation:</span>
                                    <span class="text-info" id="displayFacilityAllocation">KES <?php echo number_format($allocation['facility_allocation'], 2); ?></span>
                                </div>
                                <div class="calculation-row" id="taxRow">
                                    <span>Less: Tax Withheld:</span>
                                    <span class="text-danger" id="displayTax">KES <?php echo number_format($allocation['tax_withheld'], 2); ?></span>
                                </div>
                                <div class="calculation-row" id="deductionsRow">
                                    <span>Less: Other Deductions:</span>
                                    <span class="text-danger" id="displayDeductions">KES <?php echo number_format($allocation['other_deductions'], 2); ?></span>
                                </div>
                                <div class="calculation-row total" id="netPaymentRow">
                                    <span>Net Doctor Payment:</span>
                                    <strong id="displayNetPayment">KES <?php echo number_format($allocation['net_doctor_payment'], 2); ?></strong>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Additional Notes -->
                        <div class="form-card">
                            <div class="section-title">
                                <i class="ri-file-list-line"></i>Additional Notes
                            </div>
                            
                            <div class="row g-3">
                                <div class="col-md-12">
                                    <label class="form-label">Notes</label>
                                    <textarea class="form-control" name="notes" rows="3"><?php echo htmlspecialchars($allocation['notes']); ?></textarea>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Form Actions -->
                        <div class="form-card">
                            <div class="d-flex justify-content-between align-items-center">
                                <a href="view_payment_allocation.php?id=<?php echo $allocation_id; ?>" class="btn btn-secondary">
                                    <i class="ri-close-line me-1"></i>Cancel
                                </a>
                                <button type="submit" class="btn btn-success">
                                    <i class="ri-save-line me-1"></i>Update Allocation
                                </button>
                            </div>
                        </div>
                        
                    </form>
                    
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize Flatpickr
            flatpickr('.datepicker', {
                dateFormat: 'Y-m-d',
                allowInput: true,
                maxDate: 'today'
            });
            
            // Allocation type selection
            const typeOptions = document.querySelectorAll('.type-option');
            const doctorFields = document.getElementById('doctorFields');
            const facilityFields = document.getElementById('facilityFields');
            
            typeOptions.forEach(option => {
                option.addEventListener('click', function() {
                    typeOptions.forEach(opt => opt.classList.remove('active'));
                    this.classList.add('active');
                    const radio = this.querySelector('input[type="radio"]');
                    radio.checked = true;
                    
                    const allocationType = radio.value;
                    
                    if (allocationType === 'DOCTOR_ONLY') {
                        doctorFields.classList.remove('hidden');
                        facilityFields.classList.add('hidden');
                    } else if (allocationType === 'FACILITY_ONLY') {
                        doctorFields.classList.add('hidden');
                        facilityFields.classList.add('hidden');
                    } else {
                        doctorFields.classList.remove('hidden');
                        facilityFields.classList.remove('hidden');
                    }
                    
                    calculateAllocations();
                });
            });
            
            // Doctor selection - auto-fill commission rate
            const doctorSelect = document.getElementById('doctorSelect');
            const doctorCommissionRate = document.getElementById('doctorCommissionRate');
            
            doctorSelect.addEventListener('change', function() {
                const selected = this.options[this.selectedIndex];
                if (this.value && selected.dataset.commission) {
                    doctorCommissionRate.value = selected.dataset.commission;
                    calculateAllocations();
                }
            });
            
            // Calculate allocations on input change
            const totalServiceCost = document.getElementById('totalServiceCost');
            const taxWithheld = document.getElementById('taxWithheld');
            const otherDeductions = document.getElementById('otherDeductions');
            const facilityPercentage = document.getElementById('facilityPercentage');
            
            [totalServiceCost, doctorCommissionRate, taxWithheld, otherDeductions, facilityPercentage].forEach(input => {
                if (input) {
                    input.addEventListener('input', calculateAllocations);
                }
            });
            
            function calculateAllocations() {
                const serviceCost = parseFloat(totalServiceCost.value) || 0;
                const doctorRate = parseFloat(doctorCommissionRate.value) || 0;
                const tax = parseFloat(taxWithheld.value) || 0;
                const deductions = parseFloat(otherDeductions.value) || 0;
                const facilityRate = parseFloat(facilityPercentage.value) || 0;
                
                const allocationType = document.querySelector('input[name="allocation_type"]:checked')?.value;
                
                let doctorAllocation = 0;
                let facilityAllocation = 0;
                let netPayment = 0;
                
                document.getElementById('displayServiceCost').textContent = 
                    'KES ' + serviceCost.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                
                if (allocationType === 'DOCTOR_ONLY') {
                    doctorAllocation = serviceCost * (doctorRate / 100);
                    netPayment = doctorAllocation - tax - deductions;
                    
                    document.getElementById('doctorAllocationRow').style.display = 'flex';
                    document.getElementById('facilityAllocationRow').style.display = 'none';
                    document.getElementById('netPaymentRow').style.display = 'flex';
                    
                } else if (allocationType === 'FACILITY_ONLY') {
                    facilityAllocation = serviceCost;
                    
                    document.getElementById('doctorAllocationRow').style.display = 'none';
                    document.getElementById('facilityAllocationRow').style.display = 'flex';
                    document.getElementById('netPaymentRow').style.display = 'none';
                    document.getElementById('taxRow').style.display = 'none';
                    document.getElementById('deductionsRow').style.display = 'none';
                    
                } else if (allocationType === 'DOCTOR_AND_FACILITY') {
                    doctorAllocation = serviceCost * (doctorRate / 100);
                    facilityAllocation = serviceCost * (facilityRate / 100);
                    netPayment = doctorAllocation - tax - deductions;
                    
                    document.getElementById('doctorAllocationRow').style.display = 'flex';
                    document.getElementById('facilityAllocationRow').style.display = 'flex';
                    document.getElementById('netPaymentRow').style.display = 'flex';
                }
                
                if (doctorAllocation > 0) {
                    document.getElementById('displayDoctorAllocation').textContent = 
                        'KES ' + doctorAllocation.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                }
                
                if (facilityAllocation > 0) {
                    document.getElementById('displayFacilityAllocation').textContent = 
                        'KES ' + facilityAllocation.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                }
                
                if (tax > 0) {
                    document.getElementById('taxRow').style.display = 'flex';
                    document.getElementById('displayTax').textContent = 
                        'KES ' + tax.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                } else {
                    document.getElementById('taxRow').style.display = 'none';
                }
                
                if (deductions > 0) {
                    document.getElementById('deductionsRow').style.display = 'flex';
                    document.getElementById('displayDeductions').textContent = 
                        'KES ' + deductions.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                } else {
                    document.getElementById('deductionsRow').style.display = 'none';
                }
                
                if (allocationType !== 'FACILITY_ONLY' && doctorAllocation > 0) {
                    document.getElementById('displayNetPayment').textContent = 
                        'KES ' + netPayment.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                }
            }
            
            // Initial calculation
            calculateAllocations();
            
            // Form validation
            document.getElementById('allocationForm').addEventListener('submit', function(e) {
                const allocationType = document.querySelector('input[name="allocation_type"]:checked');
                
                if (!allocationType) {
                    e.preventDefault();
                    Swal.fire('Error', 'Please select an allocation type', 'error');
                    return false;
                }
                
                Swal.fire({
                    title: 'Processing...',
                    text: 'Updating allocation',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
            });
        });
    </script>
</body>
</html>