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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch corporates for dropdown
$sql_corporates = "SELECT corp_id, corporate FROM corporate WHERE cancelled = 0 ORDER BY corporate";
$result_corporates = $conn->query($sql_corporates);
$corporates = $result_corporates->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Member Search & Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Add select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        .search-results {
            max-height: 400px;
            overflow-y: auto;
        }
        .member-tabs .nav-link {
            padding: 10px 15px;
            border: none;
            border-bottom: 2px solid transparent;
            background: none;
        }
        .member-tabs .nav-link.active {
            border-bottom: 2px solid #556ee6;
            color: #556ee6;
        }
        .tab-content {
            padding: 20px 0;
        }
        .utilization-chart {
            height: 300px;
        }
    </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' => 'Members', 'title' => 'Member Search & Details')); ?>

                    <!-- Search Section -->
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title">Search Members</h4>
                                </div>
                                <div class="card-body">
                                    <form id="searchForm" class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label">Corporate</label>
                                            <select class="form-select select2" id="corporate" name="corp_id" required>
                                                <option value="">Select Corporate</option>
                                                <?php foreach ($corporates as $corporate): ?>
                                                    <option value="<?php echo $corporate['corp_id']; ?>"><?php echo htmlspecialchars($corporate['corporate']); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Member Number</label>
                                            <input type="text" class="form-control" id="memberNo" name="member_no">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Family Number</label>
                                            <input type="text" class="form-control" id="familyNo" name="family_no">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Name</label>
                                            <input type="text" class="form-control" id="memberName" name="member_name" 
                                                   placeholder="Enter name to search">
                                        </div>
                                        <div class="col-12 text-end">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-search-line me-1"></i> Search
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search Results -->
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="table-responsive search-results">
                                        <table class="table table-centered table-hover" id="searchResults">
                                            <thead>
                                                <tr>
                                                    <th>Member No</th>
                                                    <th>Name</th>
                                                    <th>Family No</th>
                                                    <th>Relationship</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Member Details Section -->
                    <div class="row" id="memberDetails" style="display: none;">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-body">
                                    <!-- Member Basic Info -->
                                    <div class="row mb-4">
                                        <div class="col-md-6">
                                            <h5 class="member-name mb-3"></h5>
                                            <div class="member-basic-info"></div>
                                        </div>
                                        <div class="col-md-6 text-md-end">
                                            <div class="member-status"></div>
                                        </div>
                                    </div>

                                    <!-- Tabs Navigation -->
                                    <ul class="nav nav-tabs member-tabs" role="tablist">
                                        <li class="nav-item">
                                            <a class="nav-link active" data-bs-toggle="tab" href="#personal" role="tab">
                                                Personal Details
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#family" role="tab">
                                                Family Details
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#benefits" role="tab">
                                                Benefits
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#claims" role="tab">
                                                Claims History
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#utilization" role="tab">
                                                Utilization
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#premium" role="tab">
                                                Premium History
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#anniversary" role="tab">
                                                Anniversary
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#documents" role="tab">
                                                Documents
                                            </a>
                                        </li>
                                    </ul>

                                    <!-- Tab Content -->
                                    <div class="tab-content">
                                        <!-- Personal Details Tab -->
                                        <div class="tab-pane active" id="personal" role="tabpanel"></div>

                                        <!-- Family Details Tab -->
                                        <div class="tab-pane" id="family" role="tabpanel"></div>

                                        <!-- Benefits Tab -->
                                        <div class="tab-pane" id="benefits" role="tabpanel"></div>

                                        <!-- Claims History Tab -->
                                        <div class="tab-pane" id="claims" role="tabpanel"></div>

                                        <!-- Utilization Tab -->
                                        <div class="tab-pane" id="utilization" role="tabpanel">
                                            <div class="row">
                                                <div class="col-lg-6">
                                                    <div class="card">
                                                        <div class="card-body">
                                                            <h4 class="card-title mb-4">Benefit Utilization</h4>
                                                            <div id="utilizationChart" class="utilization-chart"></div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-lg-6">
                                                    <div class="card">
                                                        <div class="card-body">
                                                            <h4 class="card-title mb-4">Utilization Summary</h4>
                                                            <div id="utilizationSummary"></div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Premium History Tab -->
                                        <div class="tab-pane" id="premium" role="tabpanel"></div>

                                        <!-- Anniversary Tab -->
                                        <div class="tab-pane" id="anniversary" role="tabpanel"></div>
                                        
                                        <!-- Documents Tab -->
                                        <div class="tab-pane" id="documents" role="tabpanel">
                                            
                                            <div class="d-flex justify-content-end mb-3">
                                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#uploadDocumentModal">
                                                        <i class="ri-upload-2-line align-middle me-1"></i> Upload Document
                                                    </button>
                                            </div>
                                            <div class="table-responsive">
                                                    <table class="table table-bordered">
                                                        <thead>
                                                            <tr>
                                                                <th>Document Type</th>
                                                                <th>Document Name</th>
                                                                <th>Description</th>
                                                                <th>Uploaded On</th>
                                                                <th>Uploaded By</th>
                                                                <th>Actions</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php
                                                            include 'layouts/dbconn.php';
                                                            // Fetch member documents
                                                            $sql = "SELECT cd.*, u.full_name as uploader 
                                                                    FROM client_documents cd
                                                                    LEFT JOIN users u ON cd.uploaded_by = u.user_id
                                                                    WHERE cd.member_no = ?
                                                                    ORDER BY cd.uploaded_at DESC";
                                                            $stmt = $conn->prepare($sql);
                                                            $stmt->bind_param('s', $member_no);
                                                            $stmt->execute();
                                                            $documents = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
                                        
                                                            foreach ($documents as $doc):
                                                            ?>
                                                            <tr>
                                                                <td><?php echo ucfirst($doc['doc_type']); ?></td>
                                                                <td><?php echo htmlspecialchars($doc['original_name']); ?></td>
                                                                <td><?php echo htmlspecialchars($doc['description']); ?></td>
                                                                <td><?php echo date('d M Y H:i', strtotime($doc['uploaded_at'])); ?></td>
                                                                <td><?php echo htmlspecialchars($doc['uploader']); ?></td>
                                                                <td>
                                                                    <div class="d-flex gap-2">
                                                                        <a href="view_document.php?id=<?php echo $doc['id']; ?>" 
                                                                           class="btn btn-sm btn-info" target="_blank">
                                                                            <i class="ri-eye-line"></i>
                                                                        </a>
                                                                        <a href="download_document.php?id=<?php echo $doc['id']; ?>" 
                                                                           class="btn btn-sm btn-success">
                                                                            <i class="ri-download-2-line"></i>
                                                                        </a>
                                                                        <?php if ($_SESSION['role_id'] == 1): ?>
                                                                        <button type="button" class="btn btn-sm btn-danger"
                                                                                onclick="deleteDocument(<?php echo $doc['id']; ?>)">
                                                                            <i class="ri-delete-bin-line"></i>
                                                                        </button>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Upload Document Modal -->
                <div class="modal fade" id="uploadDocumentModal" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Upload Document</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <form action="save_document.php" method="post" enctype="multipart/form-data">
                                <div class="modal-body">
                                    <input type="hidden" name="member_no" value="<?php echo $member_no; ?>">
                                    <input type="hidden" name="corp_id" value="<?php echo $principal['corp_id']; ?>">
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Document Type</label>
                                        <select name="doc_type" class="form-select" required>
                                            <option value="">Select Type</option>
                                            <option value="identification">Identification</option>
                                            <option value="medical">Medical Records</option>
                                            <option value="claims">Claims Documents</option>
                                            <option value="correspondence">Correspondence</option>
                                            <option value="other">Other</option>
                                        </select>
                                    </div>
                
                                    <div class="mb-3">
                                        <label class="form-label">Description</label>
                                        <textarea name="description" class="form-control" rows="3" required></textarea>
                                    </div>
                
                                    <div class="mb-3">
                                        <label class="form-label">Document</label>
                                        <input type="file" name="document" class="form-control" required>
                                        <small class="text-muted">
                                            Allowed types: PDF, JPG, PNG, DOC. Max size: 5MB
                                        </small>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                                    <button type="submit" class="btn btn-primary">Upload</button>
                                </div>
                            </form>
                        </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="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <script src="assets/js/app.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<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>
        // Initialize components
document.addEventListener('DOMContentLoaded', function() {
    // Initialize select2
    $('.select2').select2();

    // Initialize form handling
    const searchForm = document.getElementById('searchForm');
    const searchResults = document.getElementById('searchResults');
    const memberDetails = document.getElementById('memberDetails');

    // Handle form submission
    searchForm.addEventListener('submit', function(e) {
        e.preventDefault();
        searchMembers();
    });
    
    $(document).ready(function() {
    $("#uploadDocumentModal form").on('submit', function(e) {
        e.preventDefault();
        
        var formData = new FormData(this);
        
        $.ajax({
            url: 'save_document.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function() {
                Swal.fire({
                    title: 'Uploading...',
                    text: 'Please wait while we upload your document',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
            },
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: response.message
                    }).then(() => {
                        $('#uploadDocumentModal').modal('hide');
                        window.location.reload();
                    });
                } else {
                    throw new Error(response.error);
                }
            },
            error: function(xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: error || 'Failed to upload document'
                });
            }
        });
    });
});
    
    function deleteDocument(docId) {
    Swal.fire({
        title: 'Are you sure?',
        text: "This document will be permanently deleted!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'No, cancel!'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('delete_document.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `id=${docId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        title: 'Deleted!',
                        text: 'Document has been deleted.',
                        icon: 'success'
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    throw new Error(data.error);
                }
            })
            .catch(error => {
                Swal.fire({
                    title: 'Error!',
                    text: error.message,
                    icon: 'error'
                });
            });
        }
    });
}
    function searchMembers() {
        const formData = new FormData(searchForm);
        
        fetch('search_members.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error || 'Search failed');
            }
            displaySearchResults(data.members);
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.message
            });
        });
    }

    function displaySearchResults(members) {
        const tbody = searchResults.querySelector('tbody');
        tbody.innerHTML = '';

        members.forEach(member => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${member.member_no}</td>
                <td>${member.surname} ${member.first_name}</td>
                <td>${member.family_no}</td>
                <td>${getRelationshipText(member.relation_to_principal)}</td>
                <td>
                    <span class="badge ${member.status ? 'bg-success' : 'bg-danger'}">
                        ${member.status ? 'Active' : 'Inactive'}
                    </span>
                </td>
                <td>
                    <button type="button" class="btn btn-sm btn-primary" 
                            onclick="viewMemberDetails('${member.member_no}')">
                        View Details
                    </button>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    // Expose viewMemberDetails to window object
    window.viewMemberDetails = function(memberNo) {
        loadMemberDetails(memberNo);
        memberDetails.style.display = 'block';
        memberDetails.scrollIntoView({ behavior: 'smooth' });
    };

    function loadMemberDetails(memberNo) {
        // Load basic member info
        fetch(`get_member_details.php?member_no=${memberNo}`)
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    throw new Error(data.error);
                }
                displayMemberInfo(data.member);
                loadTabData(memberNo);
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
    }

    function displayMemberInfo(member) {
        // Update member name and basic info
        document.querySelector('.member-name').textContent = 
            `${member.surname} ${member.first_name}`;
        
        document.querySelector('.member-basic-info').innerHTML = `
            <p class="mb-1"><strong>Member No:</strong> ${member.member_no}</p>
            <p class="mb-1"><strong>Family No:</strong> ${member.family_no}</p>
            <p class="mb-1"><strong>Corporate:</strong> ${member.corporate}</p>
        `;

        document.querySelector('.member-status').innerHTML = `
            <span class="badge ${member.status ? 'bg-success' : 'bg-danger'} fs-5">
                ${member.status ? 'Active' : 'Inactive'}
            </span>
        `;
    }

    function loadTabData(memberNo) {
        // Load personal details
        loadPersonalDetails(memberNo);
        
        // Load family details
        loadFamilyDetails(memberNo);
        
        // Load benefits
        loadBenefits(memberNo);
        
        // Load claims history
        loadClaimsHistory(memberNo);
        
        // Load utilization
        loadUtilization(memberNo);
        
        // Load premium history
        loadPremiumHistory(memberNo);
        
        // Load anniversary history
        loadAnniversaryHistory(memberNo);
    }

    function loadPersonalDetails(memberNo) {
    fetch(`get_member_personal.php?member_no=${memberNo}`)
        .then(response => response.json())
        .then(data => {
            if (!data.success) throw new Error(data.error);
            
            document.getElementById('personal').innerHTML = `
                <div class="row">
                    <div class="col-md-6">
                        <h5 class="mb-4">Personal Information</h5>
                        <table class="table table-sm">
                            <tr>
                                <th width="150">Full Name:</th>
                                <td>${data.member.surname} ${data.member.first_name} ${data.member.other_names || ''}</td>
                            </tr>
                            <tr>
                                <th>Date of Birth:</th>
                                <td>${data.member.formatted_dob || '-'} (${data.member.age} years)</td>
                            </tr>
                            <tr>
                                <th>Gender:</th>
                                <td>${data.member.gender_text}</td>
                            </tr>
                            <tr>
                                <th>ID Number:</th>
                                <td>${data.member.id_no || '-'}</td>
                            </tr>
                            <tr>
                                <th>Marital Status:</th>
                                <td>${data.member.marital_status_text}</td>
                            </tr>
                            <tr>
                                <th>PIN Number:</th>
                                <td>${data.member.pin_no || '-'}</td>
                            </tr>
                            <tr>
                                <th>Member Since:</th>
                                <td>${formatDate(data.member.date_entered)}</td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h5 class="mb-4">Contact Information</h5>
                        <table class="table table-sm">
                            <tr>
                                <th width="150">Mobile:</th>
                                <td>${data.member.mobile_no || '-'}</td>
                            </tr>
                            <tr>
                                <th>Telephone:</th>
                                <td>${data.member.tel_no || '-'}</td>
                            </tr>
                            <tr>
                                <th>Email:</th>
                                <td>${data.member.email || '-'}</td>
                            </tr>
                            <tr>
                                <th>Postal Address:</th>
                                <td>${data.member.postal_add || '-'}</td>
                            </tr>
                            <tr>
                                <th>Physical Location:</th>
                                <td>${data.member.phy_loc || '-'}</td>
                            </tr>
                            <tr>
                                <th>Bank Branch:</th>
                                <td>${data.member.bank_branch || '-'}</td>
                            </tr>
                            <tr>
                                <th>Account Number:</th>
                                <td>${data.member.account_no || '-'}</td>
                            </tr>
                        </table>
                    </div>
                </div>
            `;
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.message || 'Failed to load personal details'
            });
        });
}

// Helper function to format dates
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('en-GB', {
        day: '2-digit',
        month: 'short',
        year: 'numeric'
    });
}

    function loadFamilyDetails(memberNo) {
        fetch(`get_member_family.php?member_no=${memberNo}`)
            .then(response => response.json())
            .then(data => {
                if (!data.success) throw new Error(data.error);
                
                const familyHtml = `
                    <div class="table-responsive">
                        <table class="table table-centered">
                            <thead>
                                <tr>
                                    <th>Member No</th>
                                    <th>Name</th>
                                    <th>Relationship</th>
                                    <th>Age</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.family.map(member => `
                                    <tr>
                                        <td>${member.member_no}</td>
                                        <td>${member.surname} ${member.first_name}</td>
                                        <td>${getRelationshipText(member.relation_to_principal)}</td>
                                        <td>${calculateAge(member.dob)}</td>
                                        <td>
                                            <span class="badge ${member.status ? 'bg-success' : 'bg-danger'}">
                                                ${member.status ? 'Active' : 'Inactive'}
                                            </span>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
                
                document.getElementById('family').innerHTML = familyHtml;
            })
            .catch(handleError);
    }

    function loadBenefits(memberNo) {
        fetch(`get_member_benefits.php?member_no=${memberNo}`)
            .then(response => response.json())
            .then(data => {
                if (!data.success) throw new Error(data.error);
                
                const benefitsHtml = `
                    <div class="table-responsive">
                        <table class="table table-centered">
                            <thead>
                                <tr>
                                    <th>Benefit</th>
                                    <th>Category</th>
                                    <th class="text-end">Limit</th>
                                    <th>Sharing</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.benefits.map(benefit => `
                                    <tr>
                                        <td>${benefit.benefit_name}</td>
                                        <td>${benefit.category}</td>
                                        <td class="text-end">${formatCurrency(benefit.limit)}</td>
                                        <td>${benefit.sharing ? 'Yes' : 'No'}</td>
                                        <td>
                                            <span class="badge bg-success">${benefit.status}</span>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
                
                document.getElementById('benefits').innerHTML = benefitsHtml;
            })
            .catch(handleError);
    }

    function loadClaimsHistory(memberNo) {
        fetch(`get_member_claims.php?member_no=${memberNo}`)
            .then(response => response.json())
            .then(data => {
                if (!data.success) throw new Error(data.error);
                
                const claimsHtml = `
                    <div class="table-responsive">
                        <table class="table table-centered">
                            <thead>
                                <tr>
                                    <th>Claim No</th>
                                    <th>Provider</th>
                                    <th>Date</th>
                                    <th class="text-end">Amount</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.claims.map(claim => `
                                    <tr>
                                        <td>${claim.claim_no}</td>
                                        <td>${claim.provider_name}</td>
                                        <td>${formatDate(claim.invoice_date)}</td>
                                        <td class="text-end">${formatCurrency(claim.invoiced_amount)}</td>
                                        <td>
                                            <span class="badge ${getClaimStatusClass(claim.vet_status)}">
                                                ${getClaimStatusText(claim.vet_status)}
                                            </span>
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-info"
                                                    onclick="viewClaimDetails('${claim.claim_no}')">
                                                View
                                            </button>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
                
                document.getElementById('claims').innerHTML = claimsHtml;
            })
            .catch(handleError);
    }

    function loadUtilization(memberNo) {
        fetch(`get_member_utilization.php?member_no=${memberNo}`)
            .then(response => response.json())
            .then(data => {
                if (!data.success) throw new Error(data.error);
                
                // Create utilization chart
                const chartOptions = {
                    series: [{
                        name: 'Utilized',
                        data: data.utilization.map(item => item.utilized_amount)
                    }],
                    chart: {
                        type: 'bar',
                        height: 350
                    },
                    plotOptions: {
                        bar: {
                            horizontal: false,
                            columnWidth: '55%',
                            endingShape: 'rounded'
                        },
                    },
                    dataLabels: {
                        enabled: false
                    },
                    xaxis: {
                        categories: data.utilization.map(item => item.benefit_name),
                    },
                    yaxis: {
                        title: {
                            text: 'Amount (KES)'
                        }
                    },
                    fill: {
                        opacity: 1
                    },
                    tooltip: {
                        y: {
                            formatter: function(val) {
                                return formatCurrency(val)
                            }
                        }
                    }
                };

                const chart = new ApexCharts(
                    document.querySelector("#utilizationChart"), 
                    chartOptions
                );
                chart.render();

                // Update utilization summary
                const summaryHtml = `
                    <div class="table-responsive">
                        <table class="table table-centered">
                            <thead>
                                <tr>
                                    <th>Benefit</th>
                                    <th class="text-end">Limit</th>
                                    <th class="text-end">Utilized</th>
                                    <th class="text-end">Available</th>
                                    <th>% Used</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.utilization.map(item => `
                                    <tr>
                                        <td>${item.benefit_name}</td>
                                        <td class="text-end">${formatCurrency(item.limit)}</td>
                                        <td class="text-end">${formatCurrency(item.utilized_amount)}</td>
                                        <td class="text-end">${formatCurrency(item.available_amount)}</td>
                                        <td>
                                            <div class="progress">
                                                <div class="progress-bar" role="progressbar" 
                                                     style="width: ${item.utilized_percentage}%"
                                                     aria-valuenow="${item.utilized_percentage}" 
                                                     aria-valuemin="0" aria-valuemax="100">
                                                    ${item.utilized_percentage}%
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;

                document.getElementById('utilizationSummary').innerHTML = summaryHtml;
            })
            .catch(handleError);
    }

    function loadPremiumHistory(memberNo) {
        fetch(`get_member_premium.php?member_no=${memberNo}`)
            .then(response => response.json())
            .then(data => {
                if (!data.success) throw new Error(data.error);
                
                const premiumHtml = `
                    <div class="table-responsive">
                        <table class="table table-centered">
                            <thead>
                                <tr>
                                    <th>Debit No</th>
                                    <th>Date</th>
                                    <th class="text-end">Amount</th>
                                    <th class="text-end">Allocated</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.premiums.map(premium => `
                                    <tr>
                                        <td>${premium.debit_no}</td>
                                        <td>${formatDate(premium.debit_date)}</td>
                                        <td class="text-end">${formatCurrency(premium.amount)}</td>
                                        <td class="text-end">${formatCurrency(premium.allocated_amount)}</td>
                                        <td>
                                            <span class="badge ${premium.status === 'ALLOCATED' ? 'bg-success' : 'bg-warning'}">
                                                ${premium.status}
                                            </span>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
                
                document.getElementById('premium').innerHTML = premiumHtml;
            })
            .catch(handleError);
    }

    function loadAnniversaryHistory(memberNo) {
        fetch(`get_member_anniversary.php?member_no=${memberNo}`)
            .then(response => response.json())
            .then(data => {
                if (!data.success) throw new Error(data.error);
                
                const anniversaryHtml = `
                    <div class="table-responsive">
                        <table class="table table-centered">
                            <thead>
                                <tr>
                                    <th>Anniversary</th>
                                    <th>Start Date</th>
                                    <th>End Date</th>
                                    <th>Renewal Date</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.anniversaries.map(anniv => `
                                    <tr>
                                        <td>${anniv.anniv}</td>
                                        <td>${formatDate(anniv.start_date)}</td>
                                        <td>${formatDate(anniv.end_date)}</td>
                                        <td>${formatDate(anniv.renewal_date)}</td>
                                        <td>
                                            <span class="badge ${isDateActive(anniv.start_date, anniv.end_date) ? 'bg-success' : 'bg-secondary'}">
                                                ${isDateActive(anniv.start_date, anniv.end_date) ? 'Active' : 'Expired'}
                                            </span>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
                
                document.getElementById('anniversary').innerHTML = anniversaryHtml;
            })
            .catch(handleError);
    }

    // Utility functions
    function formatDate(dateStr) {
        return new Date(dateStr).toLocaleDateString('en-GB');
    }

    function formatCurrency(amount) {
        return new Intl.NumberFormat('en-KE', {
            style: 'currency',
            currency: 'KES'
        }).format(amount);
    }

    function calculateAge(dob) {
        const today = new Date();
        const birthDate = new Date(dob);
        let age = today.getFullYear() - birthDate.getFullYear();
        const m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        return age;
    }

    function getRelationshipText(relation) {
        const relationships = {
            1: 'Principal',
            2: 'Spouse',
            3: 'Child',
            4: 'Parent'
        };
        return relationships[relation] || 'Unknown';
    }

    function getClaimStatusClass(status) {
        const classes = {
            0: 'bg-warning',   // Pending
            1: 'bg-success',   // Approved
            2: 'bg-danger',    // Rejected
            3: 'bg-info'       // In Progress
        };
        return classes[status] || 'bg-secondary';
    }

    function getClaimStatusText(status) {
        const statuses = {
            0: 'Pending',
            1: 'Approved',
            2: 'Rejected', 
            3: 'In Progress'
        };
        return statuses[status] || 'Unknown';
    }

    function isDateActive(startDate, endDate) {
        const today = new Date();
        return today >= new Date(startDate) && today <= new Date(endDate);
    }

    function handleError(error) {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: error.message || 'An error occurred'
        });
    }

    // Expose necessary functions to window object
    window.viewClaimDetails = function(claimNo) {
        window.location.href = `view_claim.php?claim_no=${claimNo}`;
    };
});
    </script>
</body>
</html>