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

$gereja_id = $_SESSION['gereja_id'];

if(!$gereja_id){
    die('<div class="alert alert-danger m-3">Error: Akun belum terhubung ke gereja. Logout dan login ulang.</div>');
}

// === HANDLE AJAX ===
if(isset($_POST['aksi'])){
    header('Content-Type: application/json');
    
    // 1. SIMPAN/UPDATE
    if($_POST['aksi'] == 'simpan'){
        $id = $_POST['id'];
        $jemaat_id = $_POST['jemaat_id'];
        $jabatan = $_POST['jabatan'];
        
        try {
            if($id == ''){
                $sql = "INSERT INTO pelayan (jemaat_id, jabatan, gereja_id) VALUES (?,?,?)";
                $conn->prepare($sql)->execute([$jemaat_id, $jabatan, $gereja_id]);
            } else {
                $sql = "UPDATE pelayan SET jemaat_id=?, jabatan=? WHERE id=? AND gereja_id=?";
                $conn->prepare($sql)->execute([$jemaat_id, $jabatan, $id, $gereja_id]);
            }
            echo json_encode(['status'=>'sukses']);
        } catch (PDOException $e) {
            echo json_encode(['status'=>'error','message'=>'DB Error: '.$e->getMessage()]);
        }
        exit;
    }
    
    // 2. HAPUS
    if($_POST['aksi'] == 'hapus'){
        $conn->prepare("DELETE FROM pelayan WHERE id=? AND gereja_id=?")->execute([$_POST['id'], $gereja_id]);
        echo json_encode(['status'=>'sukses']);
        exit;
    }
    
    // 3. GET DATA BUAT EDIT
    if($_POST['aksi'] == 'get'){
        $stmt = $conn->prepare("SELECT * FROM pelayan WHERE id=? AND gereja_id=?");
        $stmt->execute([$_POST['id'], $gereja_id]);
        echo json_encode($stmt->fetch(PDO::FETCH_ASSOC));
        exit;
    }
}

// LIST DATA JEMAAT BUAT DROPDOWN
$list_jemaat = $conn->prepare("SELECT id, nama_lengkap FROM jemaat WHERE gereja_id=? ORDER BY nama_lengkap ASC");
$list_jemaat->execute([$gereja_id]);

// LIST DATA PELAYAN - NO HP AMBIL DARI JEMAAT
$data = $conn->prepare("SELECT p.*, j.nama_lengkap, j.foto, j.no_hp, g.nama_gereja 
                        FROM pelayan p 
                        INNER JOIN jemaat j ON p.jemaat_id=j.id 
                        INNER JOIN gereja g ON p.gereja_id=g.id 
                        WHERE p.gereja_id=? 
                        ORDER BY p.id DESC");
$data->execute([$gereja_id]);
?>

<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Data Pelayan</h1>
    <button class="btn btn-sm btn-primary shadow-sm" onclick="tambahPelayan()">
        <i class="fas fa-plus fa-sm text-white-50"></i> Tambah Pelayan
    </button>
</div>

<div class="card shadow mb-4">
    <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 Jemaat</th>
                        <th>Jabatan</th>
                        <th>No HP</th>
                        <th>Gereja</th>
                        <th width="100">Aksi</th>
                    </tr>
                </thead>
              <tbody>
    <?php $no=1; while($row = $data->fetch(PDO::FETCH_ASSOC)): ?>
    <tr>
        <td><?= $no++?></td>
        <td>
            <img src="<?= foto_jemaat($row['foto']) ?>" 
                 width="40" height="40" 
                 class="rounded-circle" 
                 style="object-fit:cover;" 
                 onerror="this.src='assets/img/jemaat/default.jpg'">
        </td>
        <td><?= htmlspecialchars($row['nama_lengkap'])?></td>
        <td><span class="badge badge-info"><?= htmlspecialchars($row['jabatan'])?></span></td>
        <td><?= $row['no_hp'] ?: '-' ?></td>
        <td><?= htmlspecialchars($row['nama_gereja'])?></td>
        <td>
            <button class="btn btn-warning btn-sm" onclick="editPelayan(<?= $row['id']?>)"><i class="fa fa-edit"></i></button>
            <button class="btn btn-danger btn-sm" onclick="hapusPelayan(<?= $row['id']?>)"><i class="fa fa-trash"></i></button>
        </td>
    </tr>
    <?php endwhile;?>
    <?php if($data->rowCount()==0):?>
    <tr><td colspan="7" class="text-center text-muted">Belum ada data pelayan</td></tr>
    <?php endif;?>
</tbody>
                    
            </table>
        </div>
    </div>
</div>

<!-- MODAL -->
<div class="modal fade" id="modalPelayan" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="formPelayan">
                <div class="modal-header">
                    <h5 class="modal-title">Form Pelayan</h5>
                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="id" id="id">
                    <input type="hidden" name="aksi" value="simpan">
                    
                    <div class="form-group">
                        <label>Pilih Jemaat *</label>
                        <select name="jemaat_id" id="jemaat_id" class="form-control" required>
                            <option value="">- Pilih Jemaat -</option>
                            <?php 
                            $list_jemaat->execute([$gereja_id]);
                            while($j = $list_jemaat->fetch(PDO::FETCH_ASSOC)):?>
                            <option value="<?= $j['id']?>"><?= htmlspecialchars($j['nama_lengkap'])?></option>
                            <?php endwhile;?>
                        </select>
                        <?php if($list_jemaat->rowCount()==0):?>
                        <small class="text-danger">Belum ada data jemaat. Input di menu Data Jemaat dulu.</small>
                        <?php endif;?>
                    </div>
                    
                    <div class="form-group">
                        <label>Jabatan *</label>
                        <select name="jabatan" id="jabatan" class="form-control" required>
                            <option value="">- Pilih Jabatan -</option>
                            <option>Wakil Gembala</option>
                            <option>Sekretaris</option>
                            <option>Bendahara</option>
                            <option>Diaken</option>
                            <option>Penatua</option>
                            <option>Worship Leader</option>
                            <option>Pemain Musik</option>
                            <option>Singer</option>
                            <option>Usher</option>
                            <option>Multimedia</option>
                        </select>
                    </div>
                    
                    <!-- NO HP UDAH DIHAPUS - AMBIL DARI DATA JEMAAT -->
                </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(){
    $('#dataTable').DataTable();
});

function tambahPelayan(){
    $('#formPelayan')[0].reset();
    $('#id').val('');
    $('.modal-title').text('Tambah Pelayan');
    $('#modalPelayan').modal('show');
}

function editPelayan(id){
    $.post('pages/pelayan.php', {aksi:'get',id:id}, function(res){
        $('#id').val(res.id);
        $('#jemaat_id').val(res.jemaat_id);
        $('#jabatan').val(res.jabatan);
        $('.modal-title').text('Edit Pelayan');
        $('#modalPelayan').modal('show');
    },'json');
}

function hapusPelayan(id){
    Swal.fire({
        title: 'Hapus Data?',
        text: "Data tidak bisa dikembalikan!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Ya, Hapus!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('pages/pelayan.php', {aksi:'hapus',id:id}, function(res){
                Swal.fire('Terhapus!','Data berhasil dihapus','success');
                loadPage('pelayan');
            },'json');
        }
    });
}

$('#formPelayan').submit(function(e){
    e.preventDefault();
    $('#btnSimpan').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Menyimpan...');
    
    $.post('pages/pelayan.php', $(this).serialize(), function(res){
        // TUTUP MODAL DULU BARU ALERT
        $('#modalPelayan').modal('hide');
        $('body').removeClass('modal-open');
        $('.modal-backdrop').remove();
        
        if(res.status=='sukses'){
            Swal.fire('Berhasil!','Data pelayan disimpan','success');
            loadPage('pelayan');
        } else {
            Swal.fire('Error',res.message,'error');
        }
    },'json').fail(function(){
        Swal.fire('Error','Gagal simpan data','error');
    }).always(function(){
        $('#btnSimpan').prop('disabled', false).html('Simpan');
    });
});

// FIX BACKDROP NYANGKUT
$('#modalPelayan').on('hidden.bs.modal', function () {
    $('body').removeClass('modal-open');
    $('.modal-backdrop').remove();
});
</script>