@extends('dashboard.base')

@section('title', 'Profile')

@push('css')
<style>
    .btn i {
        font-size: .75rem;
    }
</style>
@endpush

@section('content')
<div class="content-wrapper">
    <div class="row">
        <div class="col-md-12 grid-margin">
            <div class="row">
                <div class="col-12 col-xl-8 mb-4 mb-xl-0">
                    <h3 class="font-weight-bold">Profile</h3>
                    <h6 class="font-weight-normal mb-0">Kelola informasi akun Anda</h6>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">Update Profile</h4>
                    <form id="profileForm" enctype="multipart/form-data">
                        <div class="form-group text-center mb-4">
                            <div class="profile-photo-container position-relative d-inline-block">
                                <img id="profilePreview"
                                     src="{{ $user->profile && $user->profile->profile_photo ? asset('storage/profiles/' . $user->profile->profile_photo) : asset('images/default-avatar.png') }}"
                                     alt="Profile Photo"
                                     class="rounded-circle"
                                     style="width: 120px; height: 120px; object-fit: cover; border: 3px solid #dee2e6;">
                                <div class="position-absolute" style="bottom: 0; right: 0;">
                                    <label for="profilePhoto" class="btn btn-primary btn-sm rounded-circle" style="width: 40px; height: 40px; padding: 0; display: flex; align-items: center; justify-content: center;">
                                        <i class="ti ti-camera" style="font-size: 16px;"></i>
                                    </label>
                                    <input type="file" id="profilePhoto" name="profile_photo" accept="image/*" style="display: none;">
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="name">Nama Lengkap</label>
                            <input type="text" class="form-control" id="name" name="name" value="{{ $user->name }}" required>
                        </div>

                        <div class="form-group">
                            <label for="email">Email</label>
                            <input type="email" class="form-control" id="email" value="{{ $user->email }}" disabled>
                            <small class="form-text text-muted">Email tidak dapat diubah</small>
                        </div>

                        <div class="form-group">
                            <label for="role">Role</label>
                            <input type="text" class="form-control" id="role" value="{{ ucfirst($user->role) }}" disabled>
                            <small class="form-text text-muted">Role tidak dapat diubah</small>
                        </div>

                        <div class="form-group">
                            <label for="nip">NIP</label>
                            <input type="text" class="form-control" id="nip" name="nip" value="{{ $user->profile->nip ?? '' }}" required>
                        </div>

                        <div class="form-group">
                            <label for="position">Jabatan</label>
                            <input type="text" class="form-control" id="position" name="position" value="{{ $user->profile->position ?? '' }}" required>
                        </div>

                        <div class="form-group">
                            <label for="phone_number">Nomor Telepon</label>
                            <input type="text" class="form-control" id="phone_number" name="phone_number" value="{{ $user->profile->phone_number ?? '' }}" required>
                        </div>

                        <button type="submit" class="btn btn-primary mr-2">
                            <i class="ti ti-save"></i> Update Profile
                        </button>
                        <button type="button" class="btn btn-light" onclick="resetProfileForm()">Reset</button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-6 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">Ubah Password</h4>
                    <form id="passwordForm">
                        <div class="form-group">
                            <label for="current_password">Password Saat Ini</label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="current_password" name="current_password" required>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('current_password')">
                                        <i class="ti ti-eye" id="current_password_icon"></i>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="new_password">Password Baru</label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="new_password" name="new_password" required minlength="6">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('new_password')">
                                        <i class="ti ti-eye" id="new_password_icon"></i>
                                    </button>
                                </div>
                            </div>
                            <small class="form-text text-muted">Minimal 6 karakter</small>
                        </div>

                        <div class="form-group">
                            <label for="new_password_confirmation">Konfirmasi Password Baru</label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="new_password_confirmation" name="new_password_confirmation" required minlength="6">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('new_password_confirmation')">
                                        <i class="ti ti-eye" id="new_password_confirmation_icon"></i>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-success mr-2">
                            <i class="ti ti-lock"></i> Ubah Password
                        </button>
                        <button type="button" class="btn btn-light" onclick="resetPasswordForm()">Reset</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('script')
<script>
$(document).ready(function() {
    $('#profilePhoto').change(function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#profilePreview').attr('src', e.target.result);
            };
            reader.readAsDataURL(file);
        }
    });

    $('#profileForm').submit(function(e) {
        e.preventDefault();

        const formData = new FormData(this);

        $.ajax({
            url: '/api/profile/update',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'Authorization': getAuthorizationHeader(),
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: response.message,
                    showConfirmButton: false,
                    timer: 1500
                });
            },
            error: function(xhr) {
                const response = xhr.responseJSON;
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: response.message || 'Terjadi kesalahan saat mengupdate profile.',
                    confirmButtonText: 'OK'
                });
            }
        });
    });

    $('#passwordForm').submit(function(e) {
        e.preventDefault();

        const newPassword = $('#new_password').val();
        const confirmPassword = $('#new_password_confirmation').val();

        if (newPassword !== confirmPassword) {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Konfirmasi password tidak sesuai.',
                confirmButtonText: 'OK'
            });
            return;
        }

        const formData = {
            current_password: $('#current_password').val(),
            new_password: newPassword,
            new_password_confirmation: confirmPassword
        };

        $.ajax({
            url: '/api/profile/password',
            type: 'POST',
            data: formData,
            headers: {
                'Authorization': getAuthorizationHeader(),
                'Accept': 'application/json',
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: response.message,
                    showConfirmButton: false,
                    timer: 1500
                });
                resetPasswordForm();
            },
            error: function(xhr) {
                const response = xhr.responseJSON;
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: response.message || 'Terjadi kesalahan saat mengubah password.',
                    confirmButtonText: 'OK'
                });
            }
        });
    });
});

function togglePassword(fieldId) {
    const field = document.getElementById(fieldId);
    const icon = document.getElementById(fieldId + '_icon');

    if (field.type === 'password') {
        field.type = 'text';
        icon.classList.remove('ti-eye');
        icon.classList.add('ti-close');
    } else {
        field.type = 'password';
        icon.classList.remove('ti-close');
        icon.classList.add('ti-eye');
    }
}

function resetProfileForm() {
    document.getElementById('profileForm').reset();
    $('#profilePreview').attr('src', '{{ $user->profile && $user->profile->profile_photo ? asset("storage/profiles/" . $user->profile->profile_photo) : asset("images/default-avatar.png") }}');
}

function resetPasswordForm() {
    document.getElementById('passwordForm').reset();
    ['current_password', 'new_password', 'new_password_confirmation'].forEach(function(fieldId) {
        const field = document.getElementById(fieldId);
        const icon = document.getElementById(fieldId + '_icon');
        field.type = 'password';
        icon.classList.remove('ti-close');
        icon.classList.add('ti-eye');
    });
}
</script>
@endpush
