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

if($_SESSION['role']!= 'bendahara'){
    header('Location:../index.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$gereja_id = $_SESSION['gereja_id'];
$nama_gereja = $_SESSION['nama_gereja'];
$nama_bendahara = $_SESSION['nama'];

// CEK HAK AKSES
$cek = $conn->prepare("SELECT id FROM user_akses WHERE user_id=? AND menu='keuangan' AND gereja_id=?");
$cek->execute([$user_id, $gereja_id]);
if($cek->rowCount() == 0){
    die('<script>alert("Akses Ditolak!");window.location="../logout.php"</script>');
}

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

// AJAX HANDLER
if(!empty($aksi)){
    header('Content-Type: application/json');

    if($aksi == 'simpan'){
        try {
            $id = $_POST['id'];
            $tanggal = $_POST['tanggal'];
            $tipe = $_POST['tipe'];
            $jenis = $_POST['jenis'];
            $jumlah = preg_replace("/[^0-9]/", "", $_POST['jumlah']);
            $keterangan = $_POST['keterangan'];

            if(empty($tanggal) || empty($tipe) || empty($jenis) || empty($jumlah)){
                echo json_encode(['status'=>'error','message'=>'Tanggal, Tipe, Jenis, dan Jumlah wajib diisi']);
                exit;
            }

            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]);
                $msg = 'Transaksi berhasil disimpan';
            } 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]);
                $msg = 'Transaksi berhasil diupdate';
            }
            echo json_encode(['status'=>'sukses','message'=>$msg]);
        } catch (PDOException $e) {
            echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
        }
        exit;
    }

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

    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;
    }
}

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

$saldo = $conn->prepare("SELECT
    COALESCE(SUM(CASE WHEN tipe='Pemasukan' THEN jumlah ELSE 0 END),0) as masuk,
    COALESCE(SUM(CASE WHEN tipe='Pengeluaran' THEN jumlah ELSE 0 END),0) as keluar
    FROM keuangan WHERE gereja_id=?");
$saldo->execute([$gereja_id]);
$s = $saldo->fetch(PDO::FETCH_ASSOC);
$total_saldo = $s['masuk'] - $s['keluar'];
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input Keuangan - <?= $nama_gereja?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <style>
        body{background: #f8f9fc!important; font-family: 'Nunito', sans-serif!important;}
      .bg-gradient-success{background: linear-gradient(180deg,#1cc88a 10%,#13855c 100%)!important;}

        /* CARD WARNA PASTEL */
      .card-stat {
            border: none!important;
            border-radius: 15px!important;
            overflow: hidden!important;
            transition: transform 0.2s!important;
            box-shadow: 0 0.5rem 1rem rgba(0,0,0,.1)!important;
        }
      .card-stat:hover {transform: translateY(-5px)!important;}

        /* KUNING MUDA - PEMASUKAN */
      .bg-kuning-muda {
            background: #FFF3CD!important;
            color: #856404!important;
        }

        /* UNGU MUDA - PENGELUARAN */
      .bg-ungu-muda {
            background: #E2D9F3!important;
            color: #5A2D82!important;
        }

        /* BIRU MUDA - SALDO */
      .bg-biru-muda {
            background: #CCE5FF!important;
            color: #004085!important;
        }

      .card-stat.card-body {padding: 1.5rem!important;}
      .card-stat.text-dark-75 {color: rgba(0,0,0,.6)!important;}
      .icon-stat {opacity: 0.5!important; font-size: 3.5rem!important;}
    </style>
</head>
<body>

<nav class="navbar navbar-expand navbar-dark bg-gradient-success shadow mb-4">
    <div class="container-fluid">
        <a class="navbar-brand" href="#"><i class="fas fa-church"></i> <b>SIMJEDPW</b> - Bendahara</a>
        <ul class="navbar-nav ml-auto">
            <li class="nav-item text-white mr-3">
                <small><?= $nama_gereja?> | <?= $nama_bendahara?></small>
            </li>
            <li class="nav-item">
                <a class="btn btn-light btn-sm" href="../logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </li>
        </ul>
    </div>
</nav>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800"><i class="fas fa-money-bill-wave"></i> Input Keuangan Gereja</h1>

    <!-- CARD SALDO WARNA PASTEL -->
    <div class="row">
        <!-- TOTAL PEMASUKAN - KUNING MUDA -->
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card card-stat bg-kuning-muda">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-dark-75 text-uppercase mb-1">
                                Total Pemasukan
                            </div>
                            <div class="h3 mb-0 font-weight-bold">Rp <?= number_format($s['masuk'],0,',','.')?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-arrow-circle-down icon-stat"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- TOTAL PENGELUARAN - UNGU MUDA -->
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card card-stat bg-ungu-muda">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-dark-75 text-uppercase mb-1">
                                Total Pengeluaran
                            </div>
                            <div class="h3 mb-0 font-weight-bold">Rp <?= number_format($s['keluar'],0,',','.')?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-arrow-circle-up icon-stat"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- SALDO AKHIR - BIRU MUDA -->
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card card-stat bg-biru-muda">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-dark-75 text-uppercase mb-1">
                                Saldo Akhir
                            </div>
                            <div class="h3 mb-0 font-weight-bold">Rp <?= number_format($total_saldo,0,',','.')?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-wallet icon-stat"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- FORM INPUT -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-success"><i class="fa fa-edit"></i> Form Input Transaksi</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>
                        </select>
                    </div>
                    <div class="form-group col-md-2">
                        <label>Jumlah Rp *</label>
                        <input type="text" name="jumlah" id="jumlah" class="form-control rupiah" placeholder="0" required>
                    </div>
                    <div class="form-group col-md-3">
                        <label>Keterangan</label>
                        <input type="text" name="keterangan" id="keterangan" class="form-control" placeholder="Opsional">
                    </div>
                <button type="submit" class="btn btn-success" id="btnSimpan"><i class="fa fa-save"></i> Simpan Transaksi</button>
                <button type="button" class="btn btn-secondary" onclick="resetForm()"><i class="fa fa-undo"></i> Reset</button>
            </form>
        </div>
    </div>

    <!-- TABEL DATA -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-success"><i class="fa fa-table"></i> 100 Transaksi Terakhir</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="tabelKeuangan" width="100%">
                   <thead>
                        <tr>
                            <th width="5%">No</th>
                            <th width="10%">Tanggal</th>
                            <th width="10%">Tipe</th>
                            <th width="15%">Jenis</th>
                            <th width="15%">Pemasukan</th>
                            <th width="15%">Pengeluaran</th>
                            <th>Keterangan</th>
                            <th width="10%">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 class="text-right"><?= $row['tipe']=='Pemasukan'? 'Rp '.number_format($row['jumlah'],0,',','.') : '-'?></td>
                            <td class="text-right"><?= $row['tipe']=='Pengeluaran'? 'Rp '.number_format($row['jumlah'],0,',','.') : '-'?></td>
                            <td><?= $row['keterangan']?></td>
                            <td class="text-center">
                                <button class="btn btn-warning btn-sm" onclick="editData(<?= $row['id']?>)" title="Edit">
                                    <i class="fa fa-edit"></i>
                                </button>
                                <button class="btn btn-danger btn-sm" onclick="hapusData(<?= $row['id']?>)" title="Hapus">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endwhile;?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
const jenisPemasukan = ['Perpuluhan','Kolekte','Extra Kolekte','Diakonia','Persembahan','Pembangunan','Lainnya'];
const jenisPengeluaran = ['Pembangunan','Operasional','Listrik/Air','Konsumsi','Transport','ATK','Diakonia','Honor Pelayan','Lainnya','Iuran Pejabat','Perpuluhan Bulanan (Kolekte,Extra Kolekte, Diakonia, Perpuluan Jemaat, Kunjungan Keluarga, WBI, Pemuda, Sekolah Minggu','Setoran Extra Kolekte Bulanan'];

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);
}

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

function formatRupiah(angka){
    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 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 Transaksi');
}

function editData(id){
    $.ajax({
        url: 'keuangan_bendahara.php',
        type: 'POST',
        data: {aksi:'get',id:id},
        dataType: 'json',
        success: function(d){
            $('#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));
            $('#keterangan').val(d.keterangan);
            $('#btnSimpan').html('<i class="fa fa-save"></i> Update Transaksi');
            $('html, body').animate({scrollTop: 0}, 'slow');
        }
    });
}

function hapusData(id){
    Swal.fire({
        title: 'Hapus Data?',
        text: "Data yang dihapus tidak bisa dikembalikan!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Ya, Hapus!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('keuangan_bendahara.php', {aksi:'hapus',id:id}, function(res){
                if(res.status=='sukses'){
                    Swal.fire('Terhapus!','Data berhasil dihapus','success').then(() => location.reload());
                }
            }, 'json');
        }
    });
}

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

    $.ajax({
        url: 'keuangan_bendahara.php',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function(res){
            if(res.status == 'sukses'){
                Swal.fire('Berhasil!',res.message,'success').then(() => location.reload());
            } else {
                Swal.fire('Error',res.message,'error');
                $('#btnSimpan').prop('disabled', false).html('<i class="fa fa-save"></i> Simpan Transaksi');
            }
        },
        error: function(){
            Swal.fire('Error','Gagal konek ke server','error');
            $('#btnSimpan').prop('disabled', false).html('<i class="fa fa-save"></i> Simpan Transaksi');
        }
    });
});

$(document).ready(function() {
    $('#tabelKeuangan').DataTable({
        "order": [[1, "desc"]],
        "pageLength": 10,
        "language": {"url": "//cdn.datatables.net/plug-ins/1.13.6/i18n/id.json"}
    });
});
</script>
</body>
</html>