<?php
session_start();
if(!isset($_SESSION['user_id'])) die('Akses ditolak');
$role = $_SESSION['role'];
$gereja_id = $_SESSION['gereja_id'];
?>
<h1 class="h3 mb-4 text-gray-800">Data Jemaat</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 Jemaat</button>
        <?php if($role=='admin_dpw'):?>
        <button class="btn btn-success btn-sm" id="btnExport"><i class="fas fa-file-excel"></i> Export Excel</button>
        <?php endif;?>
    </div>
    <div class="card-body">
        <div class="alert alert-warning" id="alertGereja" style="display:none;">
            <i class="fas fa-exclamation-triangle"></i> Anda belum terdaftar di gereja manapun. Hubungi Admin DPW.
        </div>
        <div class="table-responsive">
            <table class="table table-bordered" id="tabelData" width="100%">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Foto</th>
                        <th>No Anggota</th>
                        <th>Nama</th>
                        <th>Kaum</th>
                        <th>No HP</th>
                        <th>L/P</th>
                        <th>Gereja</th>
                        <th>Baptis</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalForm" tabindex="-1">
<div class="modal-dialog modal-lg"><div class="modal-content">
    <form id="formData" enctype="multipart/form-data">
    <div class="modal-header"><h5 class="modal-title">Form Jemaat</h5><button class="close" data-dismiss="modal">&times;</button></div>
    <div class="modal-body">
        <input type="hidden" name="id" id="id">
        <div class="row">
            <div class="col-md-6"><div class="form-group"><label>Nama Lengkap</label><input type="text" name="nama_lengkap" class="form-control" required></div></div>
            <div class="col-md-6"><div class="form-group"><label>NIK</label><input type="text" name="nik" class="form-control"></div></div>
            <div class="col-md-6"><div class="form-group"><label>Tempat Lahir</label><input type="text" name="tempat_lahir" class="form-control"></div></div>
            <div class="col-md-6"><div class="form-group"><label>Tgl Lahir</label><input type="date" name="tgl_lahir" class="form-control"></div></div>
            <div class="col-md-6"><div class="form-group"><label>Jenis Kelamin</label><select name="jenis_kelamin" class="form-control"><option value="L">Laki-laki</option><option value="P">Perempuan</option></select></div></div>

            <!-- TAMBAH FIELD KAUM -->
            <div class="col-md-6">
                <div class="form-group">
                    <label>Kaum</label>
                    <select name="kaum" class="form-control" required>
                        <option value="">-- Pilih Kaum --</option>
                        <option value="WBI">WBI</option>
                        <option value="Dewasa Muda">Dewasa Muda</option>
                        <option value="Pemuda">Pemuda</option>
                        <option value="Remaja">Remaja</option>
                        <option value="Anak">Anak</option>
                        <option value="Balita">Balita</option>
                    </select>
                </div>
            </div>

            <div class="col-md-6"><div class="form-group"><label>No HP</label><input type="text" name="no_hp" class="form-control" placeholder="0812xxxx"></div></div>
            <div class="col-md-6"><div class="form-group"><label>Status Nikah</label><select name="status_nikah" class="form-control"><option value="Belum">Belum</option><option value="Nikah">Nikah</option><option value="Duda">Duda</option><option value="Janda">Janda</option></select></div></div>
            <div class="col-md-12"><div class="form-group"><label>Alamat</label><textarea name="alamat" class="form-control"></textarea></div></div>

            <div class="col-md-6">
                <div class="form-group">
                    <label>Gereja</label>
                    <?php if($role=='admin_dpw'):?>
                    <select name="gereja_id" id="gereja_id" class="form-control" required></select>
                    <?php else:?>
                    <input type="text" class="form-control" id="nama_gereja" readonly>
                    <input type="hidden" name="gereja_id" id="gereja_id">
                    <?php endif;?>
                </div>
            </div>

            <div class="col-md-6">
                <div class="form-group">
                    <label>Status Baptis</label>
                    <select name="status_baptis" id="status_baptis" class="form-control" onchange="toggleTglBaptis()">
                        <option value="Belum">Belum</option>
                        <option value="Sudah">Sudah</option>
                    </select>
                </div>
            </div>

            <div class="col-md-6">
                <div class="form-group">
                    <label>Tgl Baptis</label>
                    <input type="date" name="tgl_baptis" id="tgl_baptis" class="form-control" disabled>
                    <small class="text-muted" id="info_baptis">Pilih "Sudah" dulu untuk input tanggal</small>
                </div>
            </div>

            <div class="col-md-12">
                <div class="form-group">
                    <label>Foto</label>
                    <input type="file" name="foto" class="form-control-file" accept="image/*">
                    <input type="hidden" name="foto_lama" id="foto_lama">
                    <small class="text-muted">Max 2MB. Format: JPG, PNG</small>
                    <div id="preview_foto" class="mt-2"></div>
                </div>
            </div>
        </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>
loadTabel();
loadGereja();

function loadTabel(){
    $.get(BASE_URL+'/api/get_jemaat.php', function(res){
        let html = '';
        if(res.status=='success' && res.data.length > 0){
            res.data.forEach((d,i)=>{
                let foto = d.foto && d.foto.trim()!= ''? `assets/img/jemaat/${d.foto}` : 'assets/img/jemaat/default.jpg';
                let kaum_badge = d.kaum ? `<span class="badge badge-secondary">${d.kaum}</span>` : '-'; // TAMBAH INI
                html += `<tr>
                    <td>${i+1}</td>
                    <td><img src="${BASE_URL}/${foto}" width="40" height="40" class="rounded-circle" style="object-fit:cover;" onerror="this.src='${BASE_URL}/assets/img/jemaat/default.jpg'"></td>
                    <td>${d.no_anggota||'-'}</td>
                    <td>${d.nama_lengkap}</td>
                    <td>${kaum_badge}</td>
                    <td>${d.no_hp||'-'}</td>
                    <td>${d.jenis_kelamin}</td>
                    <td>${d.nama_gereja||'-'}</td>
                    <td><span class="badge badge-${d.status_baptis=='Sudah'?'success':'warning'}">${d.status_baptis}</span></td>
                    <td>
                        <button class="btn btn-info btn-sm btnDetail" data-id="${d.id}"><i class="fa fa-eye"></i></button>
                        <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>`;
            });
        } else {
            html = '<tr><td colspan="10" class="text-center">Data jemaat belum ada</td></tr>';
        }
        $('#tabelData tbody').html(html);
        if($.fn.DataTable.isDataTable('#tabelData')) $('#tabelData').DataTable().destroy();
        $('#tabelData').DataTable();
    },'json');
}
function loadGereja(callback=null){
    <?php if($role=='admin_dpw'):?>
    $.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);
        if(callback) callback();
    });
    <?php else:?>
    $.get(BASE_URL+'/api/get_gereja_gembala.php', function(res){
        if(res.status=='success' && res.data){
            $('#gereja_id').val(res.data.id);
            $('#nama_gereja').val(res.data.nama_gereja);
            $('#alertGereja').hide();
            $('#btnTambah').prop('disabled', false);
        } else {
            $('#alertGereja').show();
            $('#btnTambah').prop('disabled', true);
            $('#nama_gereja').val('Belum ada gereja');
        }
        if(callback) callback();
    }).fail(function(){
        $('#alertGereja').show();
        $('#btnTambah').prop('disabled', true);
    });
    <?php endif;?>
}

// FUNGSI TOGGLE TGL BAPTIS
function toggleTglBaptis() {
    const status = $('#status_baptis').val();
    const tglBaptis = $('#tgl_baptis');
    const infoBaptis = $('#info_baptis');

    if(status === 'Sudah'){
        tglBaptis.prop('disabled', false);
        tglBaptis.prop('required', true);
        infoBaptis.text('Wajib diisi karena sudah baptis').removeClass('text-muted').addClass('text-danger');
    } else {
        tglBaptis.prop('disabled', true);
        tglBaptis.prop('required', false);
        tglBaptis.val('');
        infoBaptis.text('Pilih "Sudah" dulu untuk input tanggal').removeClass('text-danger').addClass('text-muted');
    }
}

$('#btnTambah').click(()=>{
    if($('#gereja_id').val() == '' && '<?= $role?>'!= 'admin_dpw'){
        Swal.fire('Error','Anda belum terdaftar di gereja manapun','error');
        return;
    }
    $('#formData')[0].reset();
    $('#id').val('');
    $('#preview_foto').html('');
    $('.modal-title').text('Tambah Jemaat');
    loadGereja();
    toggleTglBaptis(); // Reset kondisi tgl baptis
    $('#modalForm').modal('show');
});

// FIX EDIT TOTAL
$(document).on('click','.btnEdit',function(){
    let id = $(this).data('id');
    $.get(BASE_URL+'/api/get_jemaat_detail.php?id='+id, function(res){
        if(res.status=='success'){
            let d = res.data;
            $('#id').val(d.id);

            // ISI SEMUA FIELD
            $('[name=nama_lengkap]').val(d.nama_lengkap);
            $('[name=nik]').val(d.nik);
            $('[name=tempat_lahir]').val(d.tempat_lahir);
            $('[name=tgl_lahir]').val(d.tgl_lahir);
            $('[name=jenis_kelamin]').val(d.jenis_kelamin);
             // TAMBAH INI - BIAR KAUM KEISI PAS EDIT
            $('[name=no_hp]').val(d.no_hp);
            $('[name=alamat]').val(d.alamat);
            $('[name=status_baptis]').val(d.status_baptis);
            $('[name=tgl_baptis]').val(d.tgl_baptis);
            $('[name=status_nikah]').val(d.status_nikah);
            $('#foto_lama').val(d.foto);

            // TRIGGER TOGGLE BAPTIS
            toggleTglBaptis();

            // PREVIEW FOTO LAMA
            if(d.foto && d.foto!= ''){
                $('#preview_foto').html(`<img src="${BASE_URL}/assets/img/jemaat/${d.foto}" width="100" class="img-thumbnail"><br><small>Foto saat ini</small>`);
            } else {
                $('#preview_foto').html('');
            }

            // LOAD GEREJA DULU BARU SET VALUE
            loadGereja(function(){
                $('#gereja_id').val(d.gereja_id);
                <?php if($role!='admin_dpw'):?>
                $('#nama_gereja').val(d.nama_gereja);
                <?php endif;?>
            });

            $('.modal-title').text('Edit Jemaat');
            $('#modalForm').modal('show');
        } else {
            Swal.fire('Error',res.message,'error');
        }
    },'json').fail(function(xhr){
        Swal.fire('Error','Gagal ambil data: '+xhr.responseText,'error');
    });
});

$('#formData').submit(function(e){
    e.preventDefault();
    if($('#gereja_id').val() == ''){
        Swal.fire('Error','Gereja belum dipilih','error');
        return;
    }

    // VALIDASI TGL BAPTIS
    if($('#status_baptis').val() == 'Sudah' && $('#tgl_baptis').val() == ''){
        Swal.fire('Error','Tanggal Baptis wajib diisi jika status baptis Sudah','error');
        return;
    }

    $('#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_jemaat.php',
        type:'POST',
        data:formData,
        contentType:false,
        processData:false,
        dataType:'json',
        success:function(res){
            $('#modalForm').modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
            if(res.status=='success'){
                Swal.fire('Sukses',res.message,'success');
                loadTabel();
            } else {
                Swal.fire('Error',res.message,'error');
            }
        },
        error: function(xhr){
            Swal.fire('Error','Gagal simpan: '+xhr.responseText,'error');
        },
        complete: function(){
            $('#btnSimpan').prop('disabled', false).html('Simpan');
        }
    });
});

$(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_jemaat.php',{id:id},res=>{
                loadTabel();
                Swal.fire('Sukses',res.message,'success');
            });
        }
    });
});

$('#btnExport').click(()=> window.open(BASE_URL+'/api/export_jemaat.php'));

// PREVIEW FOTO BARU
$('input[name=foto]').change(function(e){
    if(e.target.files[0]){
        let reader = new FileReader();
        reader.onload = function(e){
            $('#preview_foto').html(`<img src="${e.target.result}" width="100" class="img-thumbnail"><br><small>Preview foto baru</small>`);
        }
        reader.readAsDataURL(e.target.files[0]);
    }
});
</script>