<?= $this->extend('layout/main_layout') ?>

<?= $this->section('content') ?>

<!-- Flash Messages -->
<?php if (session()->getFlashdata('success')): ?>
    <div class="alert alert-success">
        <?= session()->getFlashdata('success') ?>
    </div>
<?php endif; ?>

<?php if (session()->getFlashdata('error')): ?>
    <div class="alert alert-danger">
        <?= session()->getFlashdata('error') ?>
    </div>
<?php endif; ?>

<div class="container mt-5">
    <!-- Button to toggle the display of previously saved parent information -->
    <button class="btn btn-primary mb-4" type="button" data-bs-toggle="collapse" data-bs-target="#savedInfo"
        aria-expanded="false" aria-controls="savedInfo" id="viewSecondParentBtn">
        View Parent/AuthorizedUser Information
    </button>
    <!-- Collapsible section for the previously saved parent information -->
    <div class="collapse" id="savedInfo">
        <div class="card card-body">
            <h4>Parent/Authorized User Information</h4>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Email</th>
                        <th>Relation</th>
                        <th>Phone</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody id="parentTable">
                    <!-- Rows will be dynamically populated here -->
                </tbody>
            </table>
        </div>
    </div>
    <form action="<?= base_url('/parent/saveSecondParent') ?>" method="post" id="parentForm">
        <?= csrf_field() ?>

        <!-- First Name -->
        <div class="row mb-3">
            <div class="col-md-6">
                <label for="secondParentFirstName" class="form-label fw-bold">First Name <span
                        style="color: red;">*</span></label>
                <input type="text" class="form-control" id="secondParentFirstName" name="secondParentFirstName"
                    placeholder="First Name" value="<?= old('secondParentFirstName') ?>" pattern="[A-Za-z\s]+"
                    title="Letters only" required>
            </div>
        </div>

        <!-- Last Name -->
        <div class="row mb-3">
            <div class="col-md-6">
                <label for="secondParentLastName" class="form-label fw-bold">Last Name <span
                        style="color: red;">*</span></label>
                <input type="text" class="form-control" id="secondParentLastName" name="secondParentLastName"
                    placeholder="Last Name" value="<?= old('secondParentLastName') ?>" pattern="[A-Za-z\s]+"
                    title="Letters only" required>
            </div>
        </div>

        <!-- Email -->
        <div class="row mb-3">
            <div class="col-md-6">
                <label for="secondParentEmail" class="form-label fw-bold">Email Address <span
                        style="color: red;">*</span></label>
                <input type="email" class="form-control" id="secondParentEmail" name="secondParentEmail"
                    placeholder="Email Address" value="<?= old('secondParentEmail') ?>" required>
                <small id="emailError" class="text-danger"></small>
            </div>
        </div>
        <div class="row mb-3">
            <div class="col-md-6">
                <label for="relationToStudent" class="form-label fw-bold">Relation To Student <span
                        style="color: red;">*</span></label>
                <select id="relationToStudent" name="relationToStudent" class="form-select" required>
                    <option value="" disabled <?= old('relationToStudent') === null ? 'selected' : '' ?>>Select
                        Relation</option>
                    <option value="Husband" <?= old('relationToStudent') === 'Husband' ? 'selected' : '' ?>>Father
                    </option>
                    <option value="Wife" <?= old('relationToStudent') === 'Wife' ? 'selected' : '' ?>>Mother
                    </option>
                    <option value="Brother" <?= old('relationToStudent') === 'Brother' ? 'selected' : '' ?>>Brother
                    </option>
                    <option value="Sister" <?= old('relationToStudent') === 'Sister' ? 'selected' : '' ?>>Sister
                    </option>
                </select>
            </div>
        </div>

        <!-- Phone Number with Pattern Validation -->
        <div class="row mb-3">
            <div class="col-md-6">
                <label for="secondParentCellPhone" class="form-label fw-bold">Phone Number <span
                        style="color: red;">*</span></label>
                <input type="text" class="form-control" id="secondParentCellPhone" name="secondParentCellPhone"
                    placeholder="Phone Number (xxx)-xxx-xxxx" value="<?= old('secondParentCellPhone') ?>" required>
                <small class="text-muted">Format: (xxx)-xxx-xxxx</small>
            </div>
        </div>


        <!-- Submit Button -->
        <div class="row">
            <div class="col-md-6 d-flex justify-content-end">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
    </form>
</div>

<br>
<!-- JavaScript for Phone and Email Validation -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const phoneInput = document.getElementById('secondParentCellPhone');
        const emailInput = document.getElementById('secondParentEmail');
        const firstNameInput = document.getElementById('secondParentFirstName');
        const lastNameInput = document.getElementById('secondParentLastName');
        const emailError = document.getElementById('emailError');
        const nameError = document.createElement('small');
        nameError.classList.add('text-danger');
        const lastNameError = document.createElement('small');
        lastNameError.classList.add('text-danger');

        // Comprehensive domain extension list for validation
        const validExtensions = [
            'com', 'net', 'edu', 'org', 'gov', 'mil', 'int',
            'biz', 'info', 'name', 'pro', 'aero', 'coop', 'museum',
            'io', 'tech', 'ai', 'app', 'dev', 'xyz', 'store',
            'us', 'uk', 'ca', 'au', 'de', 'fr', 'it', 'es', 'nl', 'se',
            'co', 'tv', 'me', 'cc', 'ly', 'in', 'jp', 'cn', 'br', 'ru'
        ];

        // Real-time validation for first and last names (no numbers allowed)
        const namePattern = /^[a-zA-Z\s]+$/;

        function validateName(input, errorElement, fieldName) {
            if (!namePattern.test(input.value)) {
                errorElement.textContent = `Please enter a valid ${fieldName} without numbers.`;
                input.insertAdjacentElement('afterend', errorElement);
            } else {
                errorElement.textContent = '';
            }
        }

        firstNameInput.addEventListener('input', function() {
            validateName(firstNameInput, nameError, 'first name');
        });

        lastNameInput.addEventListener('input', function() {
            validateName(lastNameInput, lastNameError, 'last name');
        });

        // Phone number input formatting
        phoneInput.addEventListener('input', function(e) {
            let input = phoneInput.value.replace(/\D/g, ''); // Remove non-digit characters

            if (input.length > 3 && input.length <= 6) {
                input = `(${input.substring(0, 3)})-${input.substring(3)}`;
            } else if (input.length > 6) {
                input = `(${input.substring(0, 3)})-${input.substring(3, 6)}-${input.substring(6, 10)}`;
            } else if (input.length > 0) {
                input = `(${input}`;
            }

            phoneInput.value = input;
        });

        // Email validation
        emailInput.addEventListener('input', function() {
            const emailValue = emailInput.value;
            const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            const domainExtension = emailValue.split('.').pop(); // Get the domain extension

            if (emailValue && !emailPattern.test(emailValue)) {
                emailError.textContent = 'Please enter a valid email address.';
            } else if (domainExtension && !validExtensions.includes(domainExtension)) {
                emailError.textContent =
                    'Please enter an email with a valid domain extension (e.g., .com, .net, .edu).';
            } else {
                emailError.textContent = ''; // Clear error message if email is valid
            }
        });

        // Form submission validation
        document.getElementById('parentForm').addEventListener('submit', function(e) {
            const phoneValue = phoneInput.value;
            const emailValue = emailInput.value;
            const domainExtension = emailValue.split('.').pop();
            const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            const phonePattern = /^\(\d{3}\)-\d{3}-\d{4}$/;

            // Ensure no numbers in the first or last name
            if (!namePattern.test(firstNameInput.value)) {
                e.preventDefault();
                alert('Please enter a valid first name without numbers.');
            }

            if (!namePattern.test(lastNameInput.value)) {
                e.preventDefault();
                alert('Please enter a valid last name without numbers.');
            }

            if (!phonePattern.test(phoneValue)) {
                e.preventDefault();
                alert('Please enter a valid phone number in the format (xxx)-xxx-xxxx.');
            }

            if (!emailPattern.test(emailValue)) {
                e.preventDefault();
                alert('Please enter a valid email address.');
            } else if (!validExtensions.includes(domainExtension)) {
                e.preventDefault();
                alert('Please enter an email with a valid domain extension (e.g., .com, .net, .edu).');
            }
        });
    });
</script>
<script>
    document.getElementById('viewSecondParentBtn').addEventListener('click', function() {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', '<?= base_url('/parent/viewSecondParent') ?>', true);

        xhr.onload = function() {
            console.log('Response:', xhr.responseText); // Debugging: Log the raw response

            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);

                    if (response.error) {
                        alert(response.error); // Handle error messages
                        return;
                    }

                    const savedParent = response.savedParent;

                    // Clear existing rows in the table
                    const parentTable = document.getElementById('parentTable');
                    parentTable.innerHTML = ''; // Clear previous data

                    // Populate the table with each entry in savedParent
                    savedParent.forEach(parent => {
                        const row = `
                        <tr>
                            <td>${parent.firstName}</td>
                            <td>${parent.lastName}</t>
                            <td>${parent.email}</td>
                            <td>${parent.relation}</td>
                            <td>${parent.phone}</td>
                            <td>${parent.status || 'N/A'}</td> <!-- Status for authorized users -->
                        </tr>
                    `;
                        parentTable.innerHTML += row;
                    });
                } catch (error) {
                    console.error('Error parsing JSON response:', error);
                }
            } else {
                console.error('Failed to load parent and authorized user information. Status:', xhr.status);
            }
        };

        xhr.onerror = function() {
            console.error('An error occurred while fetching parent and authorized user information.');
        };

        xhr.send();
    });
</script>

<?= $this->endSection() ?>
