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

// Fetch existing claim numbers for reuse
$sql_claims = "SELECT DISTINCT claim_no FROM bills ORDER BY claim_no DESC";
$result_claims = $conn->query($sql_claims);
$existing_claims = [];
while($row = $result_claims->fetch_assoc()) {
    $existing_claims[] = $row['claim_no'];
}

// Fetch providers
$sql_providers = "SELECT provider_id, provider_name FROM providers WHERE status = 1";
$result_providers = $conn->query($sql_providers);
$providers = [];
while($row = $result_providers->fetch_assoc()) {
    $providers[] = $row;
}

// Fetch benefits/services
$sql_benefits = "SELECT code, benefit FROM benefit";
$result_benefits = $conn->query($sql_benefits);
$benefits = [];
while($row = $result_benefits->fetch_assoc()) {
    $benefits[] = $row;
}

// Fetch benefits/services
$sql_services = "SELECT code, service FROM services";
$result_services = $conn->query($sql_services);
$services = [];
while($row = $result_services->fetch_assoc()) {
    $services[] = $row;
}

// Fetch corporates

$sql_corporates = "SELECT corp_id, corporate FROM corporate WHERE cancelled = 0 ORDER BY corporate";
$result_corporates = $conn->query($sql_corporates);
$corporates = [];
while($row = $result_corporates->fetch_assoc()) {
    $corporates[] = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Claims Entry')); ?>
    <?php include 'layouts/head-css.php'; ?>

    <!-- Sweet Alert css-->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <style>
.unsaved-changes {
    border-color: #ffc107;
    box-shadow: 0 0 0 0.2rem rgba(255, 193, 7, 0.25);
}

.auto-add-pending {
    border-color: #28a745;
    box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
}

.member-details {
    transition: all 0.3s ease;
    display: none;
}

.member-details.selected-member {
    display: block;
}

.select2-container .select2-selection--single {
    height: 36px !important;
}

.select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 36px;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 34px;
}
</style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Claims', 'title' => 'Claims Entry')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">New Claim Entry</h4>
                                </div>

                                <div class="card-body">
                                    <form id="claimForm">
                                        <!-- Invoice Details Section -->
                                        <div class="row mb-4">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Claim Type</label>
                                                    <select class="form-select" id="claimType" required>
                                                        <option value="">Select Type</option>
                                                        <option value="new">New Claim</option>
                                                        <option value="existing">Existing Invoice</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Claim/Invoice Number</label>
                                                    <div class="input-group">
                                                        <input type="text" class="form-control" id="claimNo" readonly>
                                                        <button class="btn btn-primary" type="button" id="searchClaim">
                                                            <i class="ri-search-line"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Invoice Date</label>
                                                    <input type="date" class="form-control" id="invoiceDate" required>
                                                </div>
                                            </div>

                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Provider</label>
                                                    <select class="form-select" id="provider" name="provider" required>
                                                        <option value="">Select Provider</option>
                                                        <?php foreach($providers as $provider): ?>
                                                            <option value="<?php echo $provider['provider_id']; ?>">
                                                                <?php echo $provider['provider_name']; ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Corporate Selection Section -->
                                        <div class="row mb-4">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Corporate</label>
                                                    <select class="form-select" id="corporate" name="corporate" required>
                                                        <option value="">Select Corporate</option>
                                                        <?php foreach($corporates as $corporate): ?>
                                                            <option value="<?php echo $corporate['corp_id']; ?>">
                                                                <?php echo $corporate['corporate']; ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Member Search Section -->
                                        <div class="row mb-4">
                                            <div class="col-lg-6">
                                                <label class="form-label">Member Search</label>
                                                <div class="input-group">
                                                    <input type="text" class="form-control" id="memberSearch"
                                                           placeholder="Enter member number or name (minimum 3 characters)">
                                                    <button class="btn btn-primary" type="button" id="searchMember">
                                                        <i class="ri-search-line"></i>
                                                    </button>
                                                </div>
                                                <div id="searchResults" class="mt-2"></div>
                                            </div>

                                            <div class="col-lg-6">
                                                <div class="member-card member-details" id="memberDetails">
                                                    <div class="card border">
                                                        <div class="card-body">
                                                            <h5 class="card-title mb-3">Member Details</h5>
                                                            <div class="table-responsive">
                                                                <table class="table table-sm table-borderless mb-0">
                                                                    <tr>
                                                                        <th width="130">Member Name:</th>
                                                                        <td id="memberName"></td>
                                                                    </tr>
                                                                    <tr>
                                                                        <th>Member No:</th>
                                                                        <td id="memberNo"></td>
                                                                    </tr>
                                                                     <tr>
                                                                        <th>Family No:</th>
                                                                        <td id="familyNo"></td>
                                                                    </tr>
                                                                     <tr>
                                                                        <th>Relation to Principal:</th>
                                                                        <td id="priDep"></td>
                                                                    </tr>
                                                                    <tr>
                                                                        <th>Corporate:</th>
                                                                        <td id="memberCorporate"></td>
                                                                    </tr>
                                                                </table>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Claims Entry Section -->
                                        <div class="row">
                                            <div class="col-12">
                                                <div class="card border">
                                                    <div class="card-header bg-light">
                                                        <h5 class="card-title mb-0">Claim Details</h5>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row mb-3">
                                                            <div class="col-md-3">
                                                                <label class="form-label">Service/Benefit</label>
                                                                <select class="js-example-basic-single" id="benefit" name="benefit">
                                                                    <option value="">Select Benefit</option>
                                                                    <?php foreach($benefits as $benefit): ?>
                                                                        <option value="<?php echo $benefit['code']; ?>">
                                                                            <?php echo $benefit['benefit']; ?>
                                                                        </option>
                                                                    <?php endforeach; ?>
                                                                </select>
                                                            </div>

                                                            <div class="col-md-3">
                                                                <label class="form-label">Amount</label>
                                                                <input type="number" class="form-control" id="amount" step="0.01" >
                                                            </div>

                                                            <div class="col-md-3">
                                                                <label class="form-label">Invoice Number</label>
                                                                <input type="text" class="form-control" id="invoiceNo" >
                                                            </div>

                                                            <div class="col-md-3">
                                                                <label class="form-label">Date Received</label>
                                                                <input type="date" class="form-control" id="dateReceived" >
                                                            </div>

                                                           <div class="col-md-4">
                                                                <label class="form-label">Service Description</label>
                                                                <select class="js-example-basic-single" id="description">
                                                                    <option value="">Select Service</option>
                                                                    <?php foreach($services as $service): ?>
                                                                        <option value="<?php echo $service['code']; ?>">
                                                                            <?php echo htmlspecialchars($service['service']); ?>
                                                                        </option>
                                                                    <?php endforeach; ?>
                                                                </select>
                                                            </div>

                                                            <div class="col-md-2">
                                                                <label class="form-label">&nbsp;</label>
                                                                <button type="button" class="btn btn-primary w-100" id="addClaimLine">
                                                                    Add Line
                                                                </button>
                                                            </div>

                                                            <!-- Diagnosis Section -->
                                                            <div class="row mt-4">
                                                                <div class="col-12">
                                                                    <div class="card border">
                                                                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                                                                            <h5 class="card-title mb-0">Diagnosis Information</h5>
                                                                            <button type="button" class="btn btn-primary btn-sm" id="addDiagnosis">
                                                                                <i class="ri-add-line"></i> Add Diagnosis
                                                                            </button>
                                                                        </div>
                                                                        <div class="card-body">
                                                                            <div class="table-responsive">
                                                                                <table class="table table-bordered" id="diagnosisTable">
                                                                                    <thead>
                                                                                        <tr>
                                                                                            <th>ICD10 Code</th>
                                                                                            <th>Description</th>
                                                                                            <th>Primary</th>
                                                                                            <th>Actions</th>
                                                                                        </tr>
                                                                                    </thead>
                                                                                    <tbody></tbody>
                                                                                </table>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                        </div>

                                                        <!-- Claims Table -->
                                                        <div class="table-responsive">
                                                            <table class="table table-bordered" id="claimsTable">
                                                                <thead>
                                                                    <tr>
                                                                        <th>Benefit</th>
                                                                        <th>Description</th>
                                                                        <th>Amount</th>
                                                                        <th>Invoice Number</th>
                                                                        <th>Date Received</th>
                                                                        <th>Actions</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody></tbody>
                                                                <tfoot>
                                                                    <tr>
                                                                        <th colspan="4" class="text-end">Total:</th>
                                                                        <th id="totalAmount">0.00</th>
                                                                        <th></th>
                                                                    </tr>
                                                                </tfoot>
                                                            </table>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Submit Buttons -->
                                        <div class="row mt-4">
                                            <div class="col-12">
                                                <div class="d-flex justify-content-end gap-2">
                                                    <button type="button" class="btn btn-primary btn-label waves-effect waves-light rounded-pill" id="saveDraft">
                                                        <i class="ri-draft-line label-icon align-middle rounded-pill fs-16 me-2"></i>
                                                        Save as Draft
                                                    </button>

                                                    <button type="submit" class="btn btn-success btn-label waves-effect waves-light rounded-pill" id="submitClaim">
                                                    	<i class="ri-check-double-line label-icon align-middle rounded-pill fs-16 me-2"></i>
                                                    	Submit Claim
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </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="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/js/pages/select2.init.js"></script>
    <script src="assets/js/app.js"></script>
    <script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize state variables
    let claimLines = [];
    let currentMember = null;
    let hasUnsavedChanges = false;
    let autoAddTimeout = null;

    // DOM Elements
    const claimForm = document.getElementById('claimForm');
    const claimTypeSelect = document.getElementById('claimType');
    const claimNoInput = document.getElementById('claimNo');
    const searchClaimBtn = document.getElementById('searchClaim');
    const corporateSelect = document.getElementById('corporate');
    const memberSearchBtn = document.getElementById('searchMember');
    const memberSearchInput = document.getElementById('memberSearch');
    const addClaimLineBtn = document.getElementById('addClaimLine');

    // Initialize event listeners
    initializeEventListeners();

    function initializeEventListeners() {
        claimTypeSelect?.addEventListener('change', handleClaimTypeChange);
        searchClaimBtn?.addEventListener('click', handleClaimSearch);
        corporateSelect?.addEventListener('change', handleCorporateChange);
        memberSearchBtn?.addEventListener('click', handleMemberSearch);
        addClaimLineBtn?.addEventListener('click', handleAddClaimLine);

        // Add auto-add functionality
        setupAutoAdd();

        // Add event listener for delete claim line buttons
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('delete-claim-line') ||
                e.target.closest('.delete-claim-line')) {
                const index = parseInt(e.target.closest('.delete-claim-line').dataset.index);
                removeLine(index);
            }
        });

        // Add beforeunload event listener for unsaved changes
        window.addEventListener('beforeunload', (e) => {
            if (hasUnsavedChanges || hasPartialInput()) {
                e.preventDefault();
                e.returnValue = '';
            }
        });

        // Form submit handler
        claimForm?.addEventListener('submit', handleFormSubmit);
    }

    function setupAutoAdd() {
        const fields = ['benefit', 'amount', 'description', 'invoiceNo', 'dateReceived'];
        fields.forEach(fieldId => {
            const field = document.getElementById(fieldId);
            if (field) {
                field.addEventListener('input', () => {
                    hasUnsavedChanges = true;
                    updateFieldStatus();
                    checkForAutoAdd();
                });
            }
        });
    }

    function updateFieldStatus() {
        const fields = ['benefit', 'amount', 'description', 'invoiceNo', 'dateReceived'];
        const allFilled = fields.every(fieldId => {
            const field = document.getElementById(fieldId);
            return field && field.value.trim() !== '';
        });

        fields.forEach(fieldId => {
            const field = document.getElementById(fieldId);
            if (field) {
                field.classList.toggle('unsaved-changes', field.value.trim() !== '');
                field.classList.toggle('auto-add-pending', allFilled);
            }
        });
    }

   function validateCoreFields() {
    if (!currentMember) {
        showWarning('Please select a member first');
        return false;
    }

    if (!document.getElementById('invoiceDate').value) {
        showWarning('Please select an invoice date');
        return false;
    }

    if (!document.getElementById('provider').value) {
        showWarning('Please select a provider');
        return false;
    }

    return true;
}

    function handleClaimTypeChange() {
        const selectedType = claimTypeSelect.value;
        if (selectedType === 'new') {
            generateNewClaimNumber();
            claimNoInput.readOnly = true;
            searchClaimBtn.style.display = 'none';
        } else {
            claimNoInput.readOnly = false;
            claimNoInput.value = '';
            searchClaimBtn.style.display = 'block';
        }
    }

    function handleCorporateChange() {
        // Reset member details when corporate changes
        currentMember = null;
        document.getElementById('memberDetails').classList.remove('selected-member');
        document.getElementById('memberName').textContent = '';
        document.getElementById('memberNo').textContent = '';
        document.getElementById('familyNo').textContent = '';
        document.getElementById('priDep').textContent = '';
        document.getElementById('memberCorporate').textContent = '';
    }

function handleFormSubmit(e) {
    e.preventDefault();

    console.log("Form submission started, current claim lines:", claimLines);

    // Validate core fields (e.g., member, invoice date, provider)
    if (!validateCoreFields()) {
        console.log("Core fields validation failed");
        return;
    }

    // If we already have claim lines, proceed with submission
    if (claimLines.length > 0) {
        console.log("Existing claim lines found, proceeding with submission");
        submitFormData();
        return;
    }

    // Check if there's partial input for a new claim line
    if (hasPartialInput()) {
        console.log("Found partial input, prompting user");
        Swal.fire({
            title: 'Unsaved Changes',
            text: 'You have unsaved changes in the claim line fields. Would you like to add them before submitting?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Add and Submit',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                handleAddClaimLine(); // Add the partial input as a claim line
                if (claimLines.length > 0) {
                    submitFormData();
                }
            }
        });
    } else {
        showWarning('Please add at least one claim line');
    }
}

function validateForm() {
    console.log("Validating form, claim lines:", claimLines.length);

    // If no existing claims, validate core fields and require at least one claim line
    if (!validateCoreFields()) {
        return false;
    }

    // If there are existing claim lines, we're done
    //if (claimLines.length > 0) {
    //    return true;
    //}

    if (!selectedDiagnoses.length) {
        showWarning('Please add at least one diagnosis');
        return false;
    }

    if (claimLines.length > 0) {
        console.log("Has claim lines, validation passed");
        return true;
    }

    // No existing lines - check if there's a partial claim line being entered
    if (hasPartialInput()) {
        const benefit = document.getElementById('benefit');
        const amount = document.getElementById('amount');
        const description = document.getElementById('description');
        const invoiceNo = document.getElementById('invoiceNo');
        const dateReceived = document.getElementById('dateReceived');

        if (!validateClaimLine(benefit, amount, description, invoiceNo, dateReceived)) {
            return false;
        }
    } else {
        showWarning('Please add at least one claim line');
        return false;
    }

    return true;
}

    function hasPartialInput() {
        const fields = ['benefit', 'amount', 'description', 'invoiceNo', 'dateReceived'];
        return fields.some(fieldId => {
            const field = document.getElementById(fieldId);
            return field && field.value.trim() !== '';
        });
    }

    function checkForAutoAdd() {
        if (autoAddTimeout) {
            clearTimeout(autoAddTimeout);
        }

        autoAddTimeout = setTimeout(() => {
            const fields = ['benefit', 'amount', 'description', 'invoiceNo', 'dateReceived'];
            const allFilled = fields.every(fieldId => {
                const field = document.getElementById(fieldId);
                return field && field.value.trim() !== '';
            });

            if (allFilled) {
                handleAddClaimLine();
            }
        }, 1000);
    }

    function generateNewClaimNumber() {
        fetch('generate_claim_number.php')
            .then(response => response.json())
            .then(data => {
                if (data.error) throw new Error(data.error);
                claimNoInput.value = data.claim_number;
            })
            .catch(error => {
                showError('Failed to generate claim number: ' + error.message);
            });
    }

    function handleMemberSearch() {
        const searchValue = memberSearchInput.value.trim();
        const corporateId = corporateSelect.value;

        if (searchValue.length < 3) {
            showWarning('Please enter at least 3 characters to search');
            return;
        }

        fetch('search_member.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'search=' + encodeURIComponent(searchValue) + '&corporate_id=' + encodeURIComponent(corporateId)
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success || !data.members.length) {
                throw new Error(data.error || 'No members found');
            }
            updateMemberDetails(data.members[0]);
        })
        .catch(error => {
            showError(error.message);
        });
    }

    // Update updateMemberDetails function
function updateMemberDetails(member) {
    currentMember = member;

    // Update existing member details
    document.getElementById('memberName').textContent = member.name;
    document.getElementById('memberNo').textContent = member.member_no;
    document.getElementById('memberCorporate').textContent = member.corporate_name;
    document.getElementById('familyNo').textContent = member.family_no;
    document.getElementById('priDep').textContent = member.relation_to_principal;

    // Add benefit utilization table
    const benefitsHtml = `
        <div class="mt-3">
            <h6 class="mb-2">Benefit Utilization</h6>
            <div class="table-responsive">
                <table class="table table-sm table-bordered">
                    <thead>
                        <tr>
                            <th>Benefit</th>
                            <th class="text-end">Limit</th>
                            <th class="text-end">Claims Used</th>
                            <th class="text-end">Pre-auths</th>
                            <th class="text-end">Total Used</th>
                            <th class="text-end">Available</th>
                            <th class="text-end">%</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${member.benefits.map(benefit => `
                            <tr>
                                <td>${benefit.benefit_name}</td>
                                <td class="text-end">${benefit.limit.toLocaleString()}</td>
                                <td class="text-end">${benefit.used_claims.toLocaleString()}</td>
                                <td class="text-end">${benefit.used_preauths.toLocaleString()}</td>
                                <td class="text-end">${benefit.total_used.toLocaleString()}</td>
                                <td class="text-end">${benefit.available.toLocaleString()}</td>
                                <td class="text-end">
                                    <span class="badge bg-${
                                        benefit.percent_used >= 80 ? 'danger' :
                                        benefit.percent_used >= 50 ? 'warning' : 'success'
                                    }">${benefit.percent_used.toFixed(1)}%</span>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        </div>
    `;

    document.getElementById('memberDetails').innerHTML += benefitsHtml;
    document.getElementById('memberDetails').classList.add('selected-member');
}

 // Add this function to check for pre-auths
function checkForPreAuth(benefitCode, serviceCode) {
    const params = new URLSearchParams({
        member_no: currentMember.member_no,
        benefit: benefitCode,
        service: serviceCode,
        provider: document.getElementById('provider').value
    });

    return fetch('check_preauth.php?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (data.preauth) {
                Swal.fire({
                    title: 'Pre-Authorization Found',
                    text: `A matching pre-authorization (${data.preauth.pre_auth_code}) with reserve amount ${data.preauth.reserve} was found. It will be attached to this claim.`,
                    icon: 'info',
                    confirmButtonText: 'OK'
                });
                return true;
            }
            return false;
        })
        .catch(error => {
            console.error('Error checking pre-auth:', error);
            return false;
        });
}

async function handleAddClaimLine() {
    console.log("Adding new claim line");
    const benefit = document.getElementById('benefit');
    const amount = document.getElementById('amount');
    const description = document.getElementById('description');
    const invoiceNo = document.getElementById('invoiceNo');
    const dateReceived = document.getElementById('dateReceived');

    // Only validate fields when actually adding a new line
    if (!validateClaimLine(benefit, amount, description, invoiceNo, dateReceived)) {
        console.log("New line validation failed");
        return;
    }

    // Check for matching pre-auth before adding claim line
    try {
        const params = new URLSearchParams({
            member_no: currentMember.member_no,
            benefit: benefit.value,
            service: description.value,
            provider: document.getElementById('provider').value
        });

        console.log("Checking for pre-auth with params:", Object.fromEntries(params));

        const response = await fetch('check_preauth.php?' + params.toString());
        const data = await response.json();

        if (data.preauth) {
            console.log("Matching pre-auth found:", data.preauth);
            await Swal.fire({
                title: 'Pre-Authorization Found',
                text: `A matching pre-authorization (${data.preauth.pre_auth_code}) with reserve amount ${new Intl.NumberFormat('en-US', { style: 'currency', currency: 'KES' }).format(data.preauth.reserve)} was found. It will be attached to this claim.`,
                icon: 'info',
                confirmButtonText: 'OK'
            });
        } else {
            console.log("No matching pre-auth found");
        }
    } catch (error) {
        console.error("Error checking pre-auth:", error);
    }

    const claimLine = {
        benefit_code: benefit.value,
        benefit_name: benefit.options[benefit.selectedIndex].text,
        amount: parseFloat(amount.value),
        description: description.value,
        description_text: description.options[description.selectedIndex].text,
        invoiceNo: invoiceNo.value,
        dateReceived: dateReceived.value
    };

    claimLines.push(claimLine);
    console.log("New line added, current claim lines:", claimLines);
    updateClaimsTable();
    resetClaimLineForm();
}

   function validateClaimLine(benefit, amount, description, invoiceNo, dateReceived) {
    if (!benefit.value) {
        showWarning('Please select a benefit');
        benefit.focus();
        return false;
    }

    // Check benefit limit
    const benefitData = currentMember.benefits.find(b => b.benefit_code === benefit.value);
    if (!benefitData) {
        showWarning('Benefit not found for member');
        return false;
    }

    // Calculate total amount for this benefit including new claim
    const existingAmount = claimLines
        .filter(line => line.benefit_code === benefit.value)
        .reduce((sum, line) => sum + line.amount, 0);
    const newTotal = existingAmount + parseFloat(amount.value);

    // Check if new total would exceed available amount (considering both claims and pre-auths)
    if (newTotal > benefitData.available) {
        showWarning(`This claim would exceed the available benefit limit of ${benefitData.available.toLocaleString()}.
            (Used: Claims ${benefitData.used_claims.toLocaleString()},
            Pre-auths ${benefitData.used_preauths.toLocaleString()})`);
        return false;
    }

    // Check if new total would exceed available amount
    if (newTotal > benefitData.available) {
        showWarning(`This claim would exceed the available benefit limit of ${benefitData.available.toLocaleString()}`);
        return false;
    }

    if (!amount.value || isNaN(amount.value) || parseFloat(amount.value) <= 0) {
        showWarning('Please enter a valid amount greater than 0');
        amount.focus();
        return false;
    }

    if (!description.value) {
        showWarning('Please select a service description');
        description.focus();
        return false;
    }

    if (!invoiceNo.value) {
        showWarning('Please enter an invoice number');
        invoiceNo.focus();
        return false;
    }

    if (!dateReceived.value) {
        showWarning('Please enter a received date');
        dateReceived.focus();
        return false;
    }

    return true;
}

    function updateClaimsTable() {
    const tbody = document.querySelector('#claimsTable tbody');
    const tfootTotal = document.getElementById('totalAmount');

    tbody.innerHTML = '';
    let total = 0;

    claimLines.forEach((line, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${line.benefit_name}</td>
            <td>${line.description_text}</td>
            <td class="text-end">${parseFloat(line.amount).toFixed(2)}</td>
            <td>${line.invoiceNo}</td>
            <td>${line.dateReceived}</td>
            <td>
                <button type="button" class="btn btn-sm btn-danger delete-claim-line" data-index="${index}">
                    <i class="ri-delete-bin-line"></i>
                </button>
            </td>
        `;
        tbody.appendChild(row);
        total += parseFloat(line.amount);
    });

    tfootTotal.textContent = total.toFixed(2);
}

    function removeLine(index) {
        claimLines.splice(index, 1);
        updateClaimsTable();
    }

    function resetClaimLineForm() {
        const fields = ['benefit', 'amount', 'description', 'invoiceNo', 'dateReceived'];
        fields.forEach(fieldId => {
            const field = document.getElementById(fieldId);
            if (field) {
                field.value = '';
                field.classList.remove('unsaved-changes', 'auto-add-pending');
            }
        });
        hasUnsavedChanges = false;
        if (autoAddTimeout) {
            clearTimeout(autoAddTimeout);
            autoAddTimeout = null;
        }
    }

    function submitFormData() {
    console.log("Submitting form data with claim lines:", claimLines);

    const formData = {
        claim_no: claimNoInput.value,
        invoice_date: document.getElementById('invoiceDate').value,
        provider: document.getElementById('provider').value,
        member_no: currentMember.member_no,
        corp_id: currentMember.corp_id,
        family_no: currentMember.family_no,
        pri_dep: currentMember.relation_to_principal,
        claims: claimLines,
        diagnoses: selectedDiagnoses.map(d => ({
            id: d.id,
            primary: d.primary ? 1 : 0
        }))
    };

    Swal.fire({
        title: 'Saving...',
        text: 'Please wait while we process your claim',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch('save_claim.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) throw new Error(data.error);

        Swal.fire({
            icon: 'success',
            title: 'Success',
            text: 'Claim saved successfully!',
            confirmButtonText: 'View Claim'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'view_claim.php?id=' + data.claim_no;
            }
        });
    })
    .catch(error => {
        showError('Failed to save claim: ' + error.message);
    });
}

    function handleClaimSearch() {
        const claimNo = claimNoInput.value.trim();

        if (!claimNo) {
            showWarning('Please enter a claim number');
            return;
        }

        fetch('fetch_claim.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'claim_no=' + encodeURIComponent(claimNo)
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) throw new Error(data.error);
            populateExistingClaim(data);
        })
        .catch(error => {
            showError('Failed to fetch claim: ' + error.message);
        });
    }

    function populateExistingClaim(data) {
        document.getElementById('invoiceDate').value = data.invoice_date;
        document.getElementById('provider').value = data.provider;

        currentMember = {
            member_no: data.member_no,
            corp_id: data.corp_id,
            family_no: data.family_no,
            relation_to_principal: data.pri_dep,
            name: data.member_first_name + ' ' + data.member_surname,
            corporate_name: data.corporate_name
        };

        updateMemberDetails(currentMember);
        claimLines = data.claim_lines || [];
        updateClaimsTable();
    }

    function showWarning(message) {
        Swal.fire({
            icon: 'warning',
            title: 'Warning',
            text: message
        });
    }

    function showError(message) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: message
        });
    }

    // Add to your existing JavaScript
function saveDraft() {
    if (!currentMember) {
        showWarning('Please select a member first');
        return;
    }

    if (claimLines.length === 0) {
        showWarning('Please add at least one claim line');
        return;
    }

    const draftData = {
        claim_no: document.getElementById('claimNo').value || '',
        invoice_date: document.getElementById('invoiceDate').value || '',
        provider: document.getElementById('provider').value || '',
        member_no: currentMember.member_no,
        corp_id: currentMember.corp_id,
        family_no: currentMember.family_no,
        pri_dep: currentMember.relation_to_principal,
        claims: claimLines
    };

    // Validate required fields
    if (!draftData.invoice_date) {
        showWarning('Please select an invoice date');
        return;
    }

    if (!draftData.provider) {
        showWarning('Please select a provider');
        return;
    }

    Swal.fire({
        title: 'Saving Draft...',
        text: 'Please wait while we save your draft',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    console.log('Sending draft data:', draftData); // Debug log

    fetch('save_draft_claim.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(draftData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log('Response:', data); // Debug log

        if (!data.success) {
            throw new Error(data.error || 'Failed to save draft');
        }

        Swal.fire({
            icon: 'success',
            title: 'Success',
            text: 'Draft saved successfully!',
            showCancelButton: true,
            confirmButtonText: 'View Drafts',
            cancelButtonText: 'Continue Editing'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'view_draft_claims.php';
            }
        });
    })
    .catch(error => {
        console.error('Error:', error); // Debug log
        showError('Failed to save draft: ' + error.message);
    });
}

// Add event listener for the draft button
document.getElementById('saveDraft').addEventListener('click', saveDraft);

// Add function to check for existing draft
function checkForDraft() {
    if (!currentMember) return;

    fetch('check_draft_claim.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ member_no: currentMember.member_no })
    })
    .then(response => response.json())
    .then(data => {
        if (data.draft_exists) {
            Swal.fire({
                title: 'Draft Found',
                text: 'Would you like to load the existing draft for this member?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Load Draft',
                cancelButtonText: 'Start New'
            }).then((result) => {
                if (result.isConfirmed) {
                    loadDraft(data.draft_id);
                }
            });
        }
    })
    .catch(error => console.error('Error checking for draft:', error));
}
});

// Add these variables to your state variables section
let selectedDiagnoses = [];

// Add this to your initializeEventListeners function
document.getElementById('addDiagnosis')?.addEventListener('click', showDiagnosisSearch);

// Add these new functions
function showDiagnosisSearch() {
    Swal.fire({
        title: 'Add Diagnosis',
        html: `
            <div class="mb-3">
                <input type="text" id="diagnosisSearch" class="swal2-input" placeholder="Search ICD10 codes...">
            </div>
            <div id="diagnosisResults" class="mt-3" style="max-height: 200px; overflow-y: auto;"></div>
        `,
        showCancelButton: true,
        showConfirmButton: false,
        didOpen: () => {
            const searchInput = document.getElementById('diagnosisSearch');
            const resultsDiv = document.getElementById('diagnosisResults');
            let searchTimeout;

            searchInput.addEventListener('input', () => {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    const searchTerm = searchInput.value.trim();
                    if (searchTerm.length >= 2) {
                        searchDiagnoses(searchTerm, resultsDiv);
                    }
                }, 500);
            });
        }
    });
}

function searchDiagnoses(term, resultsDiv) {
    fetch('search_diagnoses.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `search=${encodeURIComponent(term)}`
    })
    .then(response => response.json())
    .then(data => {
        if (!data.success) {
            throw new Error(data.error || 'Failed to search diagnoses');
        }

        resultsDiv.innerHTML = data.diagnoses.map(diag => `
            <div class="d-flex align-items-center justify-content-between p-2 border-bottom">
                <div>
                    <strong>${diag.code}</strong> - ${diag.description}
                </div>
                <button class="btn btn-sm btn-primary select-diagnosis"
                        data-id="${diag.id}"
                        data-code="${diag.code}"
                        data-desc="${diag.description}">
                    Select
                </button>
            </div>
        `).join('');

        // Add click handlers for select buttons
        document.querySelectorAll('.select-diagnosis').forEach(btn => {
            btn.addEventListener('click', () => {
                addDiagnosis({
                    id: btn.dataset.id,
                    code: btn.dataset.code,
                    description: btn.dataset.desc
                });
                Swal.close();
            });
        });
    })
    .catch(error => {
        resultsDiv.innerHTML = `<div class="text-danger">${error.message}</div>`;
    });
}

function addDiagnosis(diagnosis) {
    if (selectedDiagnoses.some(d => d.id === diagnosis.id)) {
        showWarning('This diagnosis has already been added');
        return;
    }

    const isPrimary = selectedDiagnoses.length === 0; // First diagnosis is primary
    selectedDiagnoses.push({
        ...diagnosis,
        primary: isPrimary
    });

    updateDiagnosisTable();
}

function updateDiagnosisTable() {
    const tbody = document.querySelector('#diagnosisTable tbody');
    tbody.innerHTML = selectedDiagnoses.map((diag, index) => `
        <tr>
            <td>${diag.code}</td>
            <td>${diag.description}</td>
            <td>
                <div class="form-check">
                    <input class="form-check-input diagnosis-primary" type="radio"
                           name="primary_diagnosis"
                           value="${diag.id}"
                           ${diag.primary ? 'checked' : ''}>
                </div>
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger delete-diagnosis"
                        data-index="${index}">
                    <i class="ri-delete-bin-line"></i>
                </button>
            </td>
        </tr>
    `).join('');

    // Add event listeners
    document.querySelectorAll('.diagnosis-primary').forEach(radio => {
        radio.addEventListener('change', (e) => {
            selectedDiagnoses.forEach(d => d.primary = false);
            const diagnosis = selectedDiagnoses.find(d => d.id === e.target.value);
            if (diagnosis) {
                diagnosis.primary = true;
            }
        });
    });

    document.querySelectorAll('.delete-diagnosis').forEach(btn => {
        btn.addEventListener('click', () => {
            const index = parseInt(btn.dataset.index);
            const wasPromary = selectedDiagnoses[index].primary;
            selectedDiagnoses.splice(index, 1);
            if (wasPromary && selectedDiagnoses.length > 0) {
                selectedDiagnoses[0].primary = true;
            }
            updateDiagnosisTable();
        });
    });
}
    </script>
    <script>
    $(document).ready(function() {
   $('.js-example-basic-single[name="provider"]').select2({
       placeholder: "Select Provider",
       allowClear: true
   });

   $('.js-example-basic-single[name="benefit"]').select2({
       placeholder: "Select Benefit",
       allowClear: true
   });

   $('.js-example-basic-single[name="corporate"]').select2({
       placeholder: "Select Corporate",
       allowClear: true
   });
});
    </script>
</body>
</html>
