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

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <?php if($role=='admin_dpw'):?>
        <button class="btn btn-primary btn-sm" onclick="tambahGereja()"><i class="fas fa-plus"></i> Tambah Gereja</button>
        <?php endif;?>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered" id="tabelData" width="100%">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Foto</th>
                        <th>Nama Gereja</th>
                        <th>Alamat</th>
                        <th>Distrik</th>
                        <th>Gembala</th>
                        <th>Status</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 Gereja</h5>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
    </div>
    <div class="modal-body">
        <input type="hidden" name="id" id="id">
        <input type="hidden" name="foto_lama" id="foto_lama">
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label>Nama Gereja</label>
                    <input type="text" name="nama_gereja" id="nama_gereja" class="form-control" required>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label>Distrik</label>
                    <input type="text" name="distrik" id="distrik" class="form-control" required>
                </div>
            </div>
            <div class="col-md-12">
                <div class="form-group">
                    <label>Alamat</label>
                    <textarea name="alamat" id="alamat" class="form-control" rows="2"></textarea>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label>Latitude</label>
                    <input type="text" name="latitude" id="latitude" class="form-control">
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label>Longitude</label>
                    <input type="text" name="longitude" id="longitude" class="form-control">
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label>Tahun Berdiri</label>
                    <input type="number" name="tahun_berdiri" id="tahun_berdiri" class="form-control">
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label>Status</label>
                    <select name="status" id="status" class="form-control">
                        <option value="Aktif">Aktif</option>
                        <option value="Nonaktif">Nonaktif</option>
                    </select>
                </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label>Gembala</label>
                    <select name="gembala_id" id="gembala_id" class="form-control">
                        <option value="">- Pilih Gembala -</option>
                    </select>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label>Foto</label>
                    <input type="file" name="foto_gereja" class="form-control-file" accept="image/*">
                    <small class="text-muted">Kosongkan jika tidak ganti foto</small>
                    <div id="previewFoto" 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>
if(typeof window.gerejaLoaded === 'undefined'){
    window.gerejaLoaded = true;

    function tambahGereja(){
        $('#formData')[0].reset();
        $('#id').val('');
        $('#foto_lama').val('');
        $('#previewFoto').html('');
        $('#gembala_id').html('<option value="">- Pilih Gembala -</option>');
        $('#btnSimpan').prop('disabled', false).html('Simpan');
        $('#modalForm').modal('show');
    }

    function editGereja(id){
        $('#btnSimpan').prop('disabled', false).html('Simpan');
        $.get('api/get_gereja_detail.php?id='+id, function(res){
            if(res.status=='success'){
                let d = res.data;
                $('#id').val(d.id);
                $('#nama_gereja').val(d.nama_gereja);
                $('#distrik').val(d.distrik);
                $('#alamat').val(d.alamat);
                $('#latitude').val(d.latitude);
                $('#longitude').val(d.longitude);
                $('#tahun_berdiri').val(d.tahun_berdiri);
                $('#status').val(d.status);
                $('#foto_lama').val(d.foto_gereja);
                if(d.foto_gereja){
                    $('#previewFoto').html(`<img src="assets/img/gereja/${d.foto_gereja}" width="100" class="img-thumbnail mt-2">`);
                } else {
                    $('#previewFoto').html('');
                }
                // LOAD GEMBALA DARI TABEL users BERDASARKAN gereja_id
                loadGembalaByGereja(d.id, d.gembala_id);
                $('#modalForm').modal('show');
            } else {
                Swal.fire('Error','Data tidak ditemukan','error');
            }
        },'json');
    }

    function hapusGereja(id){
        Swal.fire({
            title:'Hapus data gereja?',
            text:'Data jemaat & inventaris ikut terhapus!',
            icon:'warning',
            showCancelButton:true,
            confirmButtonText: 'Ya, Hapus!',
            cancelButtonText: 'Batal'
        }).then(r=>{
            if(r.isConfirmed){
                $.post('api/hapus_gereja.php',{id:id},res=>{
                    if(res.status=='success'){
                        loadTabelGereja();
                        Swal.fire('Sukses',res.message,'success');
                    } else {
                        Swal.fire('Error',res.message,'error');
                    }
                },'json');
            }
        });
    }

    function loadTabelGereja(){
        $.get('api/get_all_gereja.php', function(res){
            let html = '';
            let badge = {'Aktif':'success','Nonaktif':'danger'};
            res.data.forEach((d,i)=>{
                let foto = d.foto_gereja? d.foto_gereja : 'default.jpg';
                let pathFoto = `assets/img/gereja/${foto}`;
                html += `<tr>
                    <td>${i+1}</td>
                    <td class="text-center">
                        <img src="${pathFoto}" width="60" height="60" class="img-thumbnail"
                             style="object-fit:cover"
                             onerror="this.src='assets/img/gereja/default.jpg'">
                    </td>
                    <td>${d.nama_gereja}</td>
                    <td>${d.alamat||'-'}</td>
                    <td>${d.distrik||'-'}</td>
                    <td>${d.nama_gembala||'-'}</td>
                    <td><span class="badge badge-${badge[d.status]}">${d.status}</span></td>
                    <td>
                        <button type="button" class="btn btn-info btn-sm" onclick="detailGereja(${d.id})"><i class="fa fa-eye"></i></button>
                        <button type="button" class="btn btn-warning btn-sm" onclick="editGereja(${d.id})"><i class="fa fa-edit"></i></button>
                        <button type="button" class="btn btn-danger btn-sm" onclick="hapusGereja(${d.id})"><i class="fa fa-trash"></i></button>
                    </td></tr>`;
            });
            $('#tabelData tbody').html(html);
            if(typeof $.fn.DataTable!== 'undefined'){
                if($.fn.DataTable.isDataTable('#tabelData')) {
                    $('#tabelData').DataTable().destroy();
                }
                $('#tabelData').DataTable({"order":[[2,"asc"]]});
            }
        });
    }

    // AMBIL DARI TABEL users YANG gereja_id = ID GEREJA INI
    function loadGembalaByGereja(gereja_id, selected_gembala_id = null){
        $.get('api/get_gembala_by_gereja.php?gereja_id='+gereja_id, function(res){
            if(res.status=='success'){
                let opt = '<option value="">- Pilih Gembala -</option>';
                res.data.forEach(d=> {
                    opt += `<option value="${d.id}">${d.nama}</option>`;
                });
                $('#gembala_id').html(opt);
                if(selected_gembala_id) $('#gembala_id').val(selected_gembala_id);
            }
        });
    }

    $('#formData').off('submit').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:'api/simpan_gereja.php',
            type:'POST',
            data:formData,
            contentType:false,
            processData:false,
            dataType:'json',
            success:function(res){
                if(res.status=='success'){
                    $('#modalForm').modal('hide');
                    Swal.fire('Sukses',res.message,'success');
                    loadTabelGereja();
                } else {
                    Swal.fire('Error',res.message,'error');
                }
            },
            error: function(xhr){
                Swal.fire('Error','Gagal: '+xhr.statusText,'error');
            },
            complete: function(){
                $('#btnSimpan').prop('disabled', false).html('Simpan');
            }
        });
    });

    loadTabelGereja();
}
</script>