<?php include 'header.php'; ?>

<!-- Normal Sub Header -->
<?php include 'template-parts/sub-header-trainer.php'; ?>

<div class="uk-container">
    <div class="uk-grid uk-grid-medium" uk-grid>

        <!-- Sidebar Area -->
        <div class="uk-width-2-6@m uk-visible@m">
            <div class="sidebar-sticky" uk-sticky="offset: 20; bottom: true">
                <?php include 'trainer-sidebar.php'; ?>
            </div>
        </div>

        <!-- Main Content Area -->
        <div class="uk-width-expand@m m-first">

            <!-- Trainer Phone Number Change Modal -->
            <div id="trainerPhoneChangeModal" uk-modal>
                <div class="uk-modal-dialog uk-modal-body">
                    <button class="uk-modal-close-default" type="button" uk-close></button>
                    <h2 class="uk-modal-title">Change Phone Number</h2>

                    <div id="trainerPhoneStep1" class="phone-change-step">
                        <p class="uk-margin-small-bottom">Enter your new phone number. We'll send you an OTP to verify it.</p>
                        <div class="form-group uk-margin">
                            <label class="form-label" for="newPhoneNumber">New Phone Number</label>
                            <input type="tel" class="uk-input" id="newPhoneNumber" placeholder="+966 55 123 4567">
                        </div>
                        <div class="uk-flex uk-flex-right uk-margin-top">
                            <button type="button" class="uk-button uk-button-default uk-margin-small-right" onclick="UIkit.modal('#trainerPhoneChangeModal').hide()">Cancel</button>
                            <button type="button" class="uk-button uk-button-primary" onclick="sendOTP()">Send OTP</button>
                        </div>
                    </div>

                    <div id="trainerPhoneStep2" class="phone-change-step uk-hidden">
                        <p class="uk-margin-small-bottom">We've sent a verification code to <span id="otpPhoneDisplay"></span></p>
                        <div class="form-group uk-margin">
                            <label class="form-label" for="otpCode">Enter 6-digit OTP</label>
                            <input type="text" class="uk-input uk-text-center" id="otpCode" placeholder="123456" maxlength="6" style="font-size: 1.2em; letter-spacing: 0.2em;">
                        </div>
                        <div class="uk-text-center uk-margin">
                            <button type="button" class="uk-button uk-button-link uk-text-small" onclick="resendOTP()" id="resendOTPBtn">
                                Didn't receive code? Resend OTP
                            </button>
                            <div id="otpTimer" class="uk-text-small uk-text-muted uk-hidden">
                                Resend OTP in <span id="timerCount">60</span> seconds
                            </div>
                        </div>
                        <div class="uk-flex uk-flex-right uk-margin-top">
                            <button type="button" class="uk-button uk-button-default uk-margin-small-right" onclick="goBackToPhoneStep()">Back</button>
                            <button type="button" class="uk-button uk-button-primary" onclick="verifyOTP()">Verify</button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="profile-container">

                <div class="profile-header">
                    <h2 class="uk-heading-divider">Personal Information</h2>
                </div>

                <form id="personalInfoForm">
                    <div class="uk-grid uk-grid-medium" uk-grid>

                        <!-- Profile Picture Upload -->
                        <div class="uk-width-1-2@s">
                            <div class="form-group">
                                <label class="form-label" for="profilePictureInput">Profile Picture</label>
                                <div class="upload-container">
                                    <div class="upload-area" id="profilePictureUpload">
                                        <div class="upload-icon"><span uk-icon="icon: image; ratio: 1.6" class="uk-icon" aria-hidden="true"></span></div>
                                        <div class="upload-text">Upload new profile picture</div>
                                        <div class="upload-subtext">choose file</div>
                                    </div>
                                    <input type="file" id="profilePictureInput" class="hidden" accept="image/*">
                                    <div id="profilePicturePreview" class="preview-container hidden"></div>
                                </div>
                            </div>
                        </div>

                        <!-- Introduction Video Upload -->
                        <div class="uk-width-1-2@s">
                            <div class="form-group">
                                <label class="form-label" for="introVideoInput">Introduction Video</label>
                                <div class="upload-container">
                                    <div class="upload-area" id="introVideoUpload">
                                        <div class="upload-icon"><span uk-icon="icon: video; ratio: 1.6" class="uk-icon" aria-hidden="true"></span></div>
                                        <div class="upload-text">Upload new Introduction Video</div>
                                        <div class="upload-subtext">choose file</div>
                                    </div>
                                    <input type="file" id="introVideoInput" class="hidden" accept="video/*">
                                    <div id="introVideoPreview" class="preview-container hidden"></div>
                                </div>
                            </div>
                        </div>

                        <!-- First Name -->
                        <div class="uk-width-1-2@s">
                            <div class="form-group">
                                <label class="form-label" for="firstName">First Name</label>
                                <input type="text" class="uk-input" id="firstName" value="Ahmed" required>
                            </div>
                        </div>

                        <!-- Last Name -->
                        <div class="uk-width-1-2@s">
                            <div class="form-group">
                                <label class="form-label" for="lastName">Last Name</label>
                                <input type="text" class="uk-input" id="lastName" value="Al-Rashid" required>
                            </div>
                        </div>

                        <!-- Email -->
                        <div class="uk-width-1-2@s">
                            <div class="form-group">
                                <label class="form-label" for="email">Email</label>
                                <input type="email" class="uk-input" id="email" value="ahmed.trainer@email.com">
                            </div>
                        </div>

                        <!-- Phone Number with Edit Button -->
                        <div class="uk-width-1-2@s">
                            <div class="form-group">
                                <label class="form-label" for="phone">Phone Number</label>
                                <div class="uk-flex uk-flex-middle">
                                    <input type="tel" class="uk-input uk-margin-small-right" id="phone" value="+966 50 123 4567" readonly style="flex: 1;">
                                    <button type="button" class="uk-button uk-button-default" onclick="UIkit.modal('#trainerPhoneChangeModal').show()">
                                        <span uk-icon="icon: pencil; ratio: 0.8" class="uk-margin-small-right"></span>Edit
                                    </button>
                                </div>
                                <small class="uk-text-muted">Click edit to change your phone number (OTP verification required)</small>
                            </div>
                        </div>

                        <!-- Gender -->
                        <div class="uk-width-1-2@s">
                            <div class="form-group">
                                <label class="form-label" for="gender">Gender</label>
                                <select class="uk-select" id="gender" required>
                                    <option value="male" selected>Male</option>
                                    <option value="female">Female</option>
                                </select>
                            </div>
                        </div>

                        <!-- Experience -->
                        <div class="uk-width-1-2@s">
                            <div class="form-group">
                                <label class="form-label" for="experience">Experience (Years)</label>
                                <input type="number" class="uk-input" id="experience" value="8" min="0" required>
                            </div>
                        </div>

                        <!-- Languages Section -->
                        <div class="uk-width-1-1">
                            <div class="form-group">
                                <label class="form-label" for="languageSelect">Languages Spoken</label>
                                <select class="uk-select" id="languageSelect">
                                    <option value="">Select Language</option>
                                    <option value="Arabic">Arabic</option>
                                    <option value="English">English</option>
                                    <option value="French">French</option>
                                    <option value="German">German</option>
                                    <option value="Spanish">Spanish</option>
                                    <option value="Italian">Italian</option>
                                    <option value="Portuguese">Portuguese</option>
                                    <option value="Chinese">Chinese</option>
                                    <option value="Japanese">Japanese</option>
                                    <option value="Korean">Korean</option>
                                </select>
                                <div class="language-tags" id="selectedLanguages">
                                    <!-- Languages will appear here when selected -->
                                </div>
                            </div>
                        </div>

                        <!-- Small Description -->
                        <div class="uk-width-1-1">
                            <div class="form-group">
                                <label class="form-label" for="header-description">Header Description <small class="uk-text-normal uk-text-muted">(Appear on trainer page in header after name)</small></label>
                                <textarea class="uk-textarea" id="header-description" placeholder="Sales Director"></textarea>
                            </div>
                        </div>
                        
                        <!-- Description -->
                        <div class="uk-width-1-1">
                            <div class="form-group">
                                <label class="form-label" for="description">Professional Description <small class="uk-text-normal uk-text-muted">(Appear on trainer page in about section)</small></label>
                                <textarea class="uk-textarea" id="description" placeholder="Describe your expertise, approach, and what makes you a great trainer..."></textarea>
                            </div>
                        </div>

                        <!-- Submit Button -->
                        <div class="uk-width-1-1">
                            <button type="submit" class="uk-button uk-button-primary">Save Changes</button>
                        </div>

                    </div>
                </form>

            </div>

        </div>

    </div><!-- .uk-grid -->
</div><!-- .uk-container -->


<script>
    // Selected languages array - starts empty
    let selectedLanguages = [];

    // File upload handlers
    function setupFileUpload(uploadAreaId, inputId, previewId, isVideo = false) {
        const uploadArea = document.getElementById(uploadAreaId);
        const input = document.getElementById(inputId);
        const preview = document.getElementById(previewId);

        // Click to upload
        uploadArea.addEventListener('click', () => input.click());

        // Drag and drop
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFileUpload(files[0], uploadArea, preview, input, isVideo);
            }
        });

        // File input change
        input.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFileUpload(e.target.files[0], uploadArea, preview, input, isVideo);
            }
        });
    }

    function handleFileUpload(file, uploadArea, previewContainer, input, isVideo) {
        const reader = new FileReader();

        reader.onload = function(e) {
            let previewElement;

            if (isVideo) {
                previewElement = `
                        <video class="preview-video" controls>
                            <source src="${e.target.result}" type="${file.type}">
                            Your browser does not support the video tag.
                        </video>
                    `;
            } else {
                previewElement = `<img src="${e.target.result}" alt="Preview" class="preview-image">`;
            }

            previewContainer.innerHTML = `
                    ${previewElement}
                    <div class="actions-btns uk-margin-small uk-flex-center">
                        <button type="button" class="action-btn delete-btn" onclick="removeFile('${uploadArea.id}', '${previewContainer.id}', '${input.id}')"><span uk-icon="icon: trash; ratio: .8" class="uk-icon" aria-hidden="true"></span></button>
                        <button type="button" class="action-btn replace-btn" onclick="replaceFile('${input.id}')"><span uk-icon="icon: image; ratio: .8" class="uk-icon" aria-hidden="true"></span></button>
                    </div>
                `;

            // Hide upload area and show preview
            uploadArea.classList.add('hidden');
            previewContainer.classList.remove('hidden');
        };

        reader.readAsDataURL(file);
    }

    function removeFile(uploadAreaId, previewId, inputId) {
        const uploadArea = document.getElementById(uploadAreaId);
        const preview = document.getElementById(previewId);
        const input = document.getElementById(inputId);

        // Clear input
        input.value = '';

        // Clear preview and hide it
        preview.innerHTML = '';
        preview.classList.add('hidden');

        // Show upload area again
        uploadArea.classList.remove('hidden');
    }

    function replaceFile(inputId) {
        const input = document.getElementById(inputId);
        input.click();
    }

    // Language selection
    function addLanguage(language) {
        if (!selectedLanguages.includes(language)) {
            selectedLanguages.push(language);
            updateLanguageDisplay();
        }
    }

    function removeLanguage(language) {
        const index = selectedLanguages.indexOf(language);
        if (index > -1) {
            selectedLanguages.splice(index, 1);
            updateLanguageDisplay();
        }
    }

    function updateLanguageDisplay() {
        const container = document.getElementById('selectedLanguages');

        if (selectedLanguages.length === 0) {
            container.innerHTML = '';
            return;
        }

        container.innerHTML = selectedLanguages.map(lang => `
                <div class="language-tag" data-language="${lang}">
                    ${lang}
                    <button type="button" class="remove-tag" onclick="removeLanguage('${lang}')">×</button>
                </div>
            `).join('');
    }

    // Language select change handler
    document.getElementById('languageSelect').addEventListener('change', function() {
        if (this.value) {
            addLanguage(this.value);
            this.value = ''; // Reset select
        }
    });

    // START: Phone Number Change Functions
    let otpTimer;
    let otpTimerCount = 60;

    function sendOTP() {
        const newPhone = document.getElementById('newPhoneNumber').value.trim();

        if (!newPhone) {
            UIkit.notification({
                message: 'Please enter a valid phone number',
                status: 'warning',
                pos: 'top-center',
                timeout: 3000
            });
            return;
        }

        // Show loading state
        const sendBtn = event.target;
        const originalText = sendBtn.textContent;
        sendBtn.textContent = 'Sending...';
        sendBtn.disabled = true;

        // Simulate API call to send OTP
        setTimeout(() => {
            // Update display phone number
            document.getElementById('otpPhoneDisplay').textContent = newPhone;

            // Hide step 1, show step 2
            document.getElementById('trainerPhoneStep1').classList.add('uk-hidden');
            document.getElementById('trainerPhoneStep2').classList.remove('uk-hidden');

            // Start OTP timer
            startOTPTimer();

            // Reset button
            sendBtn.textContent = originalText;
            sendBtn.disabled = false;

            UIkit.notification({
                message: 'OTP sent successfully!',
                status: 'success',
                pos: 'top-center',
                timeout: 3000
            });
        }, 1500);
    }

    function startOTPTimer() {
        otpTimerCount = 60;
        document.getElementById('resendOTPBtn').classList.add('uk-hidden');
        document.getElementById('otpTimer').classList.remove('uk-hidden');

        otpTimer = setInterval(() => {
            otpTimerCount--;
            document.getElementById('timerCount').textContent = otpTimerCount;

            if (otpTimerCount <= 0) {
                clearInterval(otpTimer);
                document.getElementById('resendOTPBtn').classList.remove('uk-hidden');
                document.getElementById('otpTimer').classList.add('uk-hidden');
            }
        }, 1000);
    }

    function resendOTP() {
        const newPhone = document.getElementById('newPhoneNumber').value;

        // Simulate resending OTP
        UIkit.notification({
            message: 'OTP resent successfully!',
            status: 'success',
            pos: 'top-center',
            timeout: 3000
        });

        // Clear OTP input
        document.getElementById('otpCode').value = '';

        // Restart timer
        startOTPTimer();
    }

    function verifyOTP() {
        const otpCode = document.getElementById('otpCode').value.trim();

        if (!otpCode || otpCode.length !== 6) {
            UIkit.notification({
                message: 'Please enter a valid 6-digit OTP',
                status: 'warning',
                pos: 'top-center',
                timeout: 3000
            });
            return;
        }

        // Show loading state
        const verifyBtn = event.target;
        const originalText = verifyBtn.textContent;
        verifyBtn.textContent = 'Verifying...';
        verifyBtn.disabled = true;

        // Simulate OTP verification
        setTimeout(() => {
            // Simulate verification result (you would check with your backend)
            const isValidOTP = otpCode === '123456' || Math.random() > 0.3; // Demo purposes

            if (isValidOTP) {
                // Update the main phone number field
                const newPhone = document.getElementById('newPhoneNumber').value;
                document.getElementById('phone').value = newPhone;

                // Close modal
                UIkit.modal('#trainerPhoneChangeModal').hide();

                // Clear timer
                if (otpTimer) {
                    clearInterval(otpTimer);
                }

                // Reset modal to step 1
                resetPhoneModal();

                UIkit.notification({
                    message: 'Phone number updated successfully!',
                    status: 'success',
                    pos: 'top-center',
                    timeout: 3000
                });
            } else {
                UIkit.notification({
                    message: 'Invalid OTP. Please try again.',
                    status: 'danger',
                    pos: 'top-center',
                    timeout: 3000
                });
            }

            // Reset button
            verifyBtn.textContent = originalText;
            verifyBtn.disabled = false;
        }, 1500);
    }

    function goBackToPhoneStep() {
        document.getElementById('trainerPhoneStep2').classList.add('uk-hidden');
        document.getElementById('trainerPhoneStep1').classList.remove('uk-hidden');

        // Clear timer
        if (otpTimer) {
            clearInterval(otpTimer);
        }

        // Clear OTP input
        document.getElementById('otpCode').value = '';
    }

    function resetPhoneModal() {
        // Reset to step 1
        document.getElementById('trainerPhoneStep2').classList.add('uk-hidden');
        document.getElementById('trainerPhoneStep1').classList.remove('uk-hidden');

        // Clear inputs
        document.getElementById('newPhoneNumber').value = '';
        document.getElementById('otpCode').value = '';

        // Clear timer
        if (otpTimer) {
            clearInterval(otpTimer);
        }

        // Reset timer display
        document.getElementById('resendOTPBtn').classList.remove('uk-hidden');
        document.getElementById('otpTimer').classList.add('uk-hidden');
    }

    // Auto-format OTP input
    document.addEventListener('DOMContentLoaded', function() {
        const otpInput = document.getElementById('otpCode');
        if (otpInput) {
            otpInput.addEventListener('input', function(e) {
                // Only allow numbers
                this.value = this.value.replace(/[^0-9]/g, '');

                // Auto-submit when 6 digits are entered
                if (this.value.length === 6) {
                    setTimeout(() => verifyOTP(), 500);
                }
            });
        }
    });

    // END: Phone Number Change Functions

    // Initialize file upload handlers
    setupFileUpload('profilePictureUpload', 'profilePictureInput', 'profilePicturePreview', false);
    setupFileUpload('introVideoUpload', 'introVideoInput', 'introVideoPreview', true);

    // Initialize language display (empty)
    updateLanguageDisplay();


    document.getElementById('personalInfoForm').addEventListener('submit', function(e) {
        e.preventDefault(); // Prevent default form submission

        // Show loading notification
        UIkit.notification({
            message: 'Saving your information...',
            status: 'primary',
            pos: 'top-center',
            timeout: 2000
        });

        // Get form data
        const formData = {
            firstName: document.getElementById('firstName').value,
            lastName: document.getElementById('lastName').value,
            email: document.getElementById('email').value,
            phone: document.getElementById('phone').value,
            gender: document.getElementById('gender').value,
            experience: document.getElementById('experience').value,
            description: document.getElementById('description').value,
            languages: selectedLanguages,
            profilePicture: document.getElementById('profilePictureInput').files[0] || null,
            introVideo: document.getElementById('introVideoInput').files[0] || null
        };

        // Simulate API call (replace with your actual API endpoint)
        setTimeout(() => {
            UIkit.notification({
                message: 'Profile updated successfully!',
                status: 'success',
                pos: 'top-center',
                timeout: 4000
            });

            console.log('Form data:', formData);
        }, 1500);

    });
</script>

<?php include 'footer.php'; ?>
