<?php
session_start();
// Fix: Naik 1 folder karena file ini di /pages/
include '../config/database.php';

// Cek login + role bendahara
if(!isset($_SESSION['user_id']) || $_SESSION['role']!= 'bendahara'){
    header("Location:../login.php");
    exit;
}

$db = new Database();
$conn = $db->getConnection();

$gereja_id = $_SESSION['gereja_id'];
$nama_user = $_SESSION['nama'];
$nama_gereja = $_SESSION['nama_gereja'];
$foto_user = $_SESSION['foto']?: 'default.png';

// Proses Simpan Data - Sesuaikan dengan struktur tabel kamu
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $tanggal = $_POST['tanggal'];
    $tipe = $_POST['tipe']; // Pemasukan / Pengeluaran - huruf besar sesuai enum
    $jenis = $_POST['jenis']; // Perpuluhan, Extra Kolekte, dll
    $jumlah = str_replace(['.', ' '], '', $_POST['jumlah']); // hapus titik
    $keterangan = $_POST['keterangan'];

    // Validasi
    if(empty($tanggal) || empty($tipe) || empty($jenis) || empty($jumlah)){
        $error = "Semua field wajib diisi!";
    } else {
        // Sesuaikan dengan kolom tabel: tipe, jenis
        $stmt = $conn->prepare("INSERT INTO keuangan (gereja_id, created_by, tanggal, tipe, jenis, jumlah, keterangan)
                                VALUES (?,?,?,?,?,?,?)");
        $result = $stmt->execute([$gereja_id, $_SESSION['user_id'], $tanggal, $tipe, $jenis, $jumlah, $keterangan]);

        if($result){
            $success = "Data keuangan berhasil disimpan!";
        } else {
            $error = "Gagal menyimpan data!";
        }
    }
}

// Hapus data
if(isset($_GET['hapus'])){
    $id_hapus = $_GET['hapus'];
    // Wajib filter gereja_id biar gak bisa hapus data gereja lain
    $del = $conn->prepare("DELETE FROM keuangan WHERE id =? AND gereja_id =?");
    $del->execute([$id_hapus, $gereja_id]);
    header("Location: input_keuangan_bendahara.php?msg=deleted");
    exit;
}

// Ambil data keuangan gereja ini aja
$q_data = $conn->prepare("SELECT * FROM keuangan WHERE gereja_id =? ORDER BY tanggal DESC, id DESC LIMIT 50");
$q_data->execute([$gereja_id]);
$data_keuangan = $q_data->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input Keuangan - Bendahara</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #f8fafc; }
      .sidebar {
            background: linear-gradient(180deg, #1e3a8a 0%, #1e40af 100%);
            min-height: 100vh;
            color: white;
        }
      .sidebar a {
            color: #cbd5e1;
            text-decoration: none;
            display: block;
            padding: 12px 20px;
            transition: all 0.3s;
        }
      .sidebar a:hover,.sidebar a.active {
            background: rgba(255,255,255,0.1);
            color: white;
            border-left: 3px solid #fff;
        }
      .card-form {
            border: none;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
      .form-control:focus,.form-select:focus {
            border-color: #8b5cf6;
            box-shadow: 0 0 0 0.2rem rgba(139, 92, 246, 0.15);
        }
      .btn-simpan {
            background: #10b981;
            border: none;
        }
      .btn-simpan:hover {
            background: #059669;
        }
      .img-profile { width: 36px; height: 36px; object-fit: cover; }
      .bg-hijau-muda { background-color: #d1fae5; }
      .bg-ungu-muda { background-color: #ede9fe; }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <!-- Sidebar - Fix path pakai../ -->
        <div class="col-md-2 sidebar p-0">
            <div class="p-3 text-center border-bottom border-light border-opacity-25">
                <i class="fas fa-church fa-2x mb-2"></i>
                <h5 class="mb-0">SIMJEBPW</h5>
                <small class="text-light text-opacity-75">BENDAHARA</small>
            </div>
            <a href="../dashboard_bendahara.php"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a>
            <div class="px-3 mt-3 mb-2 text-light text-opacity-50"><small>KEUANGAN GEREJA</small></div>
            <a href="input_keuangan_bendahara.php" class="active"><i class="fas fa-wallet me-2"></i> Input Keuangan</a>
            <a href="laporan_keuangan_bendahara.php"><i class="fas fa-file-invoice-dollar me-2"></i> Laporan Keuangan</a>
            <div class="px-3 mt-4">
                <a href="../logout.php" class="btn btn-danger btn-sm w-100"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
            </div>
        </div>

        <!-- Konten -->
        <div class="col-md-10 p-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h3 class="fw-light">Input Keuangan - <?= htmlspecialchars($nama_gereja)?></h3>
                <div class="d-flex align-items-center">
                    <img src="../assets/img/jemaat/<?= $foto_user?>"
                         onerror="this.src='../assets/img/jemaat/default.png'"
                         class="img-profile rounded-circle me-2"
                         alt="Foto">
                    <div>
                        <span class="me-2 text-dark"><?= htmlspecialchars($nama_user)?></span>
                        <span class="badge bg-primary">Bendahara</span>
                    </div>
                </div>
            </div>

            <?php if(isset($success)):?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i><?= $success?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif;?>

            <?php if(isset($error)):?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i><?= $error?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif;?>

            <div class="row">
                <div class="col-lg-7">
                    <div class="card card-form">
                        <div class="card-header bg-white py-3">
                            <h5 class="mb-0"><i class="fas fa-plus-circle me-2 text-primary"></i>Form Transaksi Keuangan</h5>
                        </div>
                        <div class="card-body">
                            <form method="POST" id="formKeuangan">
                                <div class="mb-3">
                                    <label class="form-label">Tanggal Transaksi</label>
                                    <input type="date" name="tanggal" class="form-control" value="<?= date('Y-m-d')?>" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Tipe Transaksi</label>
                                    <select name="tipe" id="tipe" class="form-select" required onchange="gantiJenis()">
                                        <option value="">-- Pilih Tipe --</option>
                                        <option value="Pemasukan">Pemasukan</option>
                                        <option value="Pengeluaran">Pengeluaran</option>
                                    </select>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Jenis</label>
                                    <select name="jenis" id="jenis" class="form-select" required>
                                        <option value="">-- Pilih Tipe Dulu --</option>
                                    </select>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Jumlah (Rp)</label>
                                    <input type="text" name="jumlah" id="jumlah" class="form-control" placeholder="0" required>
                                    <small class="text-muted">Contoh: 1.500.000</small>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Keterangan</label>
                                    <textarea name="keterangan" class="form-control" rows="3" placeholder="Tulis keterangan lengkap..."></textarea>
                                </div>

                                <div class="d-grid">
                                    <button type="submit" class="btn btn-simpan btn-lg text-white">
                                        <i class="fas fa-save me-2"></i>Simpan Transaksi
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-lg-5">
                    <div class="card card-form bg-hijau-muda mb-3">
                        <div class="card-body">
                            <h6 class="text-success"><i class="fas fa-info-circle me-2"></i>Jenis Pemasukan</h6>
                            <ul class="mb-0 small">
                                <li>Perpuluhan</li>
                                <li>Extra Kolekte</li>
                                <li>Diakonia</li>
                                <li>Kolekte</li>
                                <li>Pembangunan</li>
                            </ul>
                        </div>
                    </div>

                    <div class="card card-form bg-ungu-muda">
                        <div class="card-body">
                            <h6 style="color: #8b5cf6"><i class="fas fa-info-circle me-2"></i>Jenis Pengeluaran</h6>
                            <ul class="mb-0 small">
                                <li>Operasional Gereja</li>
                                <li>Gaji/Honor Pelayan</li>
                                <li>Bantuan Sosial</li>
                                <li>Pemeliharaan Gedung</li>
                                <li>ATK & Perlengkapan</li>
                                <li>Lain-lain</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tabel Data -->
            <div class="card card-form mt-4">
                <div class="card-header bg-white py-3">
                    <h5 class="mb-0"><i class="fas fa-list me-2 text-primary"></i>50 Transaksi Terakhir</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th width="5%">No</th>
                                    <th>Tanggal</th>
                                    <th>Tipe</th>
                                    <th>Jenis</th>
                                    <th>Keterangan</th>
                                    <th class="text-end">Jumlah</th>
                                    <th width="10%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($data_keuangan)):?>
                                    <tr><td colspan="7" class="text-center text-muted py-4">Belum ada data keuangan</td></tr>
                                <?php else:?>
                                    <?php $no=1; foreach($data_keuangan as $dk):?>
                                    <tr>
                                        <td><?= $no++?></td>
                                        <td><?= date('d/m/Y', strtotime($dk['tanggal']))?></td>
                                        <td>
                                            <?php if($dk['tipe'] == 'Pemasukan'):?>
                                                <span class="badge bg-success">Pemasukan</span>
                                            <?php else:?>
                                                <span class="badge" style="background:#8b5cf6">Pengeluaran</span>
                                            <?php endif;?>
                                        </td>
                                        <td><?= htmlspecialchars($dk['jenis'])?></td>
                                        <td><?= htmlspecialchars($dk['keterangan'])?></td>
                                        <td class="text-end fw-bold <?= $dk['tipe'] == 'Pemasukan'? 'text-success' : 'text-danger'?>">
                                            Rp <?= number_format($dk['jumlah'],0,',','.')?>
                                        </td>
                                        <td>
                                            <a href="?hapus=<?= $dk['id']?>" class="btn btn-sm btn-outline-danger"
                                               onclick="return confirm('Yakin hapus data ini?')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach;?>
                                <?php endif;?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Data jenis sesuai enum tabel kamu
    const jenisPemasukan = ['Perpuluhan','Extra Kolekte','Diakonia','Kolektek','Persembahan Syukur','Pembangunan'];
    const jenisPengeluaran = ['Operasional Gereja','Gaji/Honor Pelayan','Bantuan Sosial','Pemeliharaan Gedung','ATK & Perlengkapan','Pdt Tamu','Pengijil Tamu','Lain-lain'];

    function gantiJenis() {
        const tipe = document.getElementById('tipe').value;
        const selectJenis = document.getElementById('jenis');
        selectJenis.innerHTML = '<option value="">-- Pilih Jenis --</option>';

        let listJenis = [];
        if(tipe === 'Pemasukan') listJenis = jenisPemasukan;
        if(tipe === 'Pengeluaran') listJenis = jenisPengeluaran;

        listJenis.forEach(j => {
            selectJenis.innerHTML += `<option value="${j}">${j}</option>`;
        });
    }

    // Format input jumlah pakai titik
    document.getElementById('jumlah').addEventListener('keyup', function(e) {
        let value = this.value.replace(/[^,\d]/g, '').toString();
        let split = value.split(',');
        let sisa = split[0].length % 3;
        let rupiah = split[0].substr(0, sisa);
        let ribuan = split[0].substr(sisa).match(/\d{3}/gi);

        if(ribuan){
            let separator = sisa? '.' : '';
            rupiah += separator + ribuan.join('.');
        }

        rupiah = split[1]!= undefined? rupiah + ',' + split[1] : rupiah;
        this.value = rupiah;
    });
</script>
</body>
</html>