<?php 
session_start(); 
if(!isset($_SESSION['user_id'])) die('Akses ditolak');
$role = $_SESSION['role'];
?>
<h1 class="h3 mb-4 text-gray-800">Pengurus & Gembala</h1>

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <button class="btn btn-primary btn-sm" id="btnTambah"><i class="fas fa-plus"></i> Tambah Pengurus</button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered" id="tabelData" width="100%">
                <thead><tr><th>No</th><th>Nama</th><th>Username</th><th>Role</th><th>Gereja</th><th>No HP</th><th>Aksi</th></tr></thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalForm" tabindex="-1">
<div class="modal-dialog"><div class="modal-content">
    <form id="formData" enctype="multipart/form-data">
    <div class="modal-header"><h5 class="modal-title">Form Pengurus</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
    <div class="modal-body">
        <input type="hidden" name="id" id="id">
        <div class="form-group"><label>Nama Lengkap</label><input type="text" name="nama" class="form-control" required></div>
        <div class="form-group"><label>Username</label><input type="text" name="username" class="form-control" required></div>
        <div class="form-group"><label>Password <small>Kosongkan jika tidak ganti</small></label><input type="password" name="password" class="form-control"></div>
        <div class="form-group"><label>Role</label>
            <select name="role" class="form-control" required>
                <option value="admin_dpw">Admin DPW</option>
                <option value="gembala">Gembala</option>
            </select>
        </div>
        <div class="form-group"><label>Gereja</label><select name="gereja_id" id="gereja_id" class="form-control"></select></div>
        <div class="form-group"><label>No HP</label><input type="text" name="no_hp" class="form-control"></div>
        <div class="form-group"><label>Foto</label><input type="file" name="foto" class="form-control-file"><input type="hidden" name="foto_lama" id="foto_lama"></div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
        <button type="submit" class="btn btn-primary" id="btnSimpan">Simpan</button>
    </div>
    </form>
</div></div></div>

<script>
$(document).ready(function(){
    loadTabel(); loadGereja();

    function loadTabel(){
        $.get(BASE_URL+'/api/get_all_user.php', function(res){
            let html = '';
            res.data.forEach((d,i)=>{
                html += `<tr>
                    <td>${i+1}</td><td>${d.nama}</td><td>${d.username}</td>
                    <td><span class="badge badge-${d.role=='admin_dpw'?'danger':'info'}">${d.role}</span></td>
                    <td>${d.nama_gereja||'-'}</td><td>${d.no_hp||'-'}</td>
                    <td>
                        <button class="btn btn-warning btn-sm btnEdit" data-id="${d.id}"><i class="fa fa-edit"></i></button>
                        <button class="btn btn-danger btn-sm btnHapus" data-id="${d.id}"><i class="fa fa-trash"></i></button>
                    </td>
                </tr>`;
            });
            $('#tabelData tbody').html(html);
            if($.fn.DataTable.isDataTable('#tabelData')) $('#tabelData').DataTable().destroy();
            $('#tabelData').DataTable();
        }).fail(function(xhr){
            console.log(xhr.responseText);
            Swal.fire('Error','Gagal load data user: '+xhr.status,'error');
        });
    }

    function loadGereja(){
        $.get(BASE_URL+'/api/get_all_gereja.php', function(res){
            let opt = '<option value="">- Pilih Gereja -</option>';
            res.data.forEach(d=> opt += `<option value="${d.id}">${d.nama_gereja}</option>`);
            $('#gereja_id').html(opt);
        });
    }

    $('#btnTambah').on('click', function(){ 
        $('#formData')[0].reset(); 
        $('#id').val(''); 
        $('#modalForm').modal('show'); 
    });

    $(document).on('click','.btnEdit',function(){
        let id = $(this).data('id');
        $.get(BASE_URL+'/api/get_user_detail.php?id='+id, function(res){
            $('#id').val(res.data.id); 
            $('[name=nama]').val(res.data.nama);
            $('[name=username]').val(res.data.username); 
            $('[name=role]').val(res.data.role);
            $('[name=gereja_id]').val(res.data.gereja_id); 
            $('[name=no_hp]').val(res.data.no_hp);
            $('#foto_lama').val(res.data.foto); 
            $('#modalForm').modal('show');
        });
    });

    $('#formData').on('submit', function(e){
        e.preventDefault();
        $('#btnSimpan').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Menyimpan...');
        
        let formData = new FormData(this);
        $.ajax({
            url: BASE_URL+'/api/simpan_user.php', 
            type: 'POST', 
            data: formData, 
            contentType: false, 
            processData: false, 
            dataType: 'json',
            success: function(res){
                $('#btnSimpan').prop('disabled', false).html('Simpan');
                if(res.status=='success'){ 
                    $('#modalForm').modal('hide'); 
                    Swal.fire('Sukses',res.message,'success'); 
                    loadTabel(); 
                } else {
                    Swal.fire('Error',res.message,'error');
                }
            },
            error: function(xhr){
                $('#btnSimpan').prop('disabled', false).html('Simpan');
                console.log(xhr.responseText);
                Swal.fire('Error','Gagal simpan: '+xhr.status+' - Cek api/simpan_user.php','error');
            }
        });
    });

    $(document).on('click','.btnHapus',function(){
        let id = $(this).data('id');
        Swal.fire({title:'Hapus data?',icon:'warning',showCancelButton:true}).then(r=>{
            if(r.isConfirmed){ 
                $.post(BASE_URL+'/api/hapus_user.php',{id:id},function(res){ 
                    loadTabel(); 
                    Swal.fire('Sukses',res.message,'success'); 
                },'json'); 
            }
        });
    });
});
</script>