@extends('FrontUser.layouts.app')

@section('title', 'My Profile')

@section('content')
<div class="profile-page">
    <!-- Page Header -->
    <div class="page-header mb-4">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h2 class="page-title">My Profile</h2>
                <p class="page-subtitle">Manage your account information and settings</p>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-4">
            <div class="card profile-card">
                <div class="card-body text-center">
                    <div class="user-profile-header mb-4">
                        <div class="avatar-upload">
                            <div class="avatar-preview mb-3">
                                <div id="imagePreview" class="avatar-image">
                                    @if(Auth::user()->avatar && file_exists(public_path('storage/avatars/' . Auth::user()->avatar)))
                                        <img src="{{ asset('storage/avatars/' . Auth::user()->avatar) }}" alt="Profile Picture" id="previewImg">
                                    @else
                                        <div class="avatar-placeholder">
                                            <i class="fas fa-user"></i>
                                        </div>
                                    @endif
                                </div>
                            </div>
                            <div class="avatar-edit">
                                <form method="POST" action="{{ route('user.settings.avatar.upload') }}" enctype="multipart/form-data" id="avatarForm">
                                    @csrf
                                    <div class="file-upload-wrapper">
                                        <input type='file' name='avatar' id="imageUpload" accept=".png, .jpg, .jpeg" class="file-input" />
                                        <label for="imageUpload" class="file-upload-label">
                                            <i class="fas fa-camera"></i>
                                            <span>Choose Photo</span>
                                        </label>
                                    </div>
                                    <button type="submit" class="btn btn-primary btn-sm mt-3" id="uploadBtn" style="display: none;">
                                        <i class="fas fa-upload"></i> Upload Avatar
                                    </button>
                                </form>
                            </div>
                        </div>
                        <h3 class="mb-1">{{ Auth::user()->name }}</h3>
                        <p class="text-muted">{{ Auth::user()->company ?? 'N/A' }}</p>
                        <p class="text-muted">
                            <i class="fas fa-envelope me-2"></i> {{ Auth::user()->email }}
                        </p>
                        <p class="text-muted">
                            <i class="fas fa-phone me-2"></i> {{ Auth::user()->phone ?? 'N/A' }}
                        </p>
                    </div>
                </div>
            </div>

            <div class="card mt-4">
                <div class="card-header">
                    <h5>Account Information</h5>
                </div>
                <div class="card-body">
                    <div class="info-item">
                        <strong>User ID:</strong> 
                        <span class="float-end">USR-{{ Auth::user()->id }}</span>
                    </div>
                    <hr>
                    <div class="info-item">
                        <strong>Account Type:</strong> 
                        <span class="float-end badge bg-primary">{{ ucfirst(Auth::user()->role ?? 'user') }}</span>
                    </div>
                    <hr>
                    <div class="info-item">
                        <strong>Member Since:</strong> 
                        <span class="float-end">{{ Auth::user()->created_at->format('M d, Y') }}</span>
                    </div>
                    <hr>
                    <div class="info-item">
                        <strong>Last Login:</strong> 
                        <span class="float-end">{{ Auth::user()->updated_at->format('M d, Y') }}</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h5>Profile Information</h5>
                    <small class="text-muted">Profile details are managed by administrators. You can only update your avatar.</small>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Full Name</label>
                                <input type="text" class="form-control" value="{{ Auth::user()->name }}" readonly>
                                <small class="form-text text-muted">Contact admin to update</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Email Address</label>
                                <input type="email" class="form-control" value="{{ Auth::user()->email }}" readonly>
                                <small class="form-text text-muted">Contact admin to update</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Phone Number</label>
                                <input type="tel" class="form-control" value="{{ Auth::user()->contact_number ?? 'N/A' }}" readonly>
                                <small class="form-text text-muted">Contact admin to update</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Company</label>
                                <input type="text" class="form-control" value="{{ Auth::user()->company_name ?? 'N/A' }}" readonly>
                                <small class="form-text text-muted">Contact admin to update</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Business Type</label>
                                <input type="text" class="form-control" value="{{ ucfirst(Auth::user()->business_type ?? 'N/A') }}" readonly>
                                <small class="form-text text-muted">Contact admin to update</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Account Status</label>
                                <input type="text" class="form-control" value="{{ ucfirst(Auth::user()->status ?? 'N/A') }}" readonly>
                                <small class="form-text text-muted">Managed by admin</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Address</label>
                        <textarea class="form-control" rows="3" readonly>{{ Auth::user()->address ?? 'N/A' }}</textarea>
                        <small class="form-text text-muted">Contact admin to update</small>
                    </div>

                    @if(Auth::user()->license)
                    <div class="form-group">
                        <label class="form-label">License Information</label>
                        <div class="row">
                            <div class="col-md-6">
                                <input type="text" class="form-control" value="License Key: {{ substr(Auth::user()->license->key, 0, 8) }}..." readonly>
                            </div>
                            <div class="col-md-6">
                                <input type="text" class="form-control" value="Expires: {{ Auth::user()->license->expires_at->format('M d, Y') }}" readonly>
                            </div>
                        </div>
                        <small class="form-text text-muted">License managed by admin</small>
                    </div>
                    @endif
                </div>
            </div>

            <div class="card mt-4">
                <div class="card-header">
                    <h5>Change Password</h5>
                </div>
                <div class="card-body">
                    <form method="POST" action="{{ route('user.profile.password') }}">
                        @csrf
                        @method('PUT')
                        
                        <div class="form-group">
                            <label class="form-label">Current Password</label>
                            <input type="password" class="form-control" name="current_password" required>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label">New Password</label>
                                    <input type="password" class="form-control" name="new_password" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label">Confirm New Password</label>
                                    <input type="password" class="form-control" name="new_password_confirmation" required>
                                </div>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-warning">
                            <i class="fas fa-key"></i> Change Password
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const fileInput = document.getElementById('imageUpload');
    const preview = document.getElementById('imagePreview');
    const uploadBtn = document.getElementById('uploadBtn');
    const avatarForm = document.getElementById('avatarForm');

    fileInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // Validate file type
            if (!file.type.match('image.*')) {
                alert('Please select an image file.');
                return;
            }
            
            // Validate file size (max 2MB)
            if (file.size > 2 * 1024 * 1024) {
                alert('File size must be less than 2MB.');
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                preview.innerHTML = `<img src="${e.target.result}" alt="Profile Picture" id="previewImg">`;
                uploadBtn.style.display = 'inline-block';
            };
            reader.readAsDataURL(file);
        }
    });

    avatarForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';
        submitBtn.disabled = true;
        
        fetch(this.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', 'Avatar updated successfully!');
                uploadBtn.style.display = 'none';
                fileInput.value = '';
            } else {
                showNotification('error', data.message || 'Failed to update avatar.');
            }
        })
        .catch(error => {
            showNotification('error', 'An error occurred while uploading.');
        })
        .finally(() => {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        });
    });
});

function showNotification(type, message) {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 5000);
}
</script>
@endsection