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

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

<div class="uk-container">

    <!-- 
                Hidden heading added for semantic structure and SEO/accessibility.
                Keeps heading order sequential without affecting visual design.
            -->
    <h2 class="sr-only">User Profile</h2>

    <!-- Dashboard Cards Section -->
    <div class="uk-grid uk-grid-small uk-child-width-auto uk-flex-center uk-child-width-1-5@l uk-margin-medium-bottom uk-grid-match" uk-grid>

        <!-- Transaction History -->
        <div class="uk-first-column">
            <a href="user-dashboard-wallet.php" class="dashboard-card uk-text-center uk-display-block uk-link-reset">
                <div class="card-icon uk-margin-small-bottom">
                    <span uk-icon="icon: wallet; ratio: 1.6" class="uk-icon"></span>
                </div>
                <h3 class="card-title uk-margin-small-bottom uk-flex-center uk-visible@m">My Wallet</h3>
            </a>
        </div>

        <!-- My Sessions -->
        <div>
            <a href="user-dashboard-my-sessions.php" class="dashboard-card uk-text-center uk-display-block uk-link-reset">
                <div class="card-icon uk-margin-small-bottom">
                    <span uk-icon="icon: sessions; ratio: 1.6" class="uk-icon"></span>
                </div>
                <h3 class="card-title uk-margin-small-bottom uk-flex-center uk-visible@m">My Sessions</h3>
            </a>
        </div>

        <!-- Notifications -->
        <div>
            <a href="user-dashboard-notifications.php" class="dashboard-card uk-text-center uk-display-block uk-link-reset">
                <div class="card-icon uk-margin-small-bottom">
                    <span uk-icon="icon: bell; ratio: 1.6" class="uk-icon"></span>
                </div>
                <h3 class="card-title uk-margin-small-bottom uk-flex-center uk-visible@m">Notifications</h3>
            </a>
        </div>

        <!-- Favorite Trainers -->
        <div>
            <a href="user-dashboard-favorite-trainers.php" class="dashboard-card uk-text-center uk-display-block uk-link-reset">
                <div class="card-icon uk-margin-small-bottom">
                    <span uk-icon="icon: heart; ratio: 1.6" class="uk-icon"></span>
                </div>
                <h3 class="card-title uk-margin-small-bottom uk-flex-center uk-visible@m">Favorite Trainers</h3>
            </a>
        </div>

        <!-- Transaction Log -->
        <div>
            <a href="user-dashboard-log.php" class="dashboard-card uk-text-center uk-display-block uk-link-reset">
                <div class="card-icon uk-margin-small-bottom">
                    <span uk-icon="icon: text; ratio: 1.6" class="uk-icon"></span>
                </div>
                <h3 class="card-title uk-margin-small-bottom uk-flex-center uk-visible@m">Transaction Log</h3>
            </a>
        </div>

    </div>

    <!-- Phone Number Change Modal -->
    <div id="phoneChangeModal" 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="phoneStep1" 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('#phoneChangeModal').hide()">Cancel</button>
                    <button type="button" class="uk-button uk-button-primary" onclick="sendOTP()">Send OTP</button>
                </div>
            </div>

            <div id="phoneStep2" 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>

                <!-- CV Upload -->
                <div class="uk-width-1-2@s">
                    <div class="form-group">
                        <label class="form-label" for="cvInput">Upload CV</label>
                        <div class="upload-container">
                            <div class="upload-area" id="cvUpload">
                                <div class="upload-icon"><span uk-icon="icon: file-text; ratio: 1.6" class="uk-icon" aria-hidden="true"></span></div>
                                <div class="upload-text">Upload your CV</div>
                                <div class="upload-subtext">PDF, DOC files up to 10MB</div>
                            </div>
                            <input type="file" id="cvInput" class="hidden" accept=".pdf,.doc,.docx">
                            <div id="cvPreview" 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="Sara" 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="Mohammed" required>
                    </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 55 123 4567" readonly style="flex: 1;">
                            <button type="button" class="uk-button uk-button-default" onclick="UIkit.modal('#phoneChangeModal').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>

                <!-- Career Goal -->
                <div class="uk-width-1-2@s">
                    <div class="form-group">
                        <label class="form-label" for="careerGoal">Career Goal</label>
                        <input type="text" class="uk-input" id="careerGoal" value="Software Engineer" placeholder="e.g. Software Engineer, Marketing Manager">
                    </div>
                </div>

                <!-- Language Preference -->
                <div class="uk-width-1-2@s">
                    <div class="form-group">
                        <label class="form-label" for="languagePreference">Language Preference</label>
                        <select class="uk-select" id="languagePreference">
                            <option value="en" selected>English</option>
                            <option value="ar">Arabic</option>
                        </select>
                    </div>
                </div>

                <!-- Notification Toggle -->
                <div class="uk-width-1-2@s">

                    <div class="form-group">
                        <div class="form-label">
                            Notifications
                        </div>
                        <div class="uk-flex uk-flex-middle">
                            <label class="uk-switch" for="availabilityToggle">
                                <input type="checkbox" id="availabilityToggle" aria-label="Availability status toggle" checked="">
                                <div class="uk-switch-slider"></div>
                            </label>
                            <span class="uk-margin-small-left" id="availabilityStatus" style="color: var(--success-color);">Receive notifications</span>
                        </div>
                    </div>

                </div>

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

            </div>
        </form>

    </div>

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


<script>
    let otpTimer;
    let otpTimerCount = 60;

    // File upload handlers
    function setupFileUpload(uploadAreaId, inputId, previewId, isDocument = 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, isDocument);
            }
        });

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

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

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

            if (isDocument) {
                // For documents (CV), show file info instead of preview
                previewElement = `
                    <div class="document-preview">
                        <div class="document-icon"><span uk-icon="icon: file-text; ratio: 2" class="uk-icon"></span></div>
                        <div class="document-info">
                            <div class="document-name">${file.name}</div>
                            <div class="document-size">${(file.size / 1024 / 1024).toFixed(2)} MB</div>
                        </div>
                    </div>
                `;
            } else {
                // For images, show image preview
                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: ${isDocument ? 'text' : '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');
        };

        if (isDocument) {
            // For documents, we don't need to read as data URL
            reader.onload();
        } else {
            // For images, read as data URL to show preview
            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();
    }

    // Phone Number Change Functions
    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('phoneStep1').classList.add('uk-hidden');
            document.getElementById('phoneStep2').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('#phoneChangeModal').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('phoneStep2').classList.add('uk-hidden');
        document.getElementById('phoneStep1').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('phoneStep2').classList.add('uk-hidden');
        document.getElementById('phoneStep1').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');
        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);
            }
        });
    });

    // Initialize file upload handlers
    setupFileUpload('profilePictureUpload', 'profilePictureInput', 'profilePicturePreview', false);
    setupFileUpload('cvUpload', 'cvInput', 'cvPreview', true);

    // Form submission handler
    document.getElementById('personalInfoForm').addEventListener('submit', function(e) {
        e.preventDefault();

        // Collect form data
        const formData = new FormData();
        formData.append('firstName', document.getElementById('firstName').value);
        formData.append('lastName', document.getElementById('lastName').value);
        formData.append('phone', document.getElementById('phone').value);
        formData.append('careerGoal', document.getElementById('careerGoal').value);
        formData.append('languagePreference', document.getElementById('languagePreference').value);
        formData.append('notificationsEnabled', document.getElementById('notificationsEnabled').checked);

        // Add files if selected
        const profilePicture = document.getElementById('profilePictureInput').files[0];
        if (profilePicture) {
            formData.append('profilePicture', profilePicture);
        }

        const cv = document.getElementById('cvInput').files[0];
        if (cv) {
            formData.append('cv', cv);
        }

        // Here you would send the data to your backend
        console.log('Form submitted with data:', formData);

        // Show success message
        UIkit.notification({
            message: 'Profile updated successfully!',
            status: 'success',
            pos: 'top-center',
            timeout: 2000
        });
    });
</script>

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