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

<?php if (isset($_SESSION['success_message'])): ?>
    <script>
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: '<?php echo $_SESSION['success_message']; ?>'
        });
    </script>
    <?php unset($_SESSION['success_message']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['error_message'])): ?>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: '<?php echo $_SESSION['error_message']; ?>'
        });
    </script>
    <?php unset($_SESSION['error_message']); ?>
<?php endif; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Members')); ?>
    <!-- Sweet Alert css-->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Member Management', 'title' => 'Members')); ?>
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex align-items-center flex-wrap gap-2">
                                        <div class="flex-grow-1">
                                            <a href="add_new_member.php" class="btn btn-primary add-btn">
                                                <i class="ri-add-line align-bottom me-1"></i> Add Members
                                            </a>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="hstack text-nowrap gap-2">
                                                <button class="btn btn-soft-danger" id="remove-actions" onClick="deleteMultiple()"><i class="ri-delete-bin-2-line"></i></button>
                                                <button class="btn btn-primary"><i class="ri-filter-2-line me-1 align-bottom"></i> Filters</button>
                                                <button class="btn btn-soft-info">Import</button>
                                                <button type="button" id="dropdownMenuLink1" data-bs-toggle="dropdown" aria-expanded="false" class="btn btn-soft-primary"><i class="ri-more-2-fill"></i></button>
                                                <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink1">
                                                    <li><a class="dropdown-item" href="#">All</a></li>
                                                    <li><a class="dropdown-item" href="#">Last Week</a></li>
                                                    <li><a class="dropdown-item" href="#">Last Month</a></li>
                                                    <li><a class="dropdown-item" href="#">Last Year</a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!--end col-->
                        <div class="col-xxl-9">
                            <div class="card" id="contactList">
                                <div class="card-header">
                                    <div class="row g-3">
                                        <div class="col-md-4">
                                            <div class="search-box">
                                                <input type="text" class="form-control search" placeholder="Search for contact...">
                                                <i class="ri-search-line search-icon"></i>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <select class="form-control" id="corporate-filter">
                                                    <option value="">All Corporates</option>
                                                    <?php
                                                    $corp_sql = "SELECT corp_id, corporate FROM corporate ORDER BY corporate";
                                                    $corp_result = $conn->query($corp_sql);
                                                    while ($corp = $corp_result->fetch_assoc()) {
                                                        echo "<option value='" . $corp['corp_id'] . "'>" . htmlspecialchars($corp['corporate']) . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-auto ms-auto">
                                            <div class="d-flex align-items-center gap-2">
                                                <span class="text-muted">Sort by: </span>
                                                <select class="form-control mb-0" data-choices data-choices-search-false id="choices-single-default">
                                                    <option value="Name">Name</option>
                                                    <option value="Company">Company</option>
                                                    <option value="Lead">Lead</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div>
                                        <div class="table-responsive table-card mb-3">
                                            <table class="table align-middle table-nowrap mb-0" id="customerTable">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th scope="col" style="width: 50px;">
                                                            <div class="form-check">
                                                                <input class="form-check-input" type="checkbox" id="checkAll" value="option">
                                                            </div>
                                                        </th>
                                                        <th class="sort" data-sort="name" scope="col">Name</th>
                                                        <th class="sort" data-sort="corporate" scope="col">Corporate</th>
                                                        <th class="sort" data-sort="member_no" scope="col">Member No</th>
                                                        <th class="sort" data-sort="categories" scope="col">Category</th>
                                                        <th class="sort" data-sort="gender" scope="col">Gender</th>
                                                        <th class="sort" data-sort="status" scope="col">Status</th>
                                                        <th scope="col">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody class="list form-check-all">
                                                <?php
                                                $sql = "
                                                    SELECT 
                                                        mi.*,
                                                        mb.category
                                                    FROM 
                                                        member_info mi
                                                    LEFT JOIN 
                                                        member_benefits mb ON mi.member_no = mb.member_no
                                                    GROUP BY 
                                                        mi.member_no
                                                ";
                                                $result = $conn->query($sql);
                                            
                                                if ($result->num_rows > 0) {
                                                    while ($row = $result->fetch_assoc()) {
                                                        $corp_sql = "SELECT corporate FROM corporate WHERE corp_id = ?";
                                                        $corp_stmt = $conn->prepare($corp_sql);
                                                        $corp_stmt->bind_param("s", $row['corp_id']);
                                                        $corp_stmt->execute();
                                                        $corp_result = $corp_stmt->get_result();
                                                        $corporate_name = ($corp_row = $corp_result->fetch_assoc()) ? $corp_row['corporate'] : 'N/A';
                                            
                                                        echo '<tr data-member-no="' . $row['member_no'] . '" class="member-row">';
                                                        echo '<th scope="row">';
                                                        echo '<div class="form-check">';
                                                        echo '<input class="form-check-input" type="checkbox" name="chk_child" value="option1">';
                                                        echo '</div>';
                                                        echo '</th>';
                                                        echo '<td class="name">';
                                                        echo '<div class="d-flex align-items-center">';
                                                        echo '<div class="flex-grow-1 ms-2 name">' . $row['first_name'] . ' ' . $row['surname'] . '</div>';
                                                        echo '</div>';
                                                        echo '</td>';
                                                        echo '<td class="member_no" style="display:none;">' . $row['member_no'] . '</td>';
                                                        echo '<td class="corporate">' . htmlspecialchars($corporate_name) . '</td>';
                                                        echo '<td class="member_no">' . $row['member_no'] . '</td>';
                                                        echo '<td class="categories">' . htmlspecialchars($row['category'] ?? 'N/A') . '</td>';
                                                        echo '<td class="gender">' . ($row['gender'] == 1 ? 'Male' : 'Female') . '</td>';
                                                        echo '<td class="status">' . ($row['status'] == 1 ? 'Active' : 'Inactive') . '</td>';
                                                        echo '<td>';
                                                        echo '<ul class="list-inline hstack gap-2 mb-0">';
                                                        echo '<li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="View Member">';
                                                        echo '<a href="view_member.php?member_no=' . $row['member_no'] . '" class="text-primary d-inline-block">';
                                                        echo '<i class="ri-eye-fill fs-16"></i>';
                                                        echo '</a>';
                                                        echo '</li>';
                                                        echo '<li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Edit Member">';
                                                        echo '<a href="edit_member.php?member_no=' . $row['member_no'] . '" class="text-primary d-inline-block">';
                                                        echo '<i class="ri-pencil-line fs-16"></i>';
                                                        echo '</a>';
                                                        echo '</li>';
                                                        echo '<li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" 
                                                            title="' . ($row['status'] == 1 ? 'Suspend' : 'Reinstate') . ' Member">';
                                                        echo '<a href="javascript:void(0);" onclick="updateMemberStatus(\'' . $row['member_no'] . '\', \'' . ($row['status'] == 1 ? '0' : '1') . '\')" 
                                                            class="text-' . ($row['status'] == 1 ? 'danger' : 'success') . ' d-inline-block">';
                                                        echo '<i class="ri-' . ($row['status'] == 1 ? 'close' : 'check') . '-circle-line fs-16"></i>';
                                                        echo '</a>';
                                                        echo '</li>';
                                                        echo '</ul>';
                                                        echo '</td>';
                                                        echo '</tr>';
                                                    }
                                                } else {
                                                    echo '<tr><td colspan="9">No members found</td></tr>';
                                                }
                                                ?>
                                            </tbody>
                                            </table>
                                            <div class="noresult" style="display: none">
                                                <div class="text-center">
                                                    <lord-icon src="https://cdn.lordicon.com/msoeawqm.json" trigger="loop" colors="primary:#121331,secondary:#08a88a" style="width:75px;height:75px"></lord-icon>
                                                    <h5 class="mt-2">Sorry! No Result Found</h5>
                                                    <p class="text-muted mb-0">We've searched more than 150+ contacts We did not find any contacts for you search.</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="d-flex justify-content-end mt-3">
                                            <div class="pagination-wrap hstack gap-2">
                                                <a class="page-item pagination-prev disabled" href="#">
                                                    Previous
                                                </a>
                                                <ul class="pagination listjs-pagination mb-0"></ul>
                                                <a class="page-item pagination-next" href="#">
                                                    Next
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!--end card-->
                        </div>
                        <!--end col-->
                        <div class="col-xxl-3">
                            <div class="card" id="contact-view-detail">
                                <div class="card-body text-center">
                                    <h5 class="mt-4 mb-1" id="member-name"></h5>
                                    <p class="text-muted" id="member-corporate"></p>
                                    <ul class="list-inline mb-0">
                                        <li class="list-inline-item avatar-xs">
                                            <a href="javascript:void(0);" class="avatar-title bg-success-subtle text-success fs-15 rounded">
                                                <i class="ri-phone-line"></i>
                                            </a>
                                        </li>
                                        <li class="list-inline-item avatar-xs">
                                            <a href="javascript:void(0);" class="avatar-title bg-danger-subtle text-danger fs-15 rounded">
                                                <i class="ri-mail-line"></i>
                                            </a>
                                        </li>
                                        <li class="list-inline-item avatar-xs">
                                            <a href="javascript:void(0);" class="avatar-title bg-warning-subtle text-warning fs-15 rounded">
                                                <i class="ri-question-answer-line"></i>
                                            </a>
                                        </li>
                                    </ul>
                                </div>
                                <div class="card-body">
                                    <h6 class="text-muted text-uppercase fw-semibold mb-3">Personal Information</h6>
                                    <div class="table-responsive table-card">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <td class="fw-semibold" scope="row">Member Number</td>
                                                    <td id="member-number"></td>
                                                </tr>
                                                <tr>
                                                    <td class="fw-semibold" scope="row">DOB</td>
                                                    <td id="member-dob"></td>
                                                </tr>
                                                <tr>
                                                    <td class="fw-semibold" scope="row">Gender</td>
                                                    <td id="member-gender"></td>
                                                </tr>
                                                <tr>
                                                    <td class="fw-semibold" scope="row">Date Entered</td>
                                                    <td id="member-date-entered"></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <!--end card-->
                        </div>
                        <!--end col-->
                    </div>
                    <!--end row-->
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->
            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->
    <?php include 'layouts/vendor-scripts.php'; ?>
    <!-- list.js min js -->
    <script src="assets/libs/list.js/list.min.js"></script>
    <script src="assets/libs/list.pagination.js/list.pagination.min.js"></script>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.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>
document.addEventListener('DOMContentLoaded', function() {
    const table = document.getElementById('customerTable');
    if (table) {
        table.addEventListener('click', function(e) {
            // Check if the click is on any action button (view, edit, or status)
            const actionButton = e.target.closest('a[href^="view_member.php"], a[href^="edit_member.php"], a[onclick]');
            if (actionButton) {
                return; // Don't fetch member details if clicking on action buttons
            }
            
            // Check if clicking on any list-inline item (the action buttons container)
            const actionContainer = e.target.closest('.list-inline-item, .list-inline');
            if (actionContainer) {
                return; // Don't fetch member details if clicking in the actions area
            }
            
            const row = e.target.closest('tr');
            if (row && row.getAttribute('data-member-no')) {
                // Remove active class from all rows
                table.querySelectorAll('tr').forEach(r => r.classList.remove('table-active'));
                // Add active class to clicked row
                row.classList.add('table-active');
                
                const memberNo = row.getAttribute('data-member-no');
                console.log('Fetching details for member:', memberNo);
                fetchMemberDetails(memberNo);
            }
        });
    }
});

function fetchMemberDetails(memberNo) {
    console.log('Making fetch request for member:', memberNo);
    fetch('fetch_member_details.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'member_no=' + encodeURIComponent(memberNo)
    })
    .then(response => {
        console.log('Response status:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Received data:', data);
        if (data.error) {
            console.error('Server error:', data.error);
            return;
        }
        updateMemberCard(data);
    })
    .catch(error => {
        console.error('Fetch error:', error);
        // Don't show error popup for fetch failures during navigation
        // The error usually happens when user navigates away quickly
    });
}

function updateMemberCard(member) {
    try {
        document.getElementById('member-name').textContent = `${member.first_name} ${member.surname}`;
        document.getElementById('member-corporate').textContent = member.corporate_name || 'N/A';
        document.getElementById('member-number').textContent = member.member_no || 'N/A';
        document.getElementById('member-dob').textContent = member.dob ? new Date(member.dob).toLocaleDateString() : 'N/A';
        document.getElementById('member-gender').textContent = member.gender === '1' ? 'Male' : 'Female';
        document.getElementById('member-date-entered').textContent = member.date_entered ? new Date(member.date_entered).toLocaleDateString() : 'N/A';
        
        const card = document.getElementById('contact-view-detail');
        if (card) {
            card.style.display = 'block';
        }
    } catch (error) {
        console.error('Error updating card:', error);
        console.error('Member data:', member);
    }
}

function updateMemberStatus(memberNo, newStatus) {
    const actionText = newStatus === '1' ? 'reinstate' : 'suspend';
    Swal.fire({
        title: 'Are you sure?',
        text: `Do you want to ${actionText} this member?`,
        icon: 'warning',
        input: 'text',
        inputLabel: 'Please provide a reason for this action',
        inputPlaceholder: 'Enter reason...',
        showCancelButton: true,
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        inputValidator: (value) => {
            if (!value) {
                return 'You need to provide a reason!';
            }
        }
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'update_member_status.php',
                type: 'POST',
                data: {
                    member_no: memberNo,
                    status: newStatus,
                    reason: result.value
                },
                success: function(response) {
                    try {
                        const data = JSON.parse(response);
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Success!',
                                text: data.message
                            }).then(() => {
                                window.location.reload();
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error!',
                                text: data.message
                            });
                        }
                    } catch (e) {
                        console.error('JSON parse error:', e);
                        Swal.fire({
                            icon: 'error',
                            title: 'Error!',
                            text: 'Invalid response from server'
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: 'Failed to update member status'
                    });
                }
            });
        }
    });
}

$(document).ready(function() {
    $('#corporate-filter').change(function() {
        const corpId = $(this).val();
        const selectedText = $('#corporate-filter option:selected').text().trim();
        
        $('.member-row').each(function() {
            const row = $(this);
            const corporateText = row.find('.corporate').text().trim();
            
            if (!corpId || corporateText === selectedText) {
                row.show();
            } else {
                row.hide();
            }
        });
    });
});
</script>
    <style>
        .member-row {
            cursor: pointer;
        }
        .member-row:hover {
            background-color: rgba(0,0,0,0.02);
        }
        .table-active {
            background-color: rgba(0,0,0,0.05) !important;
        }
    </style>
</body>
</html>