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

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

// Query to fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
}

// Fetch corporate data
$query = "SELECT corp_id, corporate, scheme FROM corporate";
$result = $conn->query($query);
$corporate = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $corporate[] = $row;
    }
}

// Fetch principal members
$principal_query = "SELECT m.member_no, m.family_no, m.surname, m.first_name, m.other_names, c.corporate
                   FROM member_info m
                   JOIN corporate c ON m.corp_id = c.corp_id
                   WHERE m.relation_to_principal = 1";
$principal_result = $conn->query($principal_query);
$principals = [];
if ($principal_result->num_rows > 0) {
    while ($row = $principal_result->fetch_assoc()) {
        $principals[] = $row;
    }
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Dependent')); ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.css">
    <?php include 'layouts/head-css.php'; ?>
</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' => 'Member Management', 'title' => 'Add Dependent')); ?>

                    <div class="row">
                        <div class="col-xxl-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Add Dependent to Principal Member</h4>
                                </div>

                                <div class="card-body">
                                    <form id="addDependentForm" method="POST" action="save_dependent.php">
                                        <div class="row mb-4">
                                            <div class="col-md-6">
                                                <label for="principalSelect" class="form-label">Select Principal Member</label>
                                                <select class="js-example-basic-single" name="principal_id" id="principalSelect" required>
                                                    <option value="">Select Principal Member</option>
                                                    <?php foreach ($principals as $principal): ?>
                                                        <option value="<?php echo $principal['member_no']; ?>"
                                                                data-family="<?php echo $principal['family_no']; ?>"
                                                                data-corporate="<?php echo $principal['corporate']; ?>">
                                                            <?php echo $principal['surname'] . ', ' . $principal['first_name'] . ' (' . $principal['member_no'] . ')'; ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Selected Member Details</label>
                                                <div id="selectedMemberDetails" class="alert alert-info">
                                                    Please select a principal member
                                                </div>
                                            </div>
                                        </div>

                                        <div id="dependentForm" style="display: none;">
                                            <!-- Dependent form fields will be dynamically added here -->
                                        </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="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>

    <script>
        $(document).ready(function() {
            $('.js-example-basic-single').select2();

            $('#principalSelect').change(function() {
                const selectedOption = $(this).find(':selected');
                const memberNo = $(this).val();
                const familyNo = selectedOption.data('family');
                const corporate = selectedOption.data('corporate');

                if (memberNo) {
                    $('#selectedMemberDetails').html(`
                        <strong>Member Number:</strong> ${memberNo}<br>
                        <strong>Family Number:</strong> ${familyNo}<br>
                        <strong>Corporate:</strong> ${corporate}
                    `);

                    loadDependentForm(memberNo, familyNo);
                } else {
                    $('#selectedMemberDetails').html('Please select a principal member');
                    $('#dependentForm').hide();
                }
            });

            function loadDependentForm(principalMemberNo, familyNo) {
                const dependentForm = `
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Surname</label>
                            <input type="text" class="form-control" name="surname" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">First Name</label>
                            <input type="text" class="form-control" name="first_name" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Other Names</label>
                            <input type="text" class="form-control" name="other_names">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Date of Birth</label>
                            <input type="date" class="form-control" name="dob" required>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Gender</label>
                            <select class="form-select" name="gender" required>
                                <option value="">Select Gender</option>
                                <option value="1">Male</option>
                                <option value="2">Female</option>
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Relationship</label>
                            <select class="form-select" name="relation_to_principal" required>
                                <option value="">Select Relation</option>
                                <option value="2">Spouse</option>
                                <option value="3">Child</option>
                                <option value="4">Parent</option>
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">ID Number</label>
                            <input type="text" class="form-control" name="id_no">
                        </div>

                        <input type="hidden" name="principal_member_no" value="${principalMemberNo}">
                        <input type="hidden" name="family_no" value="${familyNo}">

                        <div class="col-12 mt-3">
                            <button type="submit" class="btn btn-success">
                                <i class="ri-check-double-line align-middle me-2"></i>
                                Save Dependent
                            </button>
                        </div>
                    </div>
                `;

                $('#dependentForm').html(dependentForm).show();
            }

            $('#addDependentForm').on('submit', function(e) {
                e.preventDefault();

                const formData = new FormData(this);

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

                $.ajax({
                    url: 'save_dependent.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        const data = JSON.parse(response);
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Success!',
                                text: 'Dependent added successfully',
                                confirmButtonText: 'OK'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    window.location.href = 'all_members.php';
                                }
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error!',
                                text: data.message || 'Error adding dependent',
                                confirmButtonText: 'OK'
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error!',
                            text: 'An error occurred while saving the dependent',
                            confirmButtonText: 'OK'
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>
