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

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'];

// ===== TAMBAHAN HAK AKSES UNTUK BENDAHARA =====
if($role == 'bendahara'){
    // Cek apakah bendahara punya akses ke menu keuangan + ambil gereja_id
    $cek = $conn->prepare("SELECT gereja_id FROM user_akses WHERE user_id=? AND menu='keuangan'");
    $cek->execute([$user_id]);
    $gereja_id = $cek->fetchColumn();

    if(!$gereja_id){
        die('<div class="alert alert-danger"><i class="fa fa-ban"></i> Anda tidak punya akses ke menu Input Keuangan!</div>');
    }
}
else if($role == 'gembala'){
    // Gembala ambil gereja_id normal
    $q = $conn->prepare("SELECT id FROM gereja WHERE gembala_id=? LIMIT 1");
    $q->execute([$user_id]);
    $gereja_id = $q->fetchColumn();

    if(!$gereja_id){
        die('<div class="alert alert-danger">Akun gembala belum terhubung ke gereja. Hubungi admin.</div>');
    }
}
else {
    die('<div class="alert alert-danger"><i class="fa fa-ban"></i> Akses ditolak!</div>');
}
// ===== END TAMBAHAN HAK AKSES =====

$aksi = $_POST['aksi']?? '';

// SIMPAN DATA
if($aksi == 'simpan'){
    $id = $_POST['id'];
    $tanggal = $_POST['tanggal'];
    $tipe = $_POST['tipe'];
    $jenis = $_POST['jenis'];
    $jumlah = str_replace(['Rp. ','.'], '', $_POST['jumlah']);
    $keterangan = $_POST['keterangan'];

    if($id == ''){
        $sql = "INSERT INTO keuangan (tanggal, tipe, jenis, jumlah, keterangan, gereja_id) VALUES (?,?,?,?,?,?)";
        $conn->prepare($sql)->execute([$tanggal, $tipe, $jenis, $jumlah, $keterangan, $gereja_id]);
    } else {
        $sql = "UPDATE keuangan SET tanggal=?, tipe=?, jenis=?, jumlah=?, keterangan=? WHERE id=? AND gereja_id=?";
        $conn->prepare($sql)->execute([$tanggal, $tipe, $jenis, $jumlah, $keterangan, $id, $gereja_id]);
    }
    echo json_encode(['status'=>'sukses']);
    exit;
}

// HAPUS
if($aksi == 'hapus'){
    $conn->prepare("DELETE FROM keuangan WHERE id=? AND gereja_id=?")->execute([$_POST['id'], $gereja_id]);
    echo json_encode(['status'=>'sukses']);
    exit;
}

// GET DATA BUAT EDIT
if($aksi == 'get'){
    $stmt = $conn->prepare("SELECT * FROM keuangan WHERE id=? AND gereja_id=?");
    $stmt->execute([$_POST['id'], $gereja_id]);
    echo json_encode($stmt->fetch(PDO::FETCH_ASSOC));
    exit;
}

// LIST DATA KEUANGAN
$data = $conn->prepare("SELECT * FROM keuangan WHERE gereja_id=? ORDER BY tanggal DESC, id DESC");
$data->execute([$gereja_id]);

// HITUNG SALDO
$saldo = $conn->prepare("SELECT
    SUM(CASE WHEN tipe='Pemasukan' THEN jumlah ELSE 0 END) as masuk,
    SUM(CASE WHEN tipe='Pengeluaran' THEN jumlah ELSE 0 END) as keluar
    FROM keuangan WHERE gereja_id=?");
$saldo->execute([$gereja_id]);
$s = $saldo->fetch(PDO::FETCH_ASSOC);
$total_saldo = $s['masuk'] - $s['keluar'];
?>

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

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">Form Input Keuangan</h6>
    </div>
    <div class="card-body">
        <form id="formKeuangan">
            <input type="hidden" name="id" id="id">
            <input type="hidden" name="aksi" value="simpan">
            <div class="form-row">
                <div class="form-group col-md-2">
                    <label>Tanggal</label>
                    <input type="date" name="tanggal" id="tanggal" class="form-control" value="<?= date('Y-m-d')?>" required>
                </div>
                <div class="form-group col-md-2">
                    <label>Tipe</label>
                    <select name="tipe" id="tipe" class="form-control" required onchange="gantiJenis()">
                        <option value="">- Pilih -</option>
                        <option value="Pemasukan">Pemasukan</option>
                        <option value="Pengeluaran">Pengeluaran</option>
                    </select>
                </div>
                <div class="form-group col-md-3">
                    <label>Jenis</label>
                    <select name="jenis" id="jenis" class="form-control" required>
                        <option value="">- Pilih Tipe Dulu -</option>
                        <option value="Persembahan">Persembahan</option>
                        <option value="Extra Kolekte">Extra Kolekte</option>
                        <option value="Diakonia">Diakonia</option>
                        <option value="Pembangunan">Pembangunan</option>
                        <option value="dll">dll</option>                      
                      </select>
                </div>
                <div class="form-group col-md-2">
                    <label>Jumlah Rp</label>
                    <input type="text" name="jumlah" id="jumlah" class="form-control rupiah" required>
                </div>
                <div class="form-group col-md-3">
                    <label>Keterangan</label>
                    <input type="text" name="keterangan" id="keterangan" class="form-control">
                </div>
            </div>
            <button type="submit" class="btn btn-primary btn-sm" id="btnSimpan"><i class="fa fa-save"></i> Simpan</button>
            <button type="button" class="btn btn-secondary btn-sm" onclick="resetForm()">Reset</button>
        </form>
    </div>
</div>

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">Data Keuangan</h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered" id="tabelKeuangan">
               <thead>
                    <tr>
                        <th width="50">No</th>
                        <th>Tanggal</th>
                        <th>Tipe</th>
                        <th>Jenis</th>
                        <th>Pemasukan</th>
                        <th>Pengeluaran</th>
                        <th>Keterangan</th>
                        <th width="100">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $no=1; while($row = $data->fetch(PDO::FETCH_ASSOC)):?>
                    <tr>
                        <td><?= $no++?></td>
                        <td><?= date('d/m/Y', strtotime($row['tanggal']))?></td>
                        <td>
                            <?php if($row['tipe']=='Pemasukan'):?>
                                <span class="badge badge-success"><?= $row['tipe']?></span>
                            <?php else:?>
                                <span class="badge badge-danger"><?= $row['tipe']?></span>
                            <?php endif;?>
                        </td>
                        <td><?= $row['jenis']?></td>
                        <td align="right"><?= $row['tipe']=='Pemasukan'? 'Rp '.number_format($row['jumlah'],0,',','.') : '-'?></td>
                        <td align="right"><?= $row['tipe']=='Pengeluaran'? 'Rp '.number_format($row['jumlah'],0,',','.') : '-'?></td>
                        <td><?= $row['keterangan']?></td>
                        <td>
                            <button class="btn btn-warning btn-sm" onclick="editData(<?= $row['id']?>)"><i class="fa fa-edit"></i></button>
                            <button class="btn btn-danger btn-sm" onclick="hapusData(<?= $row['id']?>)"><i class="fa fa-trash"></i></button>
                        </td>
                    </tr>
                    <?php endwhile;?>
                    <?php if($no == 1):?>
                    <tr>
                        <td colspan="8" class="text-center">Belum ada data keuangan</td>
                    </tr>
                    <?php endif;?>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="4">Total</th>
                        <th style="text-align:right" class="text-success">Rp <?= number_format($s['masuk'],0,',','.')?></th>
                        <th style="text-align:right" class="text-danger">Rp <?= number_format($s['keluar'],0,',','.')?></th>
                        <th colspan="2" style="text-align:right">
                            <strong>Saldo: Rp <?= number_format($total_saldo,0,',','.')?></strong>
                        </th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<script>
const jenisPemasukan = ['Perpuluhan','Kolekte','Extra Kolekte','Diakonia','Persembahan','Pembangunan','Lainnya'];
const jenisPengeluaran = ['Pembangunan','Operasional','Listrik/Air','Konsumsi','Transport','ATK','Diakonia','Honor Pelayan','Lainnya'];

function gantiJenis(){
    let tipe = $('#tipe').val();
    let option = '<option value="">- Pilih Jenis -</option>';
    let list = tipe == 'Pemasukan'? jenisPemasukan : jenisPengeluaran;

    if(tipe!= ''){
        list.forEach(function(item){
            option += `<option value="${item}">${item}</option>`;
        });
    } else {
        option = '<option value="">- Pilih Tipe Dulu -</option>';
    }
    $('#jenis').html(option);
}

// Format Rupiah
$('.rupiah').on('keyup', function(){
    $(this).val(formatRupiah($(this).val(), 'Rp. '));
});

function formatRupiah(angka, prefix){
    var number_string = angka.replace(/[^,\d]/g, '').toString(),
    split = number_string.split(','),
    sisa = split[0].length % 3,
    rupiah = split[0].substr(0, sisa),
    ribuan = split[0].substr(sisa).match(/\d{3}/gi);
    if(ribuan){
        separator = sisa? '.' : '';
        rupiah += separator + ribuan.join('.');
    }
    rupiah = split[1]!= undefined? rupiah + ',' + split[1] : rupiah;
    return prefix == undefined? rupiah : (rupiah? 'Rp. ' + rupiah : '');
}

function resetForm(){
    $('#formKeuangan')[0].reset();
    $('#id').val('');
    $('#tanggal').val('<?= date('Y-m-d')?>');
    $('#jenis').html('<option value="">- Pilih Tipe Dulu -</option>');
    $('#btnSimpan').html('<i class="fa fa-save"></i> Simpan');
}

function editData(id){
    $.post('pages/keuangan.php', {aksi:'get',id:id}, function(res){
        let d = JSON.parse(res);
        $('#id').val(d.id);
        $('#tanggal').val(d.tanggal);
        $('#tipe').val(d.tipe);
        gantiJenis();
        setTimeout(function(){ $('#jenis').val(d.jenis); }, 100);
        $('#jumlah').val(formatRupiah(d.jumlah, 'Rp. '));
        $('#keterangan').val(d.keterangan);
        $('#btnSimpan').html('<i class="fa fa-save"></i> Update');
        $('html, body').animate({scrollTop: 0}, 'slow');
    });
}

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

$('#formKeuangan').submit(function(e){
    e.preventDefault();
    $('#btnSimpan').prop('disabled', true).html('Menyimpan...');

    $.post('pages/keuangan.php', $(this).serialize(), function(res){
        Swal.fire('Berhasil!','Data keuangan disimpan','success');
        loadPage('keuangan');
    }).fail(function(){
        Swal.fire('Error','Gagal simpan data','error');
    }).always(function(){
        $('#btnSimpan').prop('disabled', false).html('<i class="fa fa-save"></i> Simpan');
    });
});

$('#tabelKeuangan').DataTable({
    "order": []
});
</script>