<?php
require_once 'config/database.php';
requireAdmin();

require_once 'templates/header.php';
require_once 'templates/navbar.php';
require_once 'templates/sidebar.php';
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Member Registration</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item"><a href="members.php">Members</a></li>
                        <li class="breadcrumb-item active">Registration</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">New Member Registration</h3>
                        </div>
                        
                        <!-- Success/Error Messages -->
                        <div id="alertContainer" style="display: none;">
                            <div id="successAlert" class="alert alert-success alert-dismissible" style="display: none;">
                                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                                <h4><i class="icon fa fa-check"></i> Success!</h4>
                                <span id="successMessage"></span>
                            </div>
                            <div id="errorAlert" class="alert alert-danger alert-dismissible" style="display: none;">
                                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                                <h4><i class="icon fa fa-ban"></i> Error!</h4>
                                <span id="errorMessage"></span>
                            </div>
                        </div>
                        
                        <form id="memberRegistrationForm" enctype="multipart/form-data">
                            <div class="card-body">
                                <div class="row">
                                    <!-- Personal Information -->
                                    <div class="col-md-6">
                                        <h4 class="text-primary">
                                            <i class="fas fa-user"></i> Personal Information
                                        </h4>
                                        <div class="form-group">
                                            <label>First Name *</label>
                                            <input type="text" class="form-control" name="first_name" required>
                                        </div>
                                        <div class="form-group">
                                            <label>Last Name *</label>
                                            <input type="text" class="form-control" name="last_name" required>
                                        </div>
                                        <div class="form-group">
                                            <label>Nickname</label>
                                            <input type="text" class="form-control" name="nickname">
                                        </div>
                                        <div class="form-group">
                                            <label>Date of Birth</label>
                                            <input type="date" class="form-control" name="date_of_birth">
                                        </div>
                                        <div class="form-group">
                                            <label>Gender</label>
                                            <select class="form-control" name="gender">
                                                <option value="">Select Gender</option>
                                                <option value="Male">Male</option>
                                                <option value="Female">Female</option>
                                                <option value="Other">Other</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Blood Group</label>
                                            <select class="form-control" name="blood_group">
                                                <option value="">Select Blood Group</option>
                                                <option value="A+">A+</option>
                                                <option value="A-">A-</option>
                                                <option value="B+">B+</option>
                                                <option value="B-">B-</option>
                                                <option value="AB+">AB+</option>
                                                <option value="AB-">AB-</option>
                                                <option value="O+">O+</option>
                                                <option value="O-">O-</option>
                                            </select>
                                        </div>
                                    </div>

                                    <!-- Contact Information -->
                                    <div class="col-md-6">
                                        <h4 class="text-success">
                                            <i class="fas fa-address-book"></i> Contact Information
                                        </h4>
                                        <div class="form-group">
                                            <label>Phone Number *</label>
                                            <input type="tel" class="form-control" name="phone" required>
                                        </div>
                                        <div class="form-group">
                                            <label>Email Address *</label>
                                            <input type="email" class="form-control" name="email" required>
                                        </div>
                                        <div class="form-group">
                                            <label>Address</label>
                                            <textarea class="form-control" name="address" rows="3"></textarea>
                                        </div>
                                        <div class="form-group">
                                            <label>Emergency Contact Name</label>
                                            <input type="text" class="form-control" name="emergency_contact_name">
                                        </div>
                                        <div class="form-group">
                                            <label>Emergency Contact Number</label>
                                            <input type="tel" class="form-control" name="emergency_contact">
                                        </div>
                                    </div>
                                </div>

                                <hr>

                                <div class="row">
                                    <!-- Educational Information -->
                                    <div class="col-md-6">
                                        <h4 class="text-info">
                                            <i class="fas fa-graduation-cap"></i> Educational Information
                                        </h4>
                                        <div class="form-group">
                                            <label>College/Institution *</label>
                                            <input type="text" class="form-control" name="college" required>
                                        </div>
                                        <div class="form-group">
                                            <label>Course *</label>
                                            <input type="text" class="form-control" name="course" required>
                                        </div>
                                        <div class="form-group">
                                            <label>Year of Study</label>
                                            <input type="number" class="form-control" name="year_of_study" min="1" max="8">
                                        </div>
                                        <div class="form-group">
                                            <label>Session From Year</label>
                                            <input type="number" class="form-control" name="session_from_year" min="2020" max="2030">
                                        </div>
                                        <div class="form-group">
                                            <label>Session To Year</label>
                                            <input type="number" class="form-control" name="session_to_year" min="2020" max="2035">
                                        </div>
                                    </div>

                                    <!-- Membership Information -->
                                    <div class="col-md-6">
                                        <h4 class="text-warning">
                                            <i class="fas fa-id-card"></i> Membership Information
                                        </h4>
                                        <div class="form-group">
                                            <label>Membership Type *</label>
                                            <select class="form-control" name="membership_type" id="membershipType" required>
                                                <option value="">Select Type</option>
                                                <option value="Individual">Individual</option>
                                                <option value="Family">Family</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Membership Expiry Date</label>
                                            <input type="date" class="form-control" name="membership_expiry_date">
                                        </div>
                                        <div class="form-group">
                                            <label>Profile Photo</label>
                                            <input type="file" class="form-control-file" name="profile_photo" accept="image/*">
                                            <small class="form-text text-muted">Max size: 2MB. Formats: JPG, PNG</small>
                                        </div>
                                        <div class="form-group">
                                            <label>Photo ID (for records)</label>
                                            <input type="text" class="form-control" name="photo_id" placeholder="ID number or reference">
                                        </div>
                                        <div class="form-group">
                                            <label>Additional Notes</label>
                                            <textarea class="form-control" name="notes" rows="3"></textarea>
                                        </div>
                                    </div>
                                </div>

                                <hr>

                                                                    </div>
                                </div>
                                
                                <!-- Dependents Section (for Family Membership) -->
                                <div class="card" id="dependentsCard" style="display: none;">
                                    <div class="card-header">
                                        <h4 class="card-title">
                                            <i class="fas fa-users text-info"></i>
                                            Dependents Information
                                        </h4>
                                        <small class="text-muted">Required for Family membership</small>
                                    </div>
                                    <div class="card-body">
                                        <div id="dependentsList">
                                            <!-- Dependents will be added here dynamically -->
                                        </div>
                                        <button type="button" class="btn btn-outline-info btn-sm" id="addDependentBtn">
                                            <i class="fas fa-plus"></i> Add Dependent
                                        </button>
                                    </div>
                                </div>

                                <!-- Terms and Conditions -->
                                <div class="row">
                                    <div class="col-12">
                                        <div class="form-group">
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="terms_accepted" name="terms_accepted" required>
                                                <label class="custom-control-label" for="terms_accepted">
                                                    I agree to the <a href="#" data-toggle="modal" data-target="#termsModal">Terms and Conditions</a> *
                                                </label>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="privacy_accepted" name="privacy_accepted" required>
                                                <label class="custom-control-label" for="privacy_accepted">
                                                    I agree to the <a href="#" data-toggle="modal" data-target="#privacyModal">Privacy Policy</a> *
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="card-footer">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Register Member
                                </button>
                                <button type="reset" class="btn btn-secondary">
                                    <i class="fas fa-undo"></i> Reset Form
                                </button>
                                <a href="members.php" class="btn btn-default">
                                    <i class="fas fa-arrow-left"></i> Back to Members
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Terms Modal -->
<div class="modal fade" id="termsModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Terms and Conditions</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <h5>1. Membership Terms</h5>
                <p>By becoming a member of KSO Chandigarh, you agree to abide by all organizational rules and regulations.</p>
                
                <h5>2. Membership Fees</h5>
                <p>Membership fees are non-refundable and must be paid in full at the time of registration.</p>
                
                <h5>3. Code of Conduct</h5>
                <p>All members must maintain respectful behavior and contribute positively to the community.</p>
                
                <h5>4. Privacy and Data Protection</h5>
                <p>Your personal information will be handled in accordance with our Privacy Policy.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Privacy Modal -->
<div class="modal fade" id="privacyModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Privacy Policy</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <h5>Information We Collect</h5>
                <p>We collect personal information necessary for membership registration and management.</p>
                
                <h5>How We Use Your Information</h5>
                <p>Your information is used for membership management, communication, and event organization.</p>
                
                <h5>Data Security</h5>
                <p>We implement appropriate security measures to protect your personal information.</p>
                
                <h5>Data Sharing</h5>
                <p>We do not share your personal information with third parties without your consent.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    let dependentCount = 0;
    
    // Show/hide dependents section based on membership type
    $('#membershipType').on('change', function() {
        const membershipType = $(this).val();
        if (membershipType === 'Family') {
            $('#dependentsCard').show();
            if (dependentCount === 0) {
                addDependent(); // Add at least one dependent for family membership
            }
        } else {
            $('#dependentsCard').hide();
            $('#dependentsList').empty();
            dependentCount = 0;
        }
    });
    
    // Add dependent function
    function addDependent() {
        dependentCount++;
        const dependentHtml = `
            <div class="dependent-item border rounded p-3 mb-3" data-dependent-id="${dependentCount}">
                <div class="row">
                    <div class="col-md-12">
                        <h5>Dependent ${dependentCount} 
                            <button type="button" class="btn btn-sm btn-outline-danger float-right remove-dependent" data-dependent-id="${dependentCount}">
                                <i class="fas fa-times"></i> Remove
                            </button>
                        </h5>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>First Name *</label>
                            <input type="text" class="form-control" name="dependents[${dependentCount}][first_name]" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Last Name *</label>
                            <input type="text" class="form-control" name="dependents[${dependentCount}][last_name]" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Relationship *</label>
                            <select class="form-control" name="dependents[${dependentCount}][relationship]" required>
                                <option value="">Select Relationship</option>
                                <option value="Spouse">Spouse</option>
                                <option value="Child">Child</option>
                                <option value="Parent">Parent</option>
                                <option value="Sibling">Sibling</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Date of Birth</label>
                            <input type="date" class="form-control" name="dependents[${dependentCount}][date_of_birth]">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Gender</label>
                            <select class="form-control" name="dependents[${dependentCount}][gender]">
                                <option value="">Select Gender</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Phone</label>
                            <input type="tel" class="form-control" name="dependents[${dependentCount}][phone]">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Email</label>
                            <input type="email" class="form-control" name="dependents[${dependentCount}][email]">
                        </div>
                    </div>
                </div>
            </div>
        `;
        $('#dependentsList').append(dependentHtml);
    }
    
    // Add dependent button click
    $('#addDependentBtn').on('click', function() {
        addDependent();
    });
    
    // Remove dependent
    $(document).on('click', '.remove-dependent', function() {
        const dependentId = $(this).data('dependent-id');
        $(`.dependent-item[data-dependent-id="${dependentId}"]`).remove();
        
        // Check if this is family membership and no dependents left
        if ($('#membershipType').val() === 'Family' && $('#dependentsList .dependent-item').length === 0) {
            addDependent(); // Always have at least one dependent for family membership
        }
    });

    $('#memberRegistrationForm').on('submit', function(e) {
        e.preventDefault();
        
        // Hide any existing alerts
        $('#alertContainer').hide();
        $('#successAlert').hide();
        $('#errorAlert').hide();
        
        // Collect dependents data for family membership
        let dependentsData = [];
        if ($('#membershipType').val() === 'Family') {
            $('.dependent-item').each(function() {
                const dependentId = $(this).data('dependent-id');
                const dependent = {
                    first_name: $(`input[name="dependents[${dependentId}][first_name]"]`).val(),
                    last_name: $(`input[name="dependents[${dependentId}][last_name]"]`).val(),
                    relationship: $(`select[name="dependents[${dependentId}][relationship]"]`).val(),
                    date_of_birth: $(`input[name="dependents[${dependentId}][date_of_birth]"]`).val(),
                    gender: $(`select[name="dependents[${dependentId}][gender]"]`).val(),
                    phone: $(`input[name="dependents[${dependentId}][phone]"]`).val(),
                    email: $(`input[name="dependents[${dependentId}][email]"]`).val()
                };
                dependentsData.push(dependent);
            });
        }
        
        const formData = new FormData(this);
        formData.append('dependents', JSON.stringify(dependentsData));
        
        // Show loading state
        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.text();
        submitBtn.text('Registering...').prop('disabled', true);
        
        $.ajax({
            url: 'api/register_member.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Hide any error alerts
                    $('#errorAlert').hide();
                    
                    // Show success alert
                    $('#successMessage').html(`
                        <strong>Member registered successfully!</strong><br>
                        <strong>KSO ID:</strong> ${response.kso_id}<br>
                        <strong>Member ID:</strong> ${response.member_id}<br>
                        <strong>Membership Type:</strong> ${response.membership_type}<br>
                        <small class="text-muted">Redirecting to members list in 3 seconds...</small>
                    `);
                    $('#successAlert').show();
                    $('#alertContainer').show();
                    
                    // Also show toastr notification
                    toastr.success('Member registered successfully! KSO ID: ' + response.kso_id);
                    
                    // Scroll to top to show the alert
                    $('html, body').animate({
                        scrollTop: 0
                    }, 500);
                    
                    // Redirect after 3 seconds
                    setTimeout(function() {
                        window.location.href = 'members.php';
                    }, 3000);
                } else {
                    // Hide success alert
                    $('#successAlert').hide();
                    
                    // Show error alert
                    $('#errorMessage').text(response.message || 'Registration failed');
                    $('#errorAlert').show();
                    $('#alertContainer').show();
                    
                    // Also show toastr error
                    toastr.error(response.message || 'Registration failed');
                    
                    // Scroll to top to show the alert
                    $('html, body').animate({
                        scrollTop: 0
                    }, 500);
                }
            },
            error: function(xhr, status, error) {
                console.error('Registration error:', xhr.responseText);
                
                // Hide success alert
                $('#successAlert').hide();
                
                let errorMsg = '';
                if (xhr.status === 404) {
                    errorMsg = 'Registration service not found. Please contact administrator.';
                } else if (xhr.status === 500) {
                    errorMsg = 'Server error occurred. Please try again.';
                } else {
                    errorMsg = 'Error registering member: ' + error;
                }
                
                // Show error alert
                $('#errorMessage').text(errorMsg);
                $('#errorAlert').show();
                $('#alertContainer').show();
                
                // Also show toastr error
                toastr.error(errorMsg);
                
                // Scroll to top to show the alert
                $('html, body').animate({
                    scrollTop: 0
                }, 500);
            },
            complete: function() {
                // Restore button state
                submitBtn.text(originalText).prop('disabled', false);
            }
        });
    });
});
</script>

<?php require_once 'templates/footer.php'; ?>
