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

$gereja_id = $_SESSION['gereja_id'];

// HANDLE SIMPAN
if(isset($_POST['aksi']) && $_POST['aksi'] == 'simpan'){
    header('Content-Type: application/json');
    // HITUNG ULANG DI SERVER BIAR AMAN
    $total = (int)$_POST['jumlah_laki'] + (int)$_POST['jumlah_perempuan'] + (int)$_POST['jumlah_anak'];
    
    $sql = "INSERT INTO absensi (gereja_id, tanggal, jumlah_hadir, jumlah_laki, jumlah_perempuan, jumlah_anak, keterangan) VALUES (?,?,?,?,?,?,?)";
    $simpan = $conn->prepare($sql)->execute([
        $gereja_id, $_POST['tanggal'], $total,
        $_POST['jumlah_laki'], $_POST['jumlah_perempuan'], $_POST['jumlah_anak'], $_POST['keterangan']
    ]);
    echo json_encode(['status'=>$simpan?'sukses':'gagal']);
    exit;
}

// HANDLE HAPUS
if(isset($_POST['aksi']) && $_POST['aksi'] == 'hapus'){
    header('Content-Type: application/json');
    $hapus = $conn->prepare("DELETE FROM absensi WHERE id=? AND gereja_id=?")->execute([$_POST['id'], $gereja_id]);
    echo json_encode(['status'=>$hapus?'sukses':'gagal']);
    exit;
}

// DATA ABSENSI
$list = $conn->prepare("SELECT * FROM absensi WHERE gereja_id=? ORDER BY tanggal DESC");
$list->execute([$gereja_id]);
?>

<h1 class="h3 mb-4 text-gray-800">Data Absensi Ibadah</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">Input Absensi Baru</h6></div>
            <div class="card-body">
                <form id="formAbsensi">
                    <input type="hidden" name="aksi" value="simpan">
                    <div class="form-group">
                        <label>Tanggal Ibadah</label>
                        <input type="date" name="tanggal" class="form-control" value="<?= date('Y-m-d')?>" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-4"><div class="form-group">
                            <label>Laki-laki</label>
                            <input type="number" name="jumlah_laki" id="jml_laki" class="form-control jml" min="0" value="0">
                        </div></div>
                        <div class="col-4"><div class="form-group">
                            <label>Perempuan</label>
                            <input type="number" name="jumlah_perempuan" id="jml_perempuan" class="form-control jml" min="0" value="0">
                        </div></div>
                        <div class="col-4"><div class="form-group">
                            <label>Anak-anak</label>
                            <input type="number" name="jumlah_anak" id="jml_anak" class="form-control jml" min="0" value="0">
                        </div></div>
                    </div>

                    <!-- TOTAL HADIR PINDAH KE BAWAH + READONLY -->
                    <div class="form-group">
                        <label>Total Hadir</label>
                        <input type="number" name="jumlah_hadir" id="jml_hadir" class="form-control bg-light font-weight-bold" readonly value="0">
                    </div>

                    <div class="form-group">
                        <label>Keterangan</label>
                        <input type="text" name="keterangan" class="form-control" placeholder="Contoh: Ibadah Minggu">
                    </div>
                    <button type="submit" class="btn btn-primary btn-block" id="btnSimpan"><i class="fa fa-save"></i> Simpan Absensi</button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">Riwayat Absensi</h6>
                <a href="api/cetak_absensi_pdf.php" target="_blank" class="btn btn-danger btn-sm"><i class="fa fa-file-pdf"></i> Cetak PDF</a>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-sm" id="tableAbsensi">
                        <thead>
                            <tr>
                                <th>Tanggal</th>
                                <th>Total</th>
                                <th>L</th>
                                <th>P</th>
                                <th>Anak</th>
                                <th>Ket</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($a = $list->fetch(PDO::FETCH_ASSOC)):?>
                            <tr>
                                <td><?= date('d/m/Y',strtotime($a['tanggal']))?></td>
                                <td><b><?= $a['jumlah_hadir']?></b></td>
                                <td><?= $a['jumlah_laki']?></td>
                                <td><?= $a['jumlah_perempuan']?></td>
                                <td><?= $a['jumlah_anak']?></td>
                                <td><?= htmlspecialchars($a['keterangan']?:'-')?></td>
                                <td><button class="btn btn-danger btn-sm" onclick="hapusAbsensi(<?= $a['id']?>)"><i class="fa fa-trash"></i></button></td>
                            </tr>
                            <?php endwhile;?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// AUTO JUMLAH SAAT KETIK
$('.jml').on('keyup change', function(){
    let laki = parseInt($('#jml_laki').val()) || 0;
    let perempuan = parseInt($('#jml_perempuan').val()) || 0;
    let anak = parseInt($('#jml_anak').val()) || 0;
    $('#jml_hadir').val(laki + perempuan + anak);
});

$('#formAbsensi').submit(function(e){
    e.preventDefault();
    // CEK TOTAL GAK BOLEH 0
    if($('#jml_hadir').val() == 0){
        Swal.fire('Error','Total hadir tidak boleh 0','warning');
        return false;
    }
    $('#btnSimpan').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Menyimpan...');
    $.ajax({
        url: 'pages/absensi.php', type: 'POST', data: $(this).serialize(), dataType: 'json',
        success: function(res){
            if(res.status=='sukses'){
                Swal.fire('Berhasil!','Data absensi tersimpan','success').then(()=>loadPage('absensi'));
            } else {
                Swal.fire('Gagal!','Gagal simpan data','error');
            }
        },
        complete: function(){$('#btnSimpan').prop('disabled', false).html('<i class="fa fa-save"></i> Simpan Absensi');}
    });
});

function hapusAbsensi(id){
    Swal.fire({
        title: 'Hapus Data?', text: "Data absensi akan dihapus!", icon: 'warning',
        showCancelButton: true, confirmButtonText: 'Ya, Hapus!', cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('pages/absensi.php', {aksi:'hapus', id:id}, function(res){
                if(res.status=='sukses'){
                    Swal.fire('Terhapus!','Data berhasil dihapus','success').then(()=>loadPage('absensi'));
                }
            },'json');
        }
    });
}
</script>