<?php
session_start();
if(!isset($_SESSION['user_id'])) die('Akses ditolak');
$role = $_SESSION['role'];

$list_jabatan = [
    'Ketua DPW Keerom',
    'Wakil Ketua I',
    'Wakil Ketua II',
    'Sekretaris DPW',
    'Wakil Sekretaris',
    'Bendahara DPW',
    'Wakil Bendahara',
    'Ketua Bidang Ibadah',
    'Ketua Bidang Pemuda',
    'Ketua Bidang Wanita',
    'Ketua Bidang Anak',
    'Ketua Bidang Misi',
    'Ketua Bidang Diakonia'
];
?>
<h1 class="h3 mb-4 text-gray-800">Pengurus DPW Keerom</h1>

<div class="row">
    <div class="col-lg-4">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary" id="judulForm">Tambah Pengurus</h6>
            </div>
            <div class="card-body">
                <form id="formPengurus" enctype="multipart/form-data">
                    <input type="hidden" name="id" id="id">
                    <input type="hidden" name="foto_lama" id="foto_lama">
                    <input type="hidden" name="action" value="simpan">

                    <div class="form-group">
                        <label>Nama Lengkap <span class="text-danger">*</span></label>
                        <input type="text" name="nama_lengkap" id="nama_lengkap" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>Jabatan <span class="text-danger">*</span></label>
                        <select name="jabatan" id="jabatan" class="form-control" required>
                            <option value="">- Pilih Jabatan -</option>
                            <?php foreach($list_jabatan as $jab):?>
                            <option value="<?= $jab?>"><?= $jab?></option>
                            <?php endforeach;?>
                            <option value="Lainnya">Lainnya...</option>
                        </select>
                        <input type="text" name="jabatan_lain" id="jabatan_lain" class="form-control mt-2" placeholder="Ketik jabatan lain..." style="display:none;">
                    </div>

                    <div class="form-group">
                        <label>No. HP</label>
                        <input type="text" name="no_hp" id="no_hp" class="form-control" placeholder="08xxxx">
                    </div>

                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" id="email" class="form-control" placeholder="email@contoh.com">
                    </div>

                    <div class="row">
                        <div class="col-6">
                            <div class="form-group">
                                <label>Periode Mulai</label>
                                <input type="number" name="periode_mulai" id="periode_mulai" class="form-control" value="<?= date('Y')?>" min="2000" max="2100">
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <label>Periode Selesai</label>
                                <input type="number" name="periode_selesai" id="periode_selesai" class="form-control" value="<?= date('Y')+4?>" min="2000" max="2100">
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Urutan Tampil</label>
                        <input type="number" name="urutan" id="urutan" class="form-control" value="0">
                        <small class="text-muted">1 = Ketua, 2 = Wakil, dst</small>
                    </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 class="form-group">
                        <label>Foto</label>
                        <input type="file" name="foto" id="foto" class="form-control-file" accept="image/*">
                        <div class="mt-2 text-center">
                            <img id="preview_foto" src="assets/img/users/default.png" width="120" class="img-thumbnail rounded-circle">
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary btn-block" id="btnSimpan">
                        <i class="fa fa-save"></i> Simpan
                    </button>
                    <button type="button" class="btn btn-secondary btn-block" id="btnReset" style="display:none;">
                        <i class="fa fa-times"></i> Batal Edit
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">Daftar Pengurus DPW</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="tabelPengurus" width="100%">
                        <thead class="bg-primary text-white">
                            <tr>
                                <th width="5%">No</th>
                                <th width="10%">Foto</th>
                                <th>Nama</th>
                                <th>Jabatan</th>
                                <th>Periode</th>
                                <th>Kontak</th>
                                <th width="8%">Status</th>
                                <th width="12%">Aksi</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
if(typeof window.pengurusLoaded === 'undefined'){
    window.pengurusLoaded = true;

    function loadPengurus(){
        $.get('api/pengurus_dpw.php?action=get', function(res){
            let html = '';
            if(res.status=='success' && res.data.length > 0){
                res.data.forEach((d,i)=>{
                    let foto = d.foto? `assets/img/pengurus/${d.foto}` : 'assets/img/users/default.png';
                    let badge = d.status=='Aktif'? 'success' : 'danger';
                    let kontak = '';
                    if(d.no_hp) kontak += `<i class="fa fa-phone"></i> ${d.no_hp}<br>`;
                    if(d.email) kontak += `<i class="fa fa-envelope"></i> ${d.email}`;

                    html += `<tr>
                        <td class="text-center">${i+1}</td>
                        <td class="text-center">
                            <img src="${foto}" width="50" height="50" class="img-thumbnail rounded-circle"
                                 style="object-fit:cover" onerror="this.src='assets/img/users/default.png'">
                        </td>
                        <td><b>${d.nama_lengkap}</b></td>
                        <td>${d.jabatan}</td>
                        <td>${d.periode_mulai} - ${d.periode_selesai}</td>
                        <td style="font-size:11px">${kontak||'-'}</td>
                        <td><span class="badge badge-${badge}">${d.status}</span></td>
                        <td>
                            <button class="btn btn-warning btn-sm btn-edit" data-id="${d.id}" title="Edit">
                                <i class="fa fa-edit"></i>
                            </button>
                            <button class="btn btn-danger btn-sm btn-hapus" data-id="${d.id}" data-nama="${d.nama_lengkap}" title="Hapus">
                                <i class="fa fa-trash"></i>
                            </button>
                        </td>
                    </tr>`;
                });
            } else {
                html = '<tr><td colspan="8" class="text-center text-muted">Belum ada data pengurus</td></tr>';
            }
            $('#tabelPengurus tbody').html(html);

            if($.fn.DataTable.isDataTable('#tabelPengurus')) {
                $('#tabelPengurus').DataTable().destroy();
            }
            $('#tabelPengurus').DataTable({
                "order": [[7, "asc"]], // Order by urutan
                "pageLength": 25
            });
        });
    }

    // Toggle jabatan lain
    $('#jabatan').change(function(){
        if($(this).val() == 'Lainnya'){
            $('#jabatan_lain').show().prop('required', true);
        } else {
            $('#jabatan_lain').hide().prop('required', false).val('');
        }
    });

    // Submit form
    $('#formPengurus').submit(function(e){
        e.preventDefault();

        // Handle jabatan lain
        if($('#jabatan').val() == 'Lainnya'){
            $('#jabatan').append(`<option value="${$('#jabatan_lain').val()}" selected>${$('#jabatan_lain').val()}</option>`);
        }

        $('#btnSimpan').html('<i class="fa fa-spinner fa-spin"></i> Menyimpan...').prop('disabled', true);

        $.ajax({
            url:'api/pengurus_dpw.php',
            type:'POST',
            data:new FormData(this),
            processData:false,
            contentType:false,
            dataType:'json',
            success:function(res){
                if(res.status=='sukses'){
                    Swal.fire('Sukses',res.message,'success');
                    resetForm();
                    loadPengurus();
                } else {
                    Swal.fire('Error',res.message,'error');
                }
            },
            error: function(xhr){
                Swal.fire('Error','Gagal simpan: '+xhr.statusText,'error');
            },
            complete: function(){
                $('#btnSimpan').html('<i class="fa fa-save"></i> Simpan').prop('disabled', false);
            }
        });
    });

    // Edit
    $(document).on('click', '.btn-edit', function(){
        let id = $(this).data('id');
        $.get('api/pengurus_dpw.php?action=detail&id='+id, function(res){
            if(res.status=='success'){
                let d = res.data;
                $('#id').val(d.id);
                $('#nama_lengkap').val(d.nama_lengkap);
                $('#jabatan').val(d.jabatan);
                $('#no_hp').val(d.no_hp);
                $('#email').val(d.email);
                $('#periode_mulai').val(d.periode_mulai);
                $('#periode_selesai').val(d.periode_selesai);
                $('#urutan').val(d.urutan);
                $('#status').val(d.status);
                $('#foto_lama').val(d.foto);

                if(d.foto && d.foto!= 'default.png'){
                    $('#preview_foto').attr('src', 'assets/img/pengurus/'+d.foto);
                } else {
                    $('#preview_foto').attr('src', 'assets/img/users/default.png');
                }

                $('#judulForm').text('Edit Pengurus');
                $('#btnReset').show();
                $('html, body').animate({scrollTop: 0}, 500);
            }
        });
    });

    // Hapus
    $(document).on('click', '.btn-hapus', function(){
        let id = $(this).data('id');
        let nama = $(this).data('nama');
        Swal.fire({
            title:'Hapus Pengurus?',
            text: nama+' akan dihapus permanen!',
            icon:'warning',
            showCancelButton:true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Ya, Hapus!',
            cancelButtonText: 'Batal'
        }).then(r=>{
            if(r.isConfirmed){
                $.post('api/pengurus_dpw.php', {action:'hapus', id:id}, res=>{
                    if(res.status=='sukses'){
                        Swal.fire('Terhapus!','Data berhasil dihapus','success');
                        loadPengurus();
                    } else {
                        Swal.fire('Error',res.message,'error');
                    }
                },'json');
            }
        });
    });

    // Reset form
    function resetForm(){
        $('#formPengurus')[0].reset();
        $('#id').val('');
        $('#foto_lama').val('');
        $('#preview_foto').attr('src', 'assets/img/users/default.png');
        $('#jabatan_lain').hide().prop('required', false);
        $('#judulForm').text('Tambah Pengurus');
        $('#btnReset').hide();
    }

    $('#btnReset').click(function(){
        resetForm();
    });

    // Preview foto
    $('#foto').change(function(){
        const file = this.files[0];
        if(file){
            if(file.size > 2097152){
                Swal.fire('Error','Ukuran foto max 2MB','error');
                $(this).val('');
                return;
            }
            let reader = new FileReader();
            reader.onload = e => $('#preview_foto').attr('src', e.target.result);
            reader.readAsDataURL(file);
        }
    });

    loadPengurus();
}
</script>