<?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'];
        $gelar_jabatan = $_POST['gelar_jabatan'];
        $tgl_lantik = $_POST['tgl_lantik']?: null;
        $tgl_berakhir = $_POST['tgl_berakhir']?: null;
        $status = $_POST['status'];
        $sk_nomor = $_POST['sk_nomor']?: null;
        $keterangan = $_POST['keterangan'];
        
        try {
            if($id == ''){
                $sql = "INSERT INTO pejabat (gereja_id, jemaat_id, gelar_jabatan, tgl_lantik, tgl_berakhir, status, sk_nomor, keterangan) VALUES (?,?,?,?,?,?,?,?)";
                $conn->prepare($sql)->execute([$gereja_id, $jemaat_id, $gelar_jabatan, $tgl_lantik, $tgl_berakhir, $status, $sk_nomor, $keterangan]);
            } else {
                $sql = "UPDATE pejabat SET jemaat_id=?, gelar_jabatan=?, tgl_lantik=?, tgl_berakhir=?, status=?, sk_nomor=?, keterangan=? WHERE id=? AND gereja_id=?";
                $conn->prepare($sql)->execute([$jemaat_id, $gelar_jabatan, $tgl_lantik, $tgl_berakhir, $status, $sk_nomor, $keterangan, $id, $gereja_id]);
            }
            echo json_encode(['status'=>'sukses']);
        } catch (PDOException $e) {
            echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
        }
        exit;
    }
    
    // 2. HAPUS
    if($_POST['aksi'] == 'hapus'){
        $conn->prepare("DELETE FROM pejabat 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 pejabat 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 PEJABAT - JOIN JEMAAT BUAT AMBIL FOTO
$data = $conn->prepare("SELECT p.*, j.nama_lengkap, j.foto 
                        FROM pejabat p 
                        INNER JOIN jemaat j ON p.jemaat_id=j.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">Input Pejabat Gereja</h1>
    <button class="btn btn-sm btn-primary shadow-sm" onclick="tambahPejabat()">
        <i class="fas fa-plus fa-sm text-white-50"></i> Tambah Pejabat
    </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 Pejabat</th>
                        <th>Gelar Jabatan</th>
                        <th>Tgl Lantik</th>
                        <th>Masa Jabatan</th>
                        <th>Status</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-primary"><?= htmlspecialchars($row['gelar_jabatan'])?></span></td>
        <td><?= format_tanggal($row['tgl_lantik']) ?></td>
        <td><?= masa_jabatan($row['tgl_lantik'], $row['tgl_berakhir']) ?></td>
        <td><span class="badge badge-<?= badge_status($row['status']) ?>"><?= $row['status']?></span></td>
        <td>
            <button class="btn btn-warning btn-sm" onclick="editPejabat(<?= $row['id']?>)"><i class="fa fa-edit"></i></button>
            <button class="btn btn-danger btn-sm" onclick="hapusPejabat(<?= $row['id']?>)"><i class="fa fa-trash"></i></button>
        </td>
    </tr>
    <?php endwhile;?>
    <?php if($data->rowCount()==0):?>
    <tr><td colspan="8" class="text-center text-muted">Belum ada data pejabat</td></tr>
    <?php endif;?>
</tbody>
            </table>
        </div>
    </div>
</div>

<!-- MODAL -->
<div class="modal fade" id="modalPejabat" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="formPejabat">
                <div class="modal-header">
                    <h5 class="modal-title">Form Pejabat</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>
                    </div>
                    
                    <div class="form-group">
                        <label>Gelar Jabatan *</label>
                        <select name="gelar_jabatan" id="gelar_jabatan" class="form-control" required>
                            <option value="">- Pilih Jabatan -</option>
                            <option>Pendeta Penuh (pdt)</option>
                            <option>Pendeta Penuh (pdt)</option>
                            <option>Gembala Sidang</option>
                            <option>Gembala Jemaat</option>
                            <option>Pendeta Muda (pdm)</option>
                            <option>Pendeta Pembantu (Pdp)</option>
                            <option>Penatua</option>
                            <option>Diaken</option>
                            <option>Rasul</option>
                            <option>Nabi</option>
                            <option>Guru</option>
                            <option>Penginjil</option>
                            <option>Evangelist</option> 
                        </select>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Tgl Lantik</label>
                                <input type="date" name="tgl_lantik" id="tgl_lantik" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Tgl Berakhir</label>
                                <input type="date" name="tgl_berakhir" id="tgl_berakhir" class="form-control">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Status *</label>
                                <select name="status" id="status" class="form-control" required>
                                    <option>Aktif</option>
                                    <option>Non-Aktif</option>
                                    <option>Pensiun</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>SK Nomor</label>
                                <input type="text" name="sk_nomor" id="sk_nomor" class="form-control" placeholder="SK.001/GBI/2024">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Keterangan</label>
                        <textarea name="keterangan" id="keterangan" class="form-control" rows="2"></textarea>
                    </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(){
    $('#dataTable').DataTable();
});

function tambahPejabat(){
    $('#formPejabat')[0].reset();
    $('#id').val('');
    $('.modal-title').text('Tambah Pejabat');
    $('#modalPejabat').modal('show');
}

function editPejabat(id){
    $.post('pages/pejabat.php', {aksi:'get',id:id}, function(res){
        $('#id').val(res.id);
        $('#jemaat_id').val(res.jemaat_id);
        $('#gelar_jabatan').val(res.gelar_jabatan);
        $('#tgl_lantik').val(res.tgl_lantik);
        $('#tgl_berakhir').val(res.tgl_berakhir);
        $('#status').val(res.status);
        $('#sk_nomor').val(res.sk_nomor);
        $('#keterangan').val(res.keterangan);
        $('.modal-title').text('Edit Pejabat');
        $('#modalPejabat').modal('show');
    },'json');
}

function hapusPejabat(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/pejabat.php', {aksi:'hapus',id:id}, function(res){
                Swal.fire('Terhapus!','Data berhasil dihapus','success');
                loadPage('pejabat');
            },'json');
        }
    });
}

$('#formPejabat').submit(function(e){
    e.preventDefault();
    $('#btnSimpan').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Menyimpan...');
    
    $.post('pages/pejabat.php', $(this).serialize(), function(res){
        $('#modalPejabat').modal('hide');
        $('body').removeClass('modal-open');
        $('.modal-backdrop').remove();
        
        if(res.status=='sukses'){
            Swal.fire('Berhasil!','Data pejabat disimpan','success');
            loadPage('pejabat');
        } 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');
    });
});
</script>