<?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>

<!-- <?php if (session()->getFlashdata('success')): ?>
    <div class="alert alert-success">
        <?= session()->getFlashdata('success') ?>
    </div>
<?php endif; ?> -->


<div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
    <div>
        <h4 class="mb-3 mb-md-0">Profil </h4>
    </div>

</div>

<div class="row profil-body">
    <!-- left wrapper start -->

    <div class="col-md-6 grid-margin stretch-card">
        <div class="card">
            <div class="card-body">

                <h6 class="card-title">Update Profil</h6>

                <form id="profilForm" class="forms-sample" enctype="multipart/form-data">
                    <input type="hidden" id="user_id" name="user_id" value="<?= session()->get('user_id'); ?>">

                    <div class="row mb-3">
                        <label for="firstnameProfil" class="col-sm-3 col-form-label">Firstname</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" id="firstnameProfil" name="firstnameProfil" placeholder="Nama Lengkap">
                        </div>
                    </div>

                    <div class="row mb-3">
                        <label for="emailProfil" class="col-sm-3 col-form-label">Email</label>
                        <div class="col-sm-9">
                            <input type="email" class="form-control" id="emailProfil" name="emailProfil" placeholder="Email" autocomplete="off">
                        </div>
                    </div>

                    <div class="row mb-3">
                        <label for="nohapeProfil" class="col-sm-3 col-form-label">No Hape</label>
                        <div class="col-sm-9">
                            <input type="number" class="form-control" id="nohapeProfil" name="nohapeProfil" placeholder="No hape">
                        </div>
                    </div>

                    <div class="row mb-3">
                        <label for="password" class="col-sm-3 col-form-label">Password</label>
                        <div class="col-sm-9">
                            <input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off">
                        </div>
                    </div>

                    <div class="row mb-3">
                        <label for="confirm_password" class="col-sm-3 col-form-label">Konfirmasi Password</label>
                        <div class="col-sm-9">
                            <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Konfirmasi Password" autocomplete="off">
                            <div class="col-sm-9">
                                <input type="checkbox" id="show_password" class="filled-in chk-col-red">
                                <label for="show_password">Show Password</label>
                            </div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="profile_image" class="col-sm-3 col-form-label">Foto Profil</label>
                        <div class="col-sm-9">
                            <input type="file" class="form-control" id="profile_image" name="profile_image" accept="image/*">
                            <img id="profilePicture" src="" alt="Foto Profil" width="150" class="mt-2">
                        </div>
                    </div>
                    <button type="button" class="btn btn-primary me-2" onclick="updateProfile()">Update</button>
                </form>
                <!-- Catatan -->
                <!-- <div class="alert alert-warning mt-3">
                    <strong>Catatan:</strong><br>
                    Maaf kami tidak mengizinkan untuk ubah data user dikarenakan aplikasi ini khusus untuk demonstrasi, agar client lain bisa login dengan akun demonstrasi yang sudah kami buat default.<br>
                    Terimakasih atas pengertiannya.<br><br>
                    Salam sukses selalu.
                </div> -->

            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        loadProfil(); // Muat Data Profil saat halaman dimuat
    });

    // Fungsi Memuat Data Profil
    function loadProfil() {
        var user_id = $('#user_id').val(); // Ambil User ID dari Sesi
        $.ajax({
            url: "<?= base_url('/Profil/getProfil') ?>/" + user_id, // Panggil Controller
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#firstnameProfil').val(response.profil.firstname);
                    $('#emailProfil').val(response.profil.email);
                    $('#nohapeProfil').val(response.profil.nohape);

                    // Update gambar profil jika ada
                    if (response.profil.foto) {
                        $('#profilePicture').attr('src', "<?= base_url('/public/assets/images/faces/') ?>/" + response.profil.foto);
                    } else {
                        $('#profilePicture').attr('src', "<?= base_url('/public/assets/images/faces/default.png') ?>");
                    }
                } else {
                    alert('Data profil tidak ditemukan!');
                }
            },
            error: function() {
                alert('Terjadi kesalahan saat memuat profil');
            }
        });
    }

    // Fungsi Memperbarui Profil
    function updateProfile() {
        var formData = new FormData($('#profilForm')[0]);

        // Validasi sederhana untuk memeriksa apakah form terisi dengan benar
        var firstname = $('#firstnameProfil').val();
        var email = $('#emailProfil').val();
        var nohape = $('#nohapeProfil').val();
        if (!firstname || !email || !nohape) {
            Swal.fire({
                icon: 'error',
                title: 'Form Tidak Lengkap',
                text: 'Harap isi semua field!',
                timer: 2000,
                showConfirmButton: false
            });
            return; // Menghentikan eksekusi jika ada field yang kosong
        }
        // Konfirmasi SweetAlert sebelum mengirim data
        Swal.fire({
            title: 'Apakah Anda yakin?',
            text: 'Data profil akan diperbarui.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Ya, perbarui!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {

                $.ajax({
                    url: '<?= base_url('/profil/updateProfile') ?>',
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        if (response.success) {
                            $('#message').text(response.message).css('color', 'green');

                            // Perbarui gambar jika ada
                            if (response.foto) {
                                $('#profilePicture').attr('src', "<?= base_url('/public/assets/images/faces/') ?>/" + response.foto);
                            }

                            // Tampilkan SweetAlert Sukses
                            Swal.fire({
                                icon: 'success',
                                title: 'Berhasil!',
                                text: response.message,
                                timer: 2000,
                                showConfirmButton: false
                            });
                        } else {
                            // Tampilkan SweetAlert Gagal
                            Swal.fire({
                                icon: 'error',
                                title: 'Gagal!',
                                text: response.message,
                                timer: 2000,
                                showConfirmButton: false
                            });
                        }
                    },
                    error: function() {
                        // Tampilkan SweetAlert Kesalahan Server
                        Swal.fire({
                            icon: 'error',
                            title: 'Kesalahan Server!',
                            text: 'Terjadi kesalahan saat memperbarui profil',
                            timer: 2000,
                            showConfirmButton: false
                        });
                    }
                });
            }
        });
    }

    // Fungsi Membatalkan Update
    function cancelUpdate() {
        loadProfile(); // Muat ulang data asli
    }

    document.getElementById('show_password').addEventListener('change', function() {
        const passwordField = document.getElementById('password');
        const confirmPasswordField = document.getElementById('confirm_password');

        if (this.checked) {
            passwordField.type = 'text';
            confirmPasswordField.type = 'text';
        } else {
            passwordField.type = 'password';
            confirmPasswordField.type = 'password';
        }
    });
</script>
<?= $this->endSection(); ?>