<?php
include 'header.php';

if (isset($_GET['celebrities'])){
    $celeb = $_GET['celebrities'];

    $select = mysqli_query( $link, "SELECT * FROM  celebrities  WHERE id = '$celeb' " );
    if ( mysqli_num_rows( $select ) > 0 ) {
        $row = mysqli_fetch_assoc( $select );
        $celebrities_name = $row['name'];
    } else {
        echo "<script>window.location.href = 'celebrities.php'; </script>";
    }
} else {
    // echo "<script>window.location.href = 'index.php'; </script>";
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $amount = text_input($_POST['amount']);
    $type = text_input($_POST['type']);
    $event_name = text_input($_POST['event_name']);
    $event_date= text_input($_POST['event_date']);
    $event_time = text_input($_POST['event_time']);
    $number_of_people = text_input($_POST['number_of_people']);
    $duration_hours = text_input($_POST['duration_hours']);
    $location = text_input($_POST['location']);
    $details = text_input($_POST['details']);
    $special_requests = text_input($_POST['special_requests']);
    $celebrities = $celebrities_name;
    $celebrity_id = $celeb;

    $_SESSION['payment'] = [
        "amount" => $amount,
        "type" => $type,
        "event_name" => $event_name,
         "event_date" => $event_date,
         "event_time" => $event_time,
         "number_of_people" => $number_of_people,
         "duration_hours" => $duration_hours,
         "location" => $location,
         "duration_hours" => $duration_hours,
         "details" => $details,
         "special_requests" => $special_requests,
         "celebrity_id" => $celebrity_id,
         "celebrities_name" => $celebrities_name,
         
    ];
    echo "<script> window.location.href = 'payment3.php'; </script>";

}



?>

    <main class="flex-grow-1" style="padding-top: 80px;">
        
        
        <style>
    .booking-hero {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 4rem 0;
        border-radius: 0 0 50px 50px;
        margin-bottom: 3rem;
        position: relative;
        overflow: hidden;
    }

    .booking-hero::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg width="60" height="60" viewBox="0 0 60 60" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><g fill="%23ffffff" fill-opacity="0.1"><circle cx="12" cy="12" r="2"/><circle cx="48" cy="12" r="2"/><circle cx="12" cy="48" r="2"/><circle cx="48" cy="48" r="2"/></g></g></svg>');
    }

    .hero-content {
        position: relative;
        z-index: 2;
    }

    .celebrity-card {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(20px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 20px;
        padding: 2rem;
        margin-bottom: 2rem;
    }

    .celebrity-avatar {
        width: 120px;
        height: 120px;
        border-radius: 20px;
        object-fit: cover;
        border: 4px solid rgba(255, 255, 255, 0.3);
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    }

    .celebrity-placeholder {
        width: 120px;
        height: 120px;
        border-radius: 20px;
        background: rgba(255, 255, 255, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        border: 4px solid rgba(255, 255, 255, 0.3);
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    }

    .price-badge {
        background: rgba(255, 255, 255, 0.2);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.3);
        border-radius: 15px;
        padding: 1rem 1.5rem;
        text-align: center;
        margin-top: 1rem;
    }

    .form-container {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(20px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 25px;
        padding: 3rem;
        box-shadow: 0 25px 50px rgba(0, 0, 0, 0.1);
        position: relative;
        overflow: hidden;
    }

    .form-container::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 5px;
        background: linear-gradient(90deg, #667eea, #764ba2, #667eea);
        background-size: 200% 100%;
        animation: shimmer 3s infinite;
    }

    @keyframes shimmer {
        0% { background-position: -200% 0; }
        100% { background-position: 200% 0; }
    }

    .form-section {
        background: rgba(102, 126, 234, 0.03);
        border-radius: 20px;
        padding: 2rem;
        margin-bottom: 2rem;
        border-left: 4px solid #667eea;
        position: relative;
    }

    .section-icon {
        position: absolute;
        top: -10px;
        left: 2rem;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2rem;
    }

    .section-title {
        font-weight: 700;
        color: #2d3748;
        margin-bottom: 1.5rem;
        padding-left: 3rem;
        font-size: 1.2rem;
    }

    .form-group {
        margin-bottom: 2rem;
    }

    .form-label {
        font-weight: 600;
        color: #2d3748;
        margin-bottom: 0.75rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.95rem;
    }

    .form-control {
        border: 2px solid #e2e8f0;
        border-radius: 15px;
        padding: 1rem 1.25rem;
        transition: all 0.3s ease;
        background: white;
        font-size: 1rem;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    .form-control:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        outline: none;
        transform: translateY(-2px);
    }

    .form-control.is-invalid {
        border-color: #e53e3e;
    }

    .form-control.is-valid {
        border-color: #38a169;
    }

    .input-group {
        position: relative;
    }

    .input-icon {
        position: absolute;
        left: 1rem;
        top: 50%;
        transform: translateY(-50%);
        color: #a0aec0;
        z-index: 3;
    }

    .input-group .form-control {
        padding-left: 3rem;
    }

    .character-count {
        font-size: 0.8rem;
        color: #a0aec0;
        text-align: right;
        margin-top: 0.25rem;
    }

    .character-count.text-warning {
        color: #fd7e14;
        font-weight: bold;
    }

    .btn-submit {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        padding: 1.25rem 3rem;
        border-radius: 15px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 1px;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
        box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
    }
    
    .btn-submit:disabled {
        opacity: 0.8;
        cursor: not-allowed;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    .btn-submit::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: left 0.5s;
    }

    .btn-submit:hover::before {
        left: 100%;
    }

    .btn-submit:hover {
        transform: translateY(-3px);
        box-shadow: 0 15px 40px rgba(102, 126, 234, 0.4);
    }

    .btn-cancel {
        background: rgba(108, 117, 125, 0.1);
        color: #6c757d;
        border: 2px solid #dee2e6;
        padding: 1.25rem 3rem;
        border-radius: 15px;
        font-weight: 600;
        transition: all 0.3s ease;
    }

    .btn-cancel:hover {
        background: #6c757d;
        color: white;
        border-color: #6c757d;
        transform: translateY(-2px);
    }

    .floating-elements {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
        overflow: hidden;
    }

    .floating-element {
        position: absolute;
        width: 20px;
        height: 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 50%;
        opacity: 0.1;
        animation: float 15s infinite linear;
    }

    @keyframes float {
        0% {
            transform: translateY(100vh) rotate(0deg);
            opacity: 0;
        }
        10% {
            opacity: 0.1;
        }
        90% {
            opacity: 0.1;
        }
        100% {
            transform: translateY(-100px) rotate(360deg);
            opacity: 0;
        }
    }

    .progress-indicator {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 4px;
        background: rgba(102, 126, 234, 0.1);
        z-index: 1000;
    }

    .progress-bar {
        height: 100%;
        background: linear-gradient(90deg, #667eea, #764ba2);
        width: 0%;
        transition: width 0.3s ease;
    }

    .alert-custom {
        border: none;
        border-radius: 15px;
        padding: 1.5rem;
        margin-bottom: 2rem;
        background: rgba(220, 53, 69, 0.1);
        border-left: 4px solid #dc3545;
        backdrop-filter: blur(10px);
    }

    .form-validation {
        position: relative;
    }

    .validation-icon {
        position: absolute;
        right: 1rem;
        top: 50%;
        transform: translateY(-50%);
        font-size: 1.2rem;
        opacity: 0;
        transition: opacity 0.3s ease;
    }

    .form-control:valid + .validation-icon.valid {
        opacity: 1;
        color: #38a169;
    }

    .form-control:invalid:not(:placeholder-shown) + .validation-icon.invalid {
        opacity: 1;
        color: #e53e3e;
    }

    @media (max-width: 768px) {
        .booking-hero {
            padding: 2rem 0;
            border-radius: 0 0 30px 30px;
        }
        
        .form-container {
            padding: 2rem;
            border-radius: 20px;
        }
        
        .celebrity-card {
            text-align: center;
        }
        
        .btn-submit, .btn-cancel {
            width: 100%;
            margin-bottom: 1rem;
        }
    }
</style>

<!-- Progress Indicator -->
<div class="progress-indicator">
    <div class="progress-bar" id="formProgress"></div>
</div>

<div class="container-fluid px-0">
    <!-- Hero Section -->
    <div class="booking-hero">
        <div class="container">
            <div class="hero-content">
                <div class="row align-items-center">
                    <div class="col-lg-8">
                        <h1 class="display-4 fw-bold mb-3">
                            <i class="fas fa-calendar-star me-3"></i>
                            Book an Event
                        </h1>
                        <p class="lead mb-4">Create an unforgettable event experience with Stephen Amell</p>
                        
                        <div class="celebrity-card">
                            <div class="row align-items-center">
                                <div class="col-md-4 text-center mb-3 mb-md-0">
                                                                            <img src="uploads/celebrities/<?php echo $row['image'] ?>"  
                                             alt="<?php echo $row['name'] ?>" class="celebrity-avatar">
                                                                    </div>
                                <div class="col-md-8">
                                    <h3 class="fw-bold mb-2"><?php echo $row['name'] ?></h3>
                                    <p class="opacity-75 mb-3"><?php echo $row['specialties'] ?></p>
                                    <div class="price-badge">
                                        <div class="h4 mb-1">$<?php echo number_format($row['event_booking_fee'], 2) ?></div>
                                        <small class="opacity-75">Duration: 6 hours</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Floating Elements -->
        <div class="floating-elements">
            <div class="floating-element" style="left: 10%; animation-delay: 0s;"></div>
            <div class="floating-element" style="left: 20%; animation-delay: 2s;"></div>
            <div class="floating-element" style="left: 30%; animation-delay: 4s;"></div>
            <div class="floating-element" style="left: 40%; animation-delay: 6s;"></div>
            <div class="floating-element" style="left: 50%; animation-delay: 8s;"></div>
            <div class="floating-element" style="left: 60%; animation-delay: 10s;"></div>
            <div class="floating-element" style="left: 70%; animation-delay: 12s;"></div>
            <div class="floating-element" style="left: 80%; animation-delay: 14s;"></div>
        </div>
    </div>
</div>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            
            
            <div class="form-container">
                <form action="" method="POST" id="eventBookingForm" novalidate>
                    <input type="hidden" name="_token" value="AMYr3bZTgC84TRQKvCJUXUdqCK3BGQcUJ3l9RlAg" autocomplete="off">                    <input type="hidden" name="celebrity_id" value="12">
                    <input type="hidden" name="type" value="event">
                    <input type="hidden" name="amount" value="<?php echo number_format($row['event_booking_fee'], 2) ?>">
                    
                    <!-- Event Details Section -->
                    <div class="form-section">
                        <div class="section-icon">
                            <i class="fas fa-info-circle"></i>
                        </div>
                        <h4 class="section-title">Event Details</h4>
                        
                        <div class="form-group">
                            <label for="event_name" class="form-label">
                                <i class="fas fa-tag text-primary"></i>
                                Event Name
                            </label>
                            <div class="form-validation">
                                <input type="text" 
                                       class="form-control " 
                                       id="event_name" 
                                       name="event_name" 
                                       value="" 
                                       required 
                                       placeholder="e.g., Annual Corporate Gala, Birthday Celebration"
                                       maxlength="100">
                                <i class="fas fa-check validation-icon valid"></i>
                                <i class="fas fa-times validation-icon invalid"></i>
                                <div class="character-count">
                                    <span id="event_name_count">0</span>/100
                                </div>
                            </div>
                                                    </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="event_date" class="form-label">
                                        <i class="fas fa-calendar text-success"></i>
                                        Event Date
                                    </label>
                                    <div class="form-validation">
                                        <input type="date" 
                                               class="form-control " 
                                               id="event_date" 
                                               name="event_date" 
                                               min="2025-07-07" 
                                               value="" 
                                               required>
                                        <i class="fas fa-check validation-icon valid"></i>
                                        <i class="fas fa-times validation-icon invalid"></i>
                                    </div>
                                                                    </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="event_time" class="form-label">
                                        <i class="fas fa-clock text-info"></i>
                                        Event Time
                                    </label>
                                    <div class="form-validation">
                                        <input type="time" 
                                               class="form-control " 
                                               id="event_time" 
                                               name="event_time" 
                                               value="" 
                                               required>
                                        <i class="fas fa-check validation-icon valid"></i>
                                        <i class="fas fa-times validation-icon invalid"></i>
                                    </div>
                                                                    </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="number_of_people" class="form-label">
                                        <i class="fas fa-users text-primary"></i>
                                        Number of Attendees
                                    </label>
                                    <div class="form-validation">
                                        <input type="number" 
                                               class="form-control " 
                                               id="number_of_people" 
                                               name="number_of_people" 
                                               value="1" 
                                               min="1" 
                                               max="1000"
                                               required>
                                        <i class="fas fa-check validation-icon valid"></i>
                                        <i class="fas fa-times validation-icon invalid"></i>
                                    </div>
                                                                    </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="duration_hours" class="form-label">
                                        <i class="fas fa-clock text-info"></i>
                                        Duration (hours)
                                    </label>
                                    <div class="form-validation">
                                        <input type="number" 
                                               class="form-control " 
                                               id="duration_hours" 
                                               name="duration_hours" 
                                               value="6" 
                                               min="1" 
                                               max="24"
                                               required>
                                        <i class="fas fa-check validation-icon valid"></i>
                                        <i class="fas fa-times validation-icon invalid"></i>
                                    </div>
                                                                    </div>
                            </div>
                        </div>
                    </div>

                    <!-- Location Section -->
                    <div class="form-section">
                        <div class="section-icon">
                            <i class="fas fa-map-marker-alt"></i>
                        </div>
                        <h4 class="section-title">Event Location</h4>
                        
                        <div class="form-group">
                            <label for="location" class="form-label">
                                <i class="fas fa-building text-warning"></i>
                                Venue Address
                            </label>
                            <div class="input-group">
                                <i class="fas fa-map-pin input-icon"></i>
                                <input type="text" 
                                       class="form-control " 
                                       id="location" 
                                       name="location" 
                                       value="" 
                                       required 
                                       placeholder="Enter full venue address"
                                       maxlength="200">
                                <div class="character-count">
                                    <span id="location_count">0</span>/200
                                </div>
                            </div>
                                                    </div>
                    </div>

                    <!-- Event Description Section -->
                    <div class="form-section">
                        <div class="section-icon">
                            <i class="fas fa-align-left"></i>
                        </div>
                        <h4 class="section-title">Event Description</h4>
                        
                        <div class="form-group">
                            <label for="details" class="form-label">
                                <i class="fas fa-file-alt text-purple"></i>
                                Event Details
                            </label>
                            <div class="form-validation position-relative">
                                <textarea class="form-control " 
                                          id="details" 
                                          name="details" 
                                          rows="4" 
                                          placeholder="Describe your event, expected audience, theme, and any specific requirements..."
                                          maxlength="500"></textarea>
                                <div class="character-count">
                                    <span id="details_count">0</span>/500
                                </div>
                            </div>
                                                    </div>

                        <div class="form-group">
                            <label for="special_requests" class="form-label">
                                <i class="fas fa-star text-warning"></i>
                                Special Requests
                            </label>
                            <div class="form-validation position-relative">
                                <textarea class="form-control " 
                                          id="special_requests" 
                                          name="special_requests" 
                                          rows="3" 
                                          placeholder="Any special requests, dietary requirements, or specific performance requests..."
                                          maxlength="300"
                                          data-max-chars="300"></textarea>
                                <div class="character-count">
                                    <span id="special_requests_count">0</span>/300
                                </div>
                            </div>
                                                    </div>
                    </div>

                    <!-- Submit Section -->
                    <div class="text-center">
                        <div class="d-flex flex-column flex-md-row gap-3 justify-content-center align-items-center">
                            <a href="" class="btn btn-cancel">
                                <i class="fas fa-arrow-left me-2"></i>
                                Cancel
                            </a>
                            <button type="submit" class="btn btn-submit text-white position-relative" id="submitBtn" style="min-width: 220px;">
                                <div class="d-flex align-items-center justify-content-center">
                                    <i class="fas fa-credit-card me-2"></i>
                                    <span class="btn-text">Proceed to Payment</span>
                                    <span class="btn-spinner spinner-border spinner-border-sm ms-2 d-none" role="status" aria-hidden="true"></span>
                                    <span class="ms-2 price-amount">$<?php echo number_format($row['event_booking_fee'], 2) ?></span>
                                </div>
                            </button>
                        </div>
                        
                        <p class="text-muted mt-3 mb-0">
                            <i class="fas fa-shield-alt me-1"></i>
                            Your booking is secure and protected
                        </p>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('eventBookingForm');
    const progressBar = document.getElementById('formProgress');
    const submitBtn = document.getElementById('submitBtn');
    
    // Character counters
    const counters = [
        {input: 'event_name', max: 100},
        {input: 'location', max: 200},
        {input: 'details', max: 500},
        {input: 'special_requests', max: 300}
    ];
    
    // Initialize character counters
    counters.forEach(counter => {
        const input = document.getElementById(counter.input);
        const countSpan = document.getElementById(counter.input + '_count');
        
        if (input && countSpan) {
            input.addEventListener('input', function() {
                const count = this.value.length;
                countSpan.textContent = count;
                
                if (count > counter.max * 0.9) {
                    countSpan.style.color = '#e53e3e';
                } else if (count > counter.max * 0.7) {
                    countSpan.style.color = '#d69e2e';
                } else {
                    countSpan.style.color = '#a0aec0';
                }
            });
            
            // Initialize counter
            input.dispatchEvent(new Event('input'));
        }
    });
    
    // Form progress tracking
    function updateProgress() {
        const inputs = form.querySelectorAll('input[required], textarea[required]');
        let filled = 0;
        
        inputs.forEach(input => {
            if (input.value.trim() !== '') {
                filled++;
            }
        });
        
        const progress = (filled / inputs.length) * 100;
        progressBar.style.width = progress + '%';
    }
    
    // Update progress on input
    form.addEventListener('input', updateProgress);
    updateProgress();
    
    // Enhanced form validation
    form.addEventListener('submit', function(e) {
        // Check if form is already being submitted
        if (submitBtn.disabled) {
            e.preventDefault();
            return false;
        }
        
        // Validate event date
        const eventDate = new Date(document.getElementById('event_date').value);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        if (eventDate < today) {
            e.preventDefault();
            alert('Event date cannot be in the past.');
            return false;
        }
        
        // Show loading state
        submitBtn.disabled = true;
        const spinner = submitBtn.querySelector('.btn-spinner');
        const btnText = submitBtn.querySelector('.btn-text');
        const priceSpan = submitBtn.querySelector('.price-amount');
        
        if (spinner) spinner.classList.remove('d-none');
        if (btnText) btnText.textContent = 'Processing...';
        if (priceSpan) priceSpan.style.display = 'none';
        
        // Prevent double submission
        form.querySelectorAll('button[type="submit"]').forEach(btn => {
            btn.disabled = true;
        });
        
        // Re-enable the button after 30 seconds if the form hasn't submitted
        setTimeout(() => {
            if (submitBtn.disabled) {
                submitBtn.disabled = false;
                if (spinner) spinner.classList.add('d-none');
                if (btnText) btnText.textContent = 'Proceed to Payment';
                if (priceSpan) priceSpan.style.display = 'inline';
                
                // Re-enable all submit buttons
                form.querySelectorAll('button[type="submit"]').forEach(btn => {
                    btn.disabled = false;
                });
                
                alert('Form submission is taking longer than expected. Please try again.');
            }
        }, 30000);
        
        // Allow form to submit naturally
        return true;
    });
    
    // Auto-save form data to localStorage
    const formData = {};
    form.addEventListener('input', function(e) {
        if (e.target.name) {
            formData[e.target.name] = e.target.value;
            localStorage.setItem('eventBookingForm', JSON.stringify(formData));
        }
    });
    
    // Restore form data on page load
    const savedData = localStorage.getItem('eventBookingForm');
    if (savedData) {
        const data = JSON.parse(savedData);
        Object.keys(data).forEach(key => {
            const input = form.querySelector(`[name="${key}"]`);
            if (input && !input.value) {
                input.value = data[key];
                input.dispatchEvent(new Event('input'));
            }
        });
    }
    
    // Clear saved data on successful submission
    form.addEventListener('submit', function() {
        localStorage.removeItem('eventBookingForm');
    });
});
</script>
    </main>
<?php
include 'footer.php';

?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Check if we should show the profile update modal
            
            // Handle form submission
            const profileForm = document.getElementById('profileUpdateForm');
            if (profileForm) {
                profileForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(profileForm);
                    const submitBtn = profileForm.querySelector('button[type="submit"]');
                    const originalBtnText = submitBtn.innerHTML;
                    
                    // Show loading state
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Updating...';
                    
                    fetch(profileForm.action, {
                        method: 'POST',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                            'Accept': 'application/json'
                        },
                        body: formData
                    })
                    .then(async response => {
                        const data = await response.json();
                        
                        if (!response.ok) {
                            // Handle validation errors
                            if (response.status === 422 && data.errors) {
                                // Clear previous error messages
                                document.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
                                document.querySelectorAll('.invalid-feedback').forEach(el => el.remove());
                                
                                // Display validation errors
                                Object.entries(data.errors).forEach(([field, messages]) => {
                                    const input = document.querySelector(`[name="${field}"]`);
                                    if (input) {
                                        input.classList.add('is-invalid');
                                        const errorDiv = document.createElement('div');
                                        errorDiv.className = 'invalid-feedback';
                                        errorDiv.textContent = messages[0];
                                        input.parentNode.appendChild(errorDiv);
                                    }
                                });
                                throw new Error('Validation failed');
                            }
                            throw new Error(data.message || 'Failed to update profile');
                        }
                        
                        return data;
                    })
                    .then(data => {
                        if (data.success) {
                            // Show success message
                            const successAlert = document.createElement('div');
                            successAlert.className = 'alert alert-success mt-3';
                            successAlert.textContent = 'Profile updated successfully!';
                            document.querySelector('.modal-body').prepend(successAlert);
                            
                            // Close the modal and redirect after a short delay
                            setTimeout(() => {
                                const modal = bootstrap.Modal.getInstance(document.getElementById('profileUpdateModal'));
                                modal.hide();
                                if (data.redirect) {
                                    window.location.href = data.redirect;
                                }
                            }, 1500);
                        } else {
                            throw new Error(data.message || 'Failed to update profile');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        
                        // Show error message
                        const errorAlert = document.createElement('div');
                        errorAlert.className = 'alert alert-danger mt-3';
                        errorAlert.textContent = error.message || 'An error occurred while updating your profile. Please try again.';
                        document.querySelector('.modal-body').prepend(errorAlert);
                        
                        // Remove the alert after 5 seconds
                        setTimeout(() => {
                            errorAlert.remove();
                        }, 5000);
                    })
                    .finally(() => {
                        // Reset button state
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalBtnText;
                    });
                });
            }
        });
    </script>
    </body>
</html>