@extends('layouts.admin-simple')

@section('title', 'Profile Settings')
@section('page-title', 'Profile Settings')

@section('breadcrumb')
    <li class="breadcrumb-item active">Profile Settings</li>
@endsection

@section('content')
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex align-items-center">
                <div class="flex">
                    <h4 class="card-title">Profile Settings</h4>
                    <p class="card-subtitle text-muted">Manage your account information and preferences</p>
                </div>
            </div>
            <div class="card-body">
                <!-- Profile Tabs -->
                <ul class="nav nav-tabs" id="profileTabs" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" id="personal-tab" data-toggle="tab" href="#personal" role="tab">
                            <i class="material-icons mr-2">person</i>Personal Information
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="security-tab" data-toggle="tab" href="#security" role="tab">
                            <i class="material-icons mr-2">security</i>Security
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="avatar-tab" data-toggle="tab" href="#avatar" role="tab">
                            <i class="material-icons mr-2">photo_camera</i>Avatar
                        </a>
                    </li>
                </ul>

                <div class="tab-content mt-4" id="profileTabsContent">
                    <!-- Personal Information Tab -->
                    <div class="tab-pane fade show active" id="personal" role="tabpanel">
                        <form id="profileForm" enctype="multipart/form-data">
                            @csrf
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="first_name">First Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="first_name" name="first_name" 
                                               value="{{ $user->first_name }}" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="last_name">Last Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="last_name" name="last_name" 
                                               value="{{ $user->last_name }}" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="email">Email Address <span class="text-danger">*</span></label>
                                        <input type="email" class="form-control" id="email" name="email" 
                                               value="{{ $user->email }}" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="phone">Phone Number</label>
                                        <input type="text" class="form-control" id="phone" name="phone" 
                                               value="{{ $user->phone }}">
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="department">Department</label>
                                        <input type="text" class="form-control" id="department" name="department" 
                                               value="{{ $user->department }}" readonly>
                                        <small class="form-text text-muted">Contact administrator to change department</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="employee_id">Employee ID</label>
                                        <input type="text" class="form-control" id="employee_id" name="employee_id" 
                                               value="{{ $user->employee_id }}" readonly>
                                        <small class="form-text text-muted">Employee ID cannot be changed</small>
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <i class="material-icons mr-1">save</i>Save Changes
                            </button>
                        </form>
                    </div>

                    <!-- Security Tab -->
                    <div class="tab-pane fade" id="security" role="tabpanel">
                        <form id="passwordForm">
                            @csrf
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="current_password">Current Password <span class="text-danger">*</span></label>
                                        <input type="password" class="form-control" id="current_password" name="current_password" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="password">New Password <span class="text-danger">*</span></label>
                                        <input type="password" class="form-control" id="password" name="password" required>
                                        <div class="invalid-feedback"></div>
                                        <small class="form-text text-muted">
                                            Password must be at least 8 characters long and contain uppercase, lowercase, numbers, and symbols
                                        </small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="password_confirmation">Confirm New Password <span class="text-danger">*</span></label>
                                        <input type="password" class="form-control" id="password_confirmation" name="password_confirmation" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <i class="material-icons mr-1">lock</i>Update Password
                            </button>
                        </form>
                    </div>

                    <!-- Avatar Tab -->
                    <div class="tab-pane fade" id="avatar" role="tabpanel">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="text-center">
                                    <div class="avatar-preview mb-3">
                                        @if($user->avatar)
                                            <img src="{{ Storage::disk('public')->url($user->avatar) }}" 
                                                 alt="Avatar" class="rounded-circle" width="150" height="150" 
                                                 style="object-fit: cover;" id="avatarPreview">
                                        @else
                                            <div class="rounded-circle d-flex align-items-center justify-content-center" 
                                                 style="width: 150px; height: 150px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); margin: 0 auto;" 
                                                 id="avatarPreview">
                                                <span class="text-white" style="font-size: 3rem; font-weight: 600;">
                                                    {{ substr($user->name ?? 'A', 0, 1) }}
                                                </span>
                                            </div>
                                        @endif
                                    </div>
                                    <p class="text-muted">
                                        Upload a new avatar (Max: 2MB)<br>
                                        Accepted formats: JPG, PNG, GIF
                                    </p>
                                </div>
                            </div>
                            <div class="col-md-8">
                                <form id="avatarForm" enctype="multipart/form-data">
                                    @csrf
                                    <div class="form-group">
                                        <label for="avatar">Choose Avatar</label>
                                        <input type="file" class="form-control-file" id="avatar" name="avatar" 
                                               accept="image/jpeg,image/png,image/jpg,image/gif">
                                        <div class="invalid-feedback"></div>
                                    </div>
                                    <div class="btn-group">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="material-icons mr-1">cloud_upload</i>Upload Avatar
                                        </button>
                                        @if($user->avatar)
                                            <button type="button" class="btn btn-outline-danger" id="removeAvatarBtn">
                                                <i class="material-icons mr-1">delete</i>Remove Avatar
                                            </button>
                                        @endif
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    // Profile Form Submit
    $('#profileForm').on('submit', function(e) {
        e.preventDefault();
        
        const form = $(this);
        const submitBtn = form.find('button[type="submit"]');
        const originalText = submitBtn.html();
        
        // Clear previous errors
        form.find('.is-invalid').removeClass('is-invalid');
        form.find('.invalid-feedback').text('');
        
        // Show loading state
        submitBtn.prop('disabled', true).html('<i class="material-icons mr-1">hourglass_empty</i>Saving...');
        
        $.ajax({
            url: '{{ route("admin.profile.update") }}',
            type: 'POST',
            data: form.serialize(),
            success: function(response) {
                if (response.success) {
                    showToastMessage(response.message, 'success');
                    // Update the header display name if changed
                    const fullName = $('#first_name').val() + ' ' + $('#last_name').val();
                    $('.profile-name').text(fullName);
                    $('.user-details h6').text(fullName);
                }
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    Object.keys(errors).forEach(function(key) {
                        const input = form.find(`[name="${key}"]`);
                        input.addClass('is-invalid');
                        input.siblings('.invalid-feedback').text(errors[key][0]);
                    });
                } else {
                    showToastMessage('An error occurred while updating profile', 'error');
                }
            },
            complete: function() {
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    // Password Form Submit
    $('#passwordForm').on('submit', function(e) {
        e.preventDefault();
        
        const form = $(this);
        const submitBtn = form.find('button[type="submit"]');
        const originalText = submitBtn.html();
        
        // Clear previous errors
        form.find('.is-invalid').removeClass('is-invalid');
        form.find('.invalid-feedback').text('');
        
        // Show loading state
        submitBtn.prop('disabled', true).html('<i class="material-icons mr-1">hourglass_empty</i>Updating...');
        
        $.ajax({
            url: '{{ route("admin.profile.password") }}',
            type: 'POST',
            data: form.serialize(),
            success: function(response) {
                if (response.success) {
                    showToastMessage(response.message, 'success');
                    form[0].reset();
                }
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    if (xhr.responseJSON.errors) {
                        const errors = xhr.responseJSON.errors;
                        Object.keys(errors).forEach(function(key) {
                            const input = form.find(`[name="${key}"]`);
                            input.addClass('is-invalid');
                            input.siblings('.invalid-feedback').text(errors[key][0]);
                        });
                    } else {
                        showToastMessage(xhr.responseJSON.message, 'error');
                    }
                } else {
                    showToastMessage('An error occurred while updating password', 'error');
                }
            },
            complete: function() {
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    // Avatar Form Submit
    $('#avatarForm').on('submit', function(e) {
        e.preventDefault();
        
        const form = $(this);
        const formData = new FormData(this);
        const submitBtn = form.find('button[type="submit"]');
        const originalText = submitBtn.html();
        
        // Clear previous errors
        form.find('.is-invalid').removeClass('is-invalid');
        form.find('.invalid-feedback').text('');
        
        // Show loading state
        submitBtn.prop('disabled', true).html('<i class="material-icons mr-1">hourglass_empty</i>Uploading...');
        
        $.ajax({
            url: '{{ route("admin.profile.avatar") }}',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    showToastMessage(response.message, 'success');
                    if (response.avatar_url) {
                        // Update avatar preview
                        $('#avatarPreview').html(`<img src="${response.avatar_url}" alt="Avatar" class="rounded-circle" width="150" height="150" style="object-fit: cover;">`);
                        // Update header avatar
                        $('.avatar-text').parent().html(`<img src="${response.avatar_url}" alt="Avatar" class="rounded-circle" width="32" height="32" style="object-fit: cover;">`);
                        $('.avatar-large .avatar-text').parent().html(`<img src="${response.avatar_url}" alt="Avatar" class="rounded-circle" width="48" height="48" style="object-fit: cover;">`);
                        // Show remove button if not already present
                        if (!$('#removeAvatarBtn').length) {
                            form.find('.btn-group').append('<button type="button" class="btn btn-outline-danger" id="removeAvatarBtn"><i class="material-icons mr-1">delete</i>Remove Avatar</button>');
                        }
                    }
                    form[0].reset();
                }
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    if (xhr.responseJSON.errors) {
                        const errors = xhr.responseJSON.errors;
                        Object.keys(errors).forEach(function(key) {
                            const input = form.find(`[name="${key}"]`);
                            input.addClass('is-invalid');
                            input.siblings('.invalid-feedback').text(errors[key][0]);
                        });
                    } else {
                        showToastMessage(xhr.responseJSON.message, 'error');
                    }
                } else {
                    showToastMessage('An error occurred while uploading avatar', 'error');
                }
            },
            complete: function() {
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    // Remove Avatar
    $(document).on('click', '#removeAvatarBtn', function() {
        if (confirm('Are you sure you want to remove your avatar?')) {
            const btn = $(this);
            const originalText = btn.html();
            
            btn.prop('disabled', true).html('<i class="material-icons mr-1">hourglass_empty</i>Removing...');
            
            $.ajax({
                url: '{{ route("admin.profile.avatar.remove") }}',
                type: 'DELETE',
                data: {
                    _token: '{{ csrf_token() }}'
                },
                success: function(response) {
                    if (response.success) {
                        showToastMessage(response.message, 'success');
                        // Reset to default avatar
                        const initials = '{{ substr($user->name ?? "A", 0, 1) }}';
                        $('#avatarPreview').html(`<div class="rounded-circle d-flex align-items-center justify-content-center" style="width: 150px; height: 150px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); margin: 0 auto;"><span class="text-white" style="font-size: 3rem; font-weight: 600;">${initials}</span></div>`);
                        // Update header avatar
                        $('.profile-avatar').html(`<span class="avatar-text">${initials}</span>`);
                        $('.avatar-large').html(`<span class="avatar-text">${initials}</span>`);
                        // Remove the remove button
                        btn.remove();
                    }
                },
                error: function() {
                    showToastMessage('An error occurred while removing avatar', 'error');
                },
                complete: function() {
                    btn.prop('disabled', false).html(originalText);
                }
            });
        }
    });
    
    // Preview uploaded image
    $('#avatar').on('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#avatarPreview').html(`<img src="${e.target.result}" alt="Avatar Preview" class="rounded-circle" width="150" height="150" style="object-fit: cover;">`);
            };
            reader.readAsDataURL(file);
        }
    });
});
</script>
@endpush