@extends('layout.layout')
@php
    $title = 'Profil Pengguna';
    $subTitle = 'Kelola Profil Anda';
@endphp

@push('scripts')
    <script>
        // Upload Image functionality
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    $("#imagePreview").css("background-image", "url(" + e.target.result + ")");
                    $("#imagePreview").hide();
                    $("#imagePreview").fadeIn(650);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

        function uploadProfilePhoto(file) {
            // Double check if already uploading
            if (isUploading) {
                return;
            }

            const formData = new FormData();
            formData.append('profile_photo', file);
            formData.append('_token', '{{ csrf_token() }}');

            // Show loading
            const uploadLabel = $('label[for="imageUpload"]');
            const originalContent = uploadLabel.html();
            uploadLabel.html('<div class="spinner-border spinner-border-sm" role="status"></div>');

            $.ajax({
                url: '{{ route('profile.update-photo') }}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        // Update image preview
                        $("#imagePreview").css("background-image", "url(" + response.photo_url + ")");

                        // Show success message (only one)
                        showNotification('success', response.message);

                        // Clear file input to prevent duplicate uploads
                        $("#imageUpload").val('');
                    }
                },
                error: function(xhr) {
                    let errorMessage = 'Terjadi kesalahan saat mengupload foto.';
                    if (xhr.responseJSON && xhr.responseJSON.errors) {
                        const errors = xhr.responseJSON.errors;
                        if (errors.profile_photo) {
                            errorMessage = errors.profile_photo[0];
                        }
                    }
                    showNotification('error', errorMessage);

                    // Clear file input on error
                    $("#imageUpload").val('');
                },
                complete: function() {
                    // Restore button
                    uploadLabel.html(originalContent);

                    // Reset uploading flag
                    isUploading = false;
                }
            });
        }

        function showNotification(type, message) {
            // Remove ALL existing alerts to prevent duplicates
            $('.alert').remove();

            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            const iconClass = type === 'success' ? 'material-symbols:check-circle' : 'material-symbols:error';

            const notification = `
                <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                    <iconify-icon icon="${iconClass}" class="me-2"></iconify-icon>
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;

            // Add notification to the top of the profile settings card
            $('.col-lg-8 .card-body').prepend(notification);

            // Auto dismiss after 5 seconds
            setTimeout(function() {
                $('.alert').fadeOut(function() {
                    $(this).remove();
                });
            }, 5000);
        }

        let isUploading = false;

        $(document).ready(function() {
            $("#imageUpload").change(function() {
                const file = this.files[0];

                // Prevent multiple uploads
                if (isUploading) {
                    showNotification('error', 'Upload sedang berlangsung, harap tunggu...');
                    $(this).val(''); // Clear input
                    return;
                }

                if (file) {
                    // Validate file size (2MB)
                    if (file.size > 2 * 1024 * 1024) {
                        showNotification('error', 'Ukuran file maksimal 2MB.');
                        $(this).val(''); // Clear input
                        return;
                    }

                    // Validate file type
                    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
                    if (!allowedTypes.includes(file.type)) {
                        showNotification('error', 'Format file harus jpeg, png, jpg, atau gif.');
                        $(this).val(''); // Clear input
                        return;
                    }

                    // Clear any existing alerts before starting upload
                    $('.alert').remove();

                    // Set uploading flag
                    isUploading = true;

                    // Preview image
                    readURL(this);

                    // Upload image
                    uploadProfilePhoto(file);
                }
            });
        });
    </script>
@endpush

@section('content')

    <div class="row gy-4">
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-body text-center">
                    <!-- Profile Image -->
                    <div class="mb-3">
                        <div class="avatar-upload d-inline-block position-relative">
                            <div class="avatar-edit position-absolute bottom-0 end-0 z-1 cursor-pointer">
                                <input type='file' id="imageUpload" accept=".png,.jpg,.jpeg,.gif" hidden>
                                <label for="imageUpload"
                                    class="w-32-px h-32-px d-flex justify-content-center align-items-center bg-primary-50 text-primary-600 border border-primary-600 bg-hover-primary-100 text-lg rounded-circle">
                                    <iconify-icon icon="solar:camera-outline" class="icon"></iconify-icon>
                                </label>
                            </div>
                            <div class="avatar-preview">
                                @php
                                    $defaultPhoto = asset('assets/images/user-grid/user-grid-img14.png');
                                    $userPhoto = auth()->user()->profile_photo
                                        ? asset('storage/profile_photos/' . auth()->user()->profile_photo)
                                        : $defaultPhoto;
                                @endphp
                                <div id="imagePreview"
                                    style="border-radius: 50%; background-image: url('{{ $userPhoto }}'); background-size: cover; background-position: center; border: 3px solid #fff; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- User Info -->
                    <h5 class="mb-1">{{ auth()->user()->name ?? 'User' }}</h5>
                    <p class="text-muted mb-3">{{ auth()->user()->email ?? 'email@example.com' }}</p>

                    <!-- User Role -->
                    @if (auth()->user()->roles->count() > 0)
                        <div class="mb-3">
                            @foreach (auth()->user()->roles as $role)
                                <span class="badge bg-primary me-1">{{ $role->name }}</span>
                            @endforeach
                        </div>
                    @endif

                    <!-- Account Info -->
                    <div class="text-start">
                        <h6 class="text-primary mb-3">Informasi Akun</h6>
                        <div class="small text-muted">
                            <div class="d-flex justify-content-between mb-2">
                                <span>Bergabung:</span>
                                <span>{{ auth()->user()->created_at->format('d/m/Y') }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="card h-100">
                <div class="card-body">
                    <h5 class="card-title mb-4">Pengaturan Profil</h5>

                    <!-- Profile Actions -->
                    <div class="row g-3">
                        <div class="col-md-4">
                            <div class="card border-0 bg-light h-100">
                                <div
                                    class="card-body d-flex flex-column justify-content-center align-items-center text-center">
                                    <iconify-icon icon="solar:pen-linear" class="text-success fs-1 mb-3"></iconify-icon>
                                    <h6>Edit Profil</h6>
                                    <p class="text-muted small">Ubah nama dan username</p>
                                    <a href="{{ route('profile.edit') }}"
                                        class="d-flex justify-content-center align-items-center btn btn-success btn-sm">
                                        <iconify-icon icon="solar:pen-linear" class="me-1"></iconify-icon>
                                        Edit
                                    </a>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="card border-0 bg-light h-100">
                                <div
                                    class="card-body d-flex flex-column justify-content-center align-items-center text-center">
                                    <iconify-icon icon="solar:lock-password-linear"
                                        class="text-warning fs-1 mb-3"></iconify-icon>
                                    <h6>Ubah Password</h6>
                                    <p class="text-muted small">Ganti password akun</p>
                                    <a href="{{ route('profile.change-password') }}"
                                        class="d-flex justify-content-center align-items-center btn btn-warning btn-sm">
                                        <iconify-icon icon="solar:lock-password-linear" class="me-1"></iconify-icon>
                                        Ubah
                                    </a>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="card border-0 bg-light h-100">
                                <div
                                    class="card-body d-flex flex-column justify-content-center align-items-center text-center">
                                    <iconify-icon icon="solar:letter-linear" class="text-info fs-1 mb-3"></iconify-icon>
                                    <h6>Ubah Email</h6>
                                    <p class="text-muted small">Ganti alamat email</p>
                                    <a href="{{ route('profile.change-email') }}"
                                        class="d-flex justify-content-center align-items-center btn btn-info btn-sm">
                                        <iconify-icon icon="solar:letter-linear" class="me-1"></iconify-icon>
                                        Ubah
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Info -->
                    <div class="mt-4">
                        <div class="alert alert-info">
                            <iconify-icon icon="material-symbols:info" class="me-2"></iconify-icon>
                            <strong>Tips Keamanan:</strong>
                            <ul class="mb-0 mt-2">
                                <li>Gunakan password yang kuat dengan kombinasi huruf, angka, dan simbol</li>
                                <li>Perbarui informasi profil secara berkala</li>
                                <li>Jaga kerahasiaan informasi login Anda</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
