<?php
require_once '../config/auth.php';
cek_role('admin_dpw');

include '../config/database.php';
$db = new Database();
$conn = $db->getConnection();

// JOIN ke tabel gereja biar tampil nama gerejanya
$sql = "SELECT u.*, g.nama_gereja 
        FROM users u 
        LEFT JOIN gereja g ON u.gereja_id = g.id 
        WHERE u.role = 'gembala' 
        ORDER BY u.nama";
$gembala = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Data Gembala</h1>
</div>

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <button class="btn btn-primary btn-sm" id="btnTambah">
            <i class="fa fa-plus"></i> Tambah Gembala
        </button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered" id="dataTable" width="100%">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Foto</th>
                        <th>Nama Gembala</th>
                        <th>Nama Gereja</th>
                        <th>Username</th>
                        <th>No HP</th>
                        <th>Status</th>
                        <th width="100">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $no=1; foreach($gembala as $row):?>
                    <tr>
                        <td><?= $no++?></td>
                        <td>
                            <img src="assets/img/users/<?= $row['foto']?: 'default.png'?>" 
                                 width="40" height="40" class="img-thumbnail rounded-circle"
                                 onerror="this.src='assets/img/users/default.png'">
                        </td>
                        <td><?= htmlspecialchars($row['nama'])?></td>
                        <td><span class="badge badge-info"><?= $row['nama_gereja']?: '-'?></span></td>
                        <td><?= $row['username']?></td>
                        <td><?= $row['no_hp']?></td>
                        <td>
                            <span class="badge badge-<?= $row['status']=='Aktif'?'success':'danger'?>">
                                <?= $row['status']?>
                            </span>
                        </td>
                        <td>
                            <button class="btn btn-warning btn-sm btn-edit" 
                                data-id="<?= $row['id']?>"
                                data-nama="<?= htmlspecialchars($row['nama'])?>"
                                data-username="<?= $row['username']?>"
                                data-no_hp="<?= $row['no_hp']?>"
                                data-status="<?= $row['status']?>"
                                data-foto="<?= $row['foto']?>"
                                data-gereja_id="<?= $row['gereja_id']?>"
                                data-nama_gereja="<?= htmlspecialchars($row['nama_gereja'])?>">
                                <i class="fa fa-edit"></i>
                            </button>
                            <button class="btn btn-danger btn-sm btn-hapus" 
                                data-id="<?= $row['id']?>" 
                                data-nama="<?= htmlspecialchars($row['nama'])?>"
                                data-gereja_id="<?= $row['gereja_id']?>">
                                <i class="fa fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach;?>
                    <?php if(empty($gembala)):?>
                    <tr><td colspan="8" class="text-center">Belum ada data gembala</td></tr>
                    <?php endif;?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal Tambah/Edit Gembala -->
<div class="modal fade" id="modalGembala" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Tambah Gembala</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="formGembala" enctype="multipart/form-data">
                <input type="hidden" name="id" id="id_gembala">
                <input type="hidden" name="gereja_id" id="gereja_id">
                <input type="hidden" name="action" id="action" value="tambah_gembala">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="text-primary">Data Gembala</h6>
                            <hr>
                            <div class="form-group">
                                <label>Nama Lengkap Gembala</label>
                                <input type="text" name="nama" id="nama" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label>Username</label>
                                <input type="text" name="username" id="username" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label>Password</label>
                                <input type="password" name="password" id="password" class="form-control">
                                <small class="text-muted" id="note_password">Kosongkan jika tidak ganti password</small>
                            </div>
                            <div class="form-group">
                                <label>No HP</label>
                                <input type="text" name="no_hp" id="no_hp" class="form-control">
                            </div>
                            <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>
                        <div class="col-md-6">
                            <h6 class="text-primary">Data Gereja Baru</h6>
                            <hr>
                            <div class="form-group">
                                <label>Nama Gereja</label>
                                <input type="text" name="nama_gereja" id="nama_gereja" class="form-control" required>
                                <small class="text-muted">Contoh: GBI YD Keerom. Harus unik!</small>
                            </div>
                            <div class="form-group">
                                <label>Alamat Gereja</label>
                                <textarea name="alamat_gereja" id="alamat_gereja" class="form-control" rows="3" required></textarea>
                            </div>
                            <div class="form-group">
                                <label>Foto Gembala</label>
                                <input type="file" name="foto" id="foto" class="form-control">
                                <img id="preview_foto" src="" width="80" class="mt-2 rounded" style="display:none;">
                            </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>
function reloadGembala(){
    if(typeof loadPage === 'function'){
        loadPage('data_gembala');
    } else if(typeof load_page === 'function'){
        load_page('data_gembala');
    } else {
        location.reload();
    }
}

// 1. TOMBOL TAMBAH
$('#btnTambah').click(function(){
    $('#formGembala')[0].reset();
    $('#id_gembala').val('');
    $('#gereja_id').val('');
    $('#action').val('tambah_gembala');
    $('.modal-title').text('Tambah Gembala + Gereja Baru');
    $('#password').prop('required', true);
    $('#nama_gereja, #alamat_gereja').prop('readonly', false);
    $('#note_password').hide();
    $('#preview_foto').hide();
    $('#modalGembala').modal('show');
});

// 2. TOMBOL EDIT
$(document).on('click', '.btn-edit', function(){
    $('#formGembala')[0].reset();
    $('#id_gembala').val($(this).data('id'));
    $('#gereja_id').val($(this).data('gereja_id'));
    $('#nama').val($(this).data('nama'));
    $('#username').val($(this).data('username'));
    $('#no_hp').val($(this).data('no_hp'));
    $('#status').val($(this).data('status'));
    $('#nama_gereja').val($(this).data('nama_gereja'));
    $('#action').val('edit_gembala');
    $('.modal-title').text('Edit Gembala & Gereja');
    $('#password').prop('required', false).val('');
    $('#note_password').show();
    $('#nama_gereja, #alamat_gereja').prop('readonly', false); // Bisa edit nama gereja
    
    let foto = $(this).data('foto');
    if(foto && foto!= 'default.png'){
        $('#preview_foto').attr('src', 'assets/img/users/'+foto).show();
    } else {
        $('#preview_foto').hide();
    }
    $('#modalGembala').modal('show');
});

// 3. SUBMIT TAMBAH/EDIT
$('#formGembala').submit(function(e){
    e.preventDefault();
    $('#btnSimpan').html('<i class="fa fa-spinner fa-spin"></i> Menyimpan...').prop('disabled', true);
    
    $.ajax({
        url: 'api/proses_gembala.php',
        type: 'POST',
        data: new FormData(this),
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(res){
            if(res.status == 'sukses'){
                $('#modalGembala').modal('hide');
                Swal.fire({
                    icon: 'success',
                    title: 'Sukses',
                    text: res.message,
                    confirmButtonColor: '#4e73df'
                }).then((result) => {
                    reloadGembala();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal',
                    text: res.message
                });
            }
        },
        error: function(){
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Terjadi kesalahan server'
            });
        },
        complete: function(){
            $('#btnSimpan').html('Simpan').prop('disabled', false);
        }
    });
});

// 4. TOMBOL HAPUS
$(document).on('click', '.btn-hapus', function(){
    let id = $(this).data('id');
    let nama = $(this).data('nama');
    let gereja_id = $(this).data('gereja_id');
    
    Swal.fire({
        title: 'Yakin hapus?',
        text: "Gembala "+nama+" dan gerejanya akan dihapus permanen!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Ya, Hapus!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'api/proses_gembala.php',
                type: 'POST',
                data: {action: 'hapus_gembala', id: id, gereja_id: gereja_id},
                dataType: 'json',
                success: function(res){
                    if(res.status == 'sukses'){
                        Swal.fire('Terhapus!', res.message, 'success')
                      .then(() => {
                            reloadGembala();
                        });
                    } else {
                        Swal.fire('Gagal!', res.message, 'error');
                    }
                }
            });
        }
    });
});

// Preview foto
$('#foto').change(function(){
    const file = this.files[0];
    if(file){
        let reader = new FileReader();
        reader.onload = function(e){
            $('#preview_foto').attr('src', e.target.result).show();
        }
        reader.readAsDataURL(file);
    }
});

$('#modalGembala').on('hidden.bs.modal', function () {
    $('#formGembala')[0].reset();
    $('#preview_foto').hide();
});
</script>