@extends('front_end.pages.settings.layout')

@section('title', 'Account Settings - Socialink')
@php
    $showLeftSidebar = false;
    $showRightSidebar = false;
@endphp

@section('settings_content')
<div class="card mb-4">
    <div class="card-header with-icon p-4">
        <div class="main-icon">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M490.667 405.333h-56.811C424.619 374.592 396.373 352 362.667 352s-61.931 22.592-71.189 53.333H21.333C9.557 405.333 0 414.891 0 426.667S9.557 448 21.333 448h270.144c9.237 30.741 37.483 53.333 71.189 53.333s61.931-22.592 71.189-53.333h56.811c11.797 0 21.333-9.557 21.333-21.333s-9.535-21.334-21.332-21.334zm-128 53.334c-17.643 0-32-14.357-32-32s14.357-32 32-32 32 14.357 32 32-14.358 32-32 32zM490.667 64h-56.811c-9.259-30.741-37.483-53.333-71.189-53.333S300.736 33.259 291.477 64H21.333C9.557 64 0 73.557 0 85.333s9.557 21.333 21.333 21.333h270.144C300.736 137.408 328.96 160 362.667 160s61.931-22.592 71.189-53.333h56.811c11.797 0 21.333-9.557 21.333-21.333S502.464 64 490.667 64zm-128 53.333c-17.643 0-32-14.357-32-32s14.357-32 32-32 32 14.357 32 32-14.358 32-32 32zM490.667 234.667H220.523c-9.259-30.741-37.483-53.333-71.189-53.333s-61.931 22.592-71.189 53.333H21.333C9.557 234.667 0 244.224 0 256c0 11.776 9.557 21.333 21.333 21.333h56.811c9.259 30.741 37.483 53.333 71.189 53.333s61.931-22.592 71.189-53.333h270.144c11.797 0 21.333-9.557 21.333-21.333.001-11.776-9.535-21.333-21.332-21.333zM149.333 288c-17.643 0-32-14.357-32-32s14.357-32 32-32 32 14.357 32 32-14.357 32-32 32z" fill="currentColor"/></svg>
        </div>
        <h5 class="mb-0 ms-2">Account Settings</h5>
    </div>
    <div class="card-body p-4">
        @if(session('success'))
        <div class="alert alert-success mb-4">
            {{ session('success') }}
        </div>
        @endif

        @if(session('error'))
        <div class="alert alert-danger mb-4">
            {{ session('error') }}
        </div>
        @endif

        <div class="row mb-4">
            <div class="col-md-3 text-center">
                <div class="profile-picture-container mb-3">
                    <img src="{{ Auth::check() ? getMedia(Auth::user()->avatar) : asset('assets/images/avatar/07.jpg') }}" 
                         alt="{{ auth()->user()->name }}" 
                         class="rounded-circle img-fluid" 
                         style="width: 150px; height: 150px; object-fit: cover;">
                </div>
                <form action="{{ route('settings.account.update_picture') }}" method="POST" enctype="multipart/form-data" id="profile-picture-form">
                    @csrf
                    <div class="mb-3">
                        <label for="profile_picture" class="btn btn-sm btn-outline-primary">Change Picture</label>
                        <input type="file" class="d-none" id="profile_picture" name="profile_picture" accept="image/*" onchange="document.getElementById('profile-picture-form').submit()">
                    </div>
                </form>
                <small class="text-muted">Recommended size: 300x300 pixels</small>
            </div>
            <div class="col-md-9">
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    Your account was created on <strong>{{ auth()->user()->created_at->format('F d, Y') }}</strong>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <h5 class="mb-1">{{ auth()->user()->name }}</h5>
                        <p class="text-muted mb-0">@ {{ auth()->user()->username }}</p>
                    </div>
                    <div>
                        <a href="{{ route('settings.security', ['section' => 'two-factor']) }}" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-shield-alt me-1"></i> Security Settings
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <form action="{{ route('settings.account.update') }}" method="POST" novalidate>            
            @csrf
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label class="form-label" for="username">Username</label>
                        <input type="text" class="form-control @error('username') is-invalid @enderror" id="username" name="username" value="{{ old('username', auth()->user()->username) }}">
                        @error('username')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="form-text text-muted">Your username is how people find you on Socialink.</small>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label class="form-label" for="email">Email Address</label>
                        <input type="email" class="form-control @error('email') is-invalid @enderror" id="email" name="email" value="{{ old('email', auth()->user()->email) }}">
                        @error('email')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="form-text text-muted">We'll send important updates to this address.</small>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label class="form-label" for="phone">Phone Number</label>
                        <input type="tel" class="form-control @error('phone') is-invalid @enderror" id="phone" name="phone" value="{{ old('phone', auth()->user()->phone ?? '') }}">
                        @error('phone')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="form-text text-muted">For account security and notifications.</small>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label class="form-label" for="language">Language</label>
                        <select class="form-select @error('language') is-invalid @enderror" id="language" name="language">
                            <option value="en" {{ old('language', auth()->user()->language ?? 'en') == 'en' ? 'selected' : '' }}>English</option>
                            <option value="es" {{ old('language', auth()->user()->language ?? 'en') == 'es' ? 'selected' : '' }}>Spanish</option>
                            <option value="fr" {{ old('language', auth()->user()->language ?? 'en') == 'fr' ? 'selected' : '' }}>French</option>
                            <option value="de" {{ old('language', auth()->user()->language ?? 'en') == 'de' ? 'selected' : '' }}>German</option>
                            <option value="ar" {{ old('language', auth()->user()->language ?? 'en') == 'ar' ? 'selected' : '' }}>Arabic</option>
                        </select>
                        @error('language')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="form-text text-muted">Select your preferred language for the platform.</small>
                    </div>
                </div>
            </div>

            <hr class="my-4">

            <h6 class="heading-small mb-3">Time Zone Settings</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label class="form-label" for="timezone">Time Zone</label>
                        <select class="form-select @error('timezone') is-invalid @enderror" id="timezone" name="timezone">
                            <option value="UTC" {{ old('timezone', auth()->user()->timezone ?? 'UTC') == 'UTC' ? 'selected' : '' }}>UTC (Coordinated Universal Time)</option>
                            <option value="America/New_York" {{ old('timezone', auth()->user()->timezone ?? 'UTC') == 'America/New_York' ? 'selected' : '' }}>Eastern Time (US & Canada)</option>
                            <option value="America/Chicago" {{ old('timezone', auth()->user()->timezone ?? 'UTC') == 'America/Chicago' ? 'selected' : '' }}>Central Time (US & Canada)</option>
                            <option value="America/Denver" {{ old('timezone', auth()->user()->timezone ?? 'UTC') == 'America/Denver' ? 'selected' : '' }}>Mountain Time (US & Canada)</option>
                            <option value="America/Los_Angeles" {{ old('timezone', auth()->user()->timezone ?? 'UTC') == 'America/Los_Angeles' ? 'selected' : '' }}>Pacific Time (US & Canada)</option>
                            <option value="Europe/London" {{ old('timezone', auth()->user()->timezone ?? 'UTC') == 'Europe/London' ? 'selected' : '' }}>London</option>
                            <option value="Europe/Paris" {{ old('timezone', auth()->user()->timezone ?? 'UTC') == 'Europe/Paris' ? 'selected' : '' }}>Paris</option>
                            <option value="Asia/Tokyo" {{ old('timezone', auth()->user()->timezone ?? 'UTC') == 'Asia/Tokyo' ? 'selected' : '' }}>Tokyo</option>
                            <option value="Australia/Sydney" {{ old('timezone', auth()->user()->timezone ?? 'UTC') == 'Australia/Sydney' ? 'selected' : '' }}>Sydney</option>
                        </select>
                        @error('timezone')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label class="form-label" for="date_format">Date Format</label>
                        <select class="form-select @error('date_format') is-invalid @enderror" id="date_format" name="date_format">
                            <option value="Y-m-d" {{ old('date_format', auth()->user()->date_format ?? 'Y-m-d') == 'Y-m-d' ? 'selected' : '' }}>2023-12-31 (Year-Month-Day)</option>
                            <option value="m/d/Y" {{ old('date_format', auth()->user()->date_format ?? 'Y-m-d') == 'm/d/Y' ? 'selected' : '' }}>12/31/2023 (Month/Day/Year)</option>
                            <option value="d/m/Y" {{ old('date_format', auth()->user()->date_format ?? 'Y-m-d') == 'd/m/Y' ? 'selected' : '' }}>31/12/2023 (Day/Month/Year)</option>
                            <option value="d.m.Y" {{ old('date_format', auth()->user()->date_format ?? 'Y-m-d') == 'd.m.Y' ? 'selected' : '' }}>31.12.2023 (Day.Month.Year)</option>
                        </select>
                        @error('date_format')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>

            <hr class="my-4">

            <h6 class="heading-small mb-3">Social Account Links</h6>
            <p class="text-muted mb-4">Connect your other social media accounts to your Socialink profile.</p>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label class="form-label d-flex align-items-center">
                            <i class="fab fa-facebook text-primary me-2"></i>
                            Facebook
                        </label>
                        <div class="input-group">
                            <span class="input-group-text">facebook.com/</span>
                            <input type="text" class="form-control @error('facebook_username') is-invalid @enderror" id="facebook_username" name="facebook_username" value="{{ old('facebook_username', auth()->user()->facebook_username ?? '') }}">
                        </div>
                        @error('facebook_username')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label class="form-label d-flex align-items-center">
                            <i class="fab fa-twitter text-info me-2"></i>
                            Twitter
                        </label>
                        <div class="input-group">
                            <span class="input-group-text">twitter.com/</span>
                            <input type="text" class="form-control @error('twitter_username') is-invalid @enderror" id="twitter_username" name="twitter_username" value="{{ old('twitter_username', auth()->user()->twitter_username ?? '') }}">
                        </div>
                        @error('twitter_username')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label class="form-label d-flex align-items-center">
                            <i class="fab fa-instagram text-danger me-2"></i>
                            Instagram
                        </label>
                        <div class="input-group">
                            <span class="input-group-text">instagram.com/</span>
                            <input type="text" class="form-control @error('instagram_username') is-invalid @enderror" id="instagram_username" name="instagram_username" value="{{ old('instagram_username', auth()->user()->instagram_username ?? '') }}">
                        </div>
                        @error('instagram_username')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label class="form-label d-flex align-items-center">
                            <i class="fab fa-linkedin text-primary me-2"></i>
                            LinkedIn
                        </label>
                        <div class="input-group">
                            <span class="input-group-text">linkedin.com/in/</span>
                            <input type="text" class="form-control @error('linkedin_username') is-invalid @enderror" id="linkedin_username" name="linkedin_username" value="{{ old('linkedin_username', auth()->user()->linkedin_username ?? '') }}">
                        </div>
                        @error('linkedin_username')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>
        </div>
        <div class="card-footer text-end p-4">
            <button type="submit" class="btn btn-primary">Save Changes</button>
        </div>
    </form>
</div>

<div class="card">
    <div class="card-header with-icon p-4">
        <div class="main-icon">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3H6a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h4M16 17l5-5-5-5M19.8 12H9"/></svg>
        </div>
        <h5 class="mb-0 ms-2 text-danger">Deactivate Account</h5>
    </div>
    <div class="card-body p-4">
        <p class="text-muted">Temporarily deactivate your account. Your profile and content will be hidden until you log in again.</p>
        <p><strong>Note:</strong> This action will temporarily hide your profile from other users, but your data will remain in our system.</p>
        
        <form action="{{ route('settings.account.deactivate') }}" method="POST">
            @csrf
            <div class="form-check mb-3">
                <input class="form-check-input" type="checkbox" id="deactivate_confirm" name="deactivate_confirm" required>
                <label class="form-check-label" for="deactivate_confirm">
                    I understand that my account will be temporarily deactivated
                </label>
            </div>
            <button type="submit" class="btn btn-outline-danger">Deactivate Account</button>
        </form>
    </div>
</div>

<style>
.is-invalid {
    border-color: #dc3545 !important;
    padding-right: calc(1.5em + 0.75rem);
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right calc(0.375em + 0.1875rem) center;
    background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.invalid-feedback {
    color: #dc3545;
    font-size: 0.875em;
    margin-top: 0.25rem;
}

.is-valid {
    border-color: #198754 !important;
    padding-right: calc(1.5em + 0.75rem);
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right calc(0.375em + 0.1875rem) center;
    background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.valid-feedback {
    color: #198754;
    font-size: 0.875em;
    margin-top: 0.25rem;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('form[action="{{ route('settings.account.update') }}"]');
    
    if (!form) return;

    // Validation rules
    const validationRules = {
        username: {
            required: true,
            minLength: 3,
            maxLength: 255,
            pattern: /^[a-zA-Z0-9_]+$/,
            message: {
                required: 'Username is required',
                minLength: 'Username must be at least 3 characters',
                maxLength: 'Username must not exceed 255 characters',
                pattern: 'Username can only contain letters, numbers, and underscores'
            }
        },
        email: {
            required: true,
            pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
            message: {
                required: 'Email address is required',
                pattern: 'Please enter a valid email address'
            }
        },
        phone: {
            required: false,
            pattern: /^[\d\s\+\-\(\)]+$/,
            minLength: 10,
            message: {
                pattern: 'Please enter a valid phone number',
                minLength: 'Phone number must be at least 10 digits'
            }
        },
        language: {
            required: true,
            message: {
                required: 'Please select a language'
            }
        },
        timezone: {
            required: true,
            message: {
                required: 'Please select a timezone'
            }
        },
        date_format: {
            required: true,
            message: {
                required: 'Please select a date format'
            }
        }
    };

    // Validate single field
    function validateField(field) {
        const fieldName = field.name;
        const fieldValue = field.value.trim();
        const rules = validationRules[fieldName];
        
        if (!rules) return true;

        // Clear previous validation
        clearFieldError(field);

        // Required validation
        if (rules.required && !fieldValue) {
            showFieldError(field, rules.message.required);
            return false;
        }

        // Skip other validations if field is empty and not required
        if (!rules.required && !fieldValue) {
            field.classList.add('is-valid');
            return true;
        }

        // Min length validation
        if (rules.minLength && fieldValue.length < rules.minLength) {
            showFieldError(field, rules.message.minLength);
            return false;
        }

        // Max length validation
        if (rules.maxLength && fieldValue.length > rules.maxLength) {
            showFieldError(field, rules.message.maxLength);
            return false;
        }

        // Pattern validation
        if (rules.pattern && !rules.pattern.test(fieldValue)) {
            showFieldError(field, rules.message.pattern);
            return false;
        }

        // Field is valid
        field.classList.add('is-valid');
        return true;
    }

    // Show field error
    function showFieldError(field, message) {
        field.classList.add('is-invalid');
        field.classList.remove('is-valid');
        
        // Find or create error message element
        let errorDiv = field.parentElement.querySelector('.invalid-feedback');
        
        // For input groups, look in the parent's parent
        if (!errorDiv && field.closest('.input-group')) {
            errorDiv = field.closest('.form-group').querySelector('.invalid-feedback');
        }
        
        if (!errorDiv) {
            errorDiv = document.createElement('div');
            errorDiv.className = 'invalid-feedback d-block';
            
            if (field.closest('.input-group')) {
                field.closest('.input-group').parentElement.appendChild(errorDiv);
            } else {
                field.parentElement.appendChild(errorDiv);
            }
        }
        
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
    }

    // Clear field error
    function clearFieldError(field) {
        field.classList.remove('is-invalid', 'is-valid');
        
        let errorDiv = field.parentElement.querySelector('.invalid-feedback');
        
        // For input groups
        if (!errorDiv && field.closest('.input-group')) {
            errorDiv = field.closest('.form-group').querySelector('.invalid-feedback');
        }
        
        if (errorDiv && !errorDiv.hasAttribute('data-laravel-error')) {
            errorDiv.textContent = '';
            errorDiv.style.display = 'none';
        }
    }

    // Mark Laravel errors
    document.querySelectorAll('.invalid-feedback').forEach(function(errorDiv) {
        if (errorDiv.textContent.trim()) {
            errorDiv.setAttribute('data-laravel-error', 'true');
        }
    });

    // Add real-time validation on blur
    const fieldsToValidate = ['username', 'email', 'phone', 'language', 'timezone', 'date_format'];
    
    fieldsToValidate.forEach(function(fieldName) {
        const field = form.querySelector('[name="' + fieldName + '"]');
        if (field) {
            // Validate on blur
            field.addEventListener('blur', function() {
                validateField(this);
            });

            // Clear error on input
            field.addEventListener('input', function() {
                if (this.classList.contains('is-invalid')) {
                    clearFieldError(this);
                }
            });
        }
    });

    // Form submission validation
    form.addEventListener('submit', function(e) {
        let isValid = true;
        let firstInvalidField = null;

        fieldsToValidate.forEach(function(fieldName) {
            const field = form.querySelector('[name="' + fieldName + '"]');
            if (field && !validateField(field)) {
                isValid = false;
                if (!firstInvalidField) {
                    firstInvalidField = field;
                }
            }
        });

        if (!isValid) {
            e.preventDefault();
            
            // Scroll to first error
            if (firstInvalidField) {
                firstInvalidField.focus();
                firstInvalidField.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
            
            // Show error notification
            // showNotification('Please correct the errors in the form before submitting.', 'error');
            
            return false;
        }
    });

    // Show notification function
    function showNotification(message, type) {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = 'alert alert-' + (type === 'error' ? 'danger' : 'success') + ' alert-dismissible fade show';
        notification.style.position = 'fixed';
        notification.style.top = '20px';
        notification.style.right = '20px';
        notification.style.zIndex = '9999';
        notification.style.minWidth = '300px';
        notification.innerHTML = `
            <strong>${type === 'error' ? 'Error!' : 'Success!'}</strong> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(notification);
        
        // Auto remove after 5 seconds
        setTimeout(function() {
            notification.remove();
        }, 5000);
    }

    // Username availability check (optional - debounced)
    const usernameField = form.querySelector('[name="username"]');
    if (usernameField) {
        let usernameTimeout;
        const currentUsername = '{{ auth()->user()->username }}';
        
        usernameField.addEventListener('input', function() {
            clearTimeout(usernameTimeout);
            const value = this.value.trim();
            
            if (value && value !== currentUsername && value.length >= 3) {
                usernameTimeout = setTimeout(function() {
                    // Here you could add AJAX call to check username availability
                    // For now, just validate format
                    validateField(usernameField);
                }, 500);
            }
        });
    }

    // Email validation enhancement
    const emailField = form.querySelector('[name="email"]');
    if (emailField) {
        let emailTimeout;
        const currentEmail = '{{ auth()->user()->email }}';
        
        emailField.addEventListener('input', function() {
            clearTimeout(emailTimeout);
            const value = this.value.trim();
            
            if (value && value !== currentEmail) {
                emailTimeout = setTimeout(function() {
                    validateField(emailField);
                }, 500);
            }
        });
    }
});
</script>
@endsection