<?php
require_once '../config.php';
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}
$id_admin = $_SESSION['id'];
$success = '';
$error = '';

// Handle Tambah Transaksi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['tambah_kas'])) {
    $tanggal = $_POST['tanggal'];
    $jenis = $_POST['jenis'];
    $kategori = trim($_POST['kategori']);
    $nominal = (float)str_replace(',', '.', $_POST['nominal']);
    $keterangan = trim($_POST['keterangan']);

    // Validasi kategori berdasarkan jenis
    $kategori_masuk_valid = ['Pasang Baru', 'Pendapatan Lain'];
    $kategori_keluar_valid = ['Operasional', 'Honor Penarik Iuran', 'Pembelian Barang', 'Pengeluaran Lain'];

    if ($jenis === 'masuk' && !in_array($kategori, $kategori_masuk_valid)) {
        $error = "Kategori pemasukan tidak valid!";
    } elseif ($jenis === 'keluar' && !in_array($kategori, $kategori_keluar_valid)) {
        $error = "Kategori pengeluaran tidak valid!";
    } elseif (empty($kategori) || $nominal <= 0) {
        $error = "Kategori dan Nominal harus diisi dengan benar!";
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO buku_kas (tanggal, jenis, kategori, nominal, keterangan, id_user) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$tanggal, $jenis, $kategori, $nominal, $keterangan, $id_admin]);
            $success = "Transaksi berhasil dicatat!";
        } catch (PDOException $e) {
            $error = "Gagal mencatat transaksi: " . $e->getMessage();
        }
    }
}

// Ambil Data Kas (50 Terakhir)
$kas_list = $pdo->query("SELECT * FROM buku_kas ORDER BY tanggal DESC, id DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC);

// Hitung Saldo
$total_masuk = (float)$pdo->query("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='masuk'")->fetchColumn();
$total_keluar = (float)$pdo->query("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='keluar'")->fetchColumn();
$saldo_akhir = $total_masuk - $total_keluar;
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Buku Kas - SPAM</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:#f4f7fe; font-family:'Segoe UI'; }
.bg-header{
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color:white;
    padding:18px;
    border-bottom-left-radius:20px;
    border-bottom-right-radius:20px;
}
.card-soft {
    background: white; border: none; border-radius: 20px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.05); padding: 20px; margin-bottom: 15px;
}
.saldo-box {
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color: white; border-radius: 16px; padding: 20px; text-align: center; margin-bottom: 15px;
}
.saldo-label { font-size: 0.9rem; opacity: 0.9; }
.saldo-value { font-size: 2rem; font-weight: 800; }
.saldo-detail { display: flex; justify-content: space-between; margin-top: 15px; padding-top: 15px; border-top: 1px solid rgba(255,255,255,0.2); }
.saldo-detail div { text-align: center; }
.saldo-detail .val { font-weight: 700; font-size: 1.1rem; }
.form-control, .form-select {
    border-radius: 12px; padding: 12px 15px; border: 1px solid #e0e0e0; background: #f8f9fa;
}
.form-control:focus, .form-select:focus {
    border-color: #3A7CA5; box-shadow: 0 0 0 0.25rem rgba(58, 124, 165, 0.25); background: white;
}
.form-label { font-weight: 700; font-size: 0.85rem; color: #4a5568; }
.btn-sage {
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color: white; border: none; border-radius: 12px; padding: 12px; font-weight: 700; width: 100%;
}
.kas-item {
    display: flex; justify-content: space-between; align-items: center;
    padding: 12px 0; border-bottom: 1px solid #f0f0f0;
}
.kas-item:last-child { border-bottom: none; }
.kas-icon {
    width: 40px; height: 40px; border-radius: 12px;
    display: flex; align-items: center; justify-content: center; font-size: 1.1rem; margin-right: 12px;
}
.icon-masuk { background: #eaf8ef; color: #198754; }
.icon-keluar { background: #fdecec; color: #dc3545; }
.kas-info { flex: 1; }
.kas-ket { font-weight: 700; font-size: 0.9rem; color: #2f3440; }
.kas-meta { font-size: 0.75rem; color: #7a8190; }
.kas-nominal { font-weight: 800; font-size: 0.95rem; }
.text-masuk { color: #198754; }
.text-keluar { color: #dc3545; }
.kategori-info {
    background: #fff8e1;
    border-left: 4px solid #f1c40f;
    padding: 10px 14px;
    border-radius: 8px;
    font-size: 0.82rem;
    color: #7d6608;
    margin-bottom: 15px;
}
.badge-kat {
    font-size: 0.72rem;
    padding: 4px 10px;
    border-radius: 10px;
    font-weight: 600;
}
.badge-pendapatan-air { background: #e9f2ff; color: #0d6efd; }
.badge-pasang-baru { background: #fff3cd; color: #856404; }
.badge-pendapatan-lain { background: #e6f5f5; color: #0d9488; }
.badge-operasional { background: #fdecec; color: #dc3545; }
.badge-honor { background: #f3e8ff; color: #7c3aed; }
.badge-pembelian { background: #ffedd5; color: #ea580c; }
.badge-pengeluaran-lain { background: #e2e3e5; color: #495057; }
</style>
</head>
<body>

<div class="bg-header shadow-sm">
    <div class="container d-flex justify-content-between align-items-center">
        <a href="dashboard.php" class="text-white"><i class="fa fa-arrow-left"></i></a>
        <h5 class="mb-0 fw-bold">Buku Kas</h5>
        <div style="width: 20px;"></div>
    </div>
</div>

<div class="container pb-5 mt-3">
    <?php if ($success): ?>
        <div class="alert alert-success" style="font-size:0.85rem; border-radius:10px;"><?= $success ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-danger" style="font-size:0.85rem; border-radius:10px;"><?= $error ?></div>
    <?php endif; ?>

    <!-- Saldo Kas -->
    <div class="saldo-box shadow-sm">
        <div class="saldo-label">Saldo Kas Realtime</div>
        <div class="saldo-value"><?= format_rupiah($saldo_akhir) ?></div>
        <div class="saldo-detail">
            <div>
                <div class="small opacity-75">Pemasukan</div>
                <div class="val"><?= format_rupiah($total_masuk) ?></div>
            </div>
            <div>
                <div class="small opacity-75">Pengeluaran</div>
                <div class="val"><?= format_rupiah($total_keluar) ?></div>
            </div>
        </div>
    </div>

    <!-- Form Tambah Transaksi -->
    <div class="card-soft">
        <h6 class="fw-bold mb-3"><i class="fa fa-plus-circle me-2 text-primary"></i>Catat Transaksi Manual</h6>
        
        <div class="kategori-info">
            <i class="fa fa-info-circle me-1"></i> 
            <b>Catatan:</b> Kategori <b>"Pendapatan Air"</b> otomatis tercatat saat pelanggan membayar tagihan. Gunakan form ini untuk transaksi manual lainnya.
        </div>

        <form method="POST" id="formKas">
            <input type="hidden" name="tambah_kas" value="1">
            <div class="row g-2">
                <div class="col-6">
                    <label class="form-label">Tanggal</label>
                    <input type="date" name="tanggal" class="form-control" required value="<?= date('Y-m-d') ?>">
                </div>
                <div class="col-6">
                    <label class="form-label">Jenis Transaksi</label>
                    <select name="jenis" id="jenisTransaksi" class="form-select" required>
                        <option value="masuk">Pemasukan</option>
                        <option value="keluar">Pengeluaran</option>
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Kategori</label>
                    <select name="kategori" id="kategoriSelect" class="form-select" required>
                        <!-- Opsi akan diisi oleh JavaScript -->
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Nominal (Rp)</label>
                    <input type="number" name="nominal" class="form-control" required placeholder="0" min="1">
                </div>
                <div class="col-12">
                    <label class="form-label">Keterangan</label>
                    <textarea name="keterangan" class="form-control" rows="2" placeholder="Detail transaksi..."></textarea>
                </div>
            </div>
            <button type="submit" class="btn btn-sage mt-3">
                <i class="fa fa-save me-2"></i> Simpan Transaksi
            </button>
        </form>
    </div>

    <!-- Riwayat Transaksi -->
    <div class="card-soft">
        <h6 class="fw-bold mb-3"><i class="fa fa-history me-2 text-primary"></i>Riwayat Transaksi</h6>
        <?php if (empty($kas_list)): ?>
            <div class="text-center text-muted py-3 small">Belum ada transaksi.</div>
        <?php else: ?>
            <?php foreach ($kas_list as $k): ?>
            <div class="kas-item">
                <div class="kas-icon <?= $k['jenis'] === 'masuk' ? 'icon-masuk' : 'icon-keluar' ?>">
                    <i class="fa-solid <?= $k['jenis'] === 'masuk' ? 'fa-arrow-down' : 'fa-arrow-up' ?>"></i>
                </div>
                <div class="kas-info">
                    <div class="kas-ket">
                        <?= htmlspecialchars($k['kategori']) ?>
                        <?php
                        $badge_class = '';
                        switch ($k['kategori']) {
                            case 'Pendapatan Air': $badge_class = 'badge-pendapatan-air'; break;
                            case 'Pasang Baru': $badge_class = 'badge-pasang-baru'; break;
                            case 'Pendapatan Lain': $badge_class = 'badge-pendapatan-lain'; break;
                            case 'Operasional': $badge_class = 'badge-operasional'; break;
                            case 'Honor Penarik Iuran': $badge_class = 'badge-honor'; break;
                            case 'Pembelian Barang': $badge_class = 'badge-pembelian'; break;
                            case 'Pengeluaran Lain': $badge_class = 'badge-pengeluaran-lain'; break;
                        }
                        ?>
                    </div>
                    <div class="kas-meta"><?= date('d/m/Y', strtotime($k['tanggal'])) ?> • <?= htmlspecialchars($k['keterangan']) ?></div>
                </div>
                <div class="kas-nominal <?= $k['jenis'] === 'masuk' ? 'text-masuk' : 'text-keluar' ?>">
                    <?= $k['jenis'] === 'masuk' ? '+' : '-' ?> <?= format_rupiah($k['nominal']) ?>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Data kategori
const kategoriData = {
    masuk: [
        { value: 'Pasang Baru', label: 'Pasang Baru', disabled: false },
        { value: 'Pendapatan Lain', label: 'Pendapatan Lain', disabled: false },
        { value: 'Pendapatan Air', label: 'Pendapatan Air (Otomatis)', disabled: true }
    ],
    keluar: [
        { value: 'Operasional', label: 'Operasional', disabled: false },
        { value: 'Honor Penarik Iuran', label: 'Honor Penarik Iuran', disabled: false },
        { value: 'Pembelian Barang', label: 'Pembelian Barang', disabled: false },
        { value: 'Pengeluaran Lain', label: 'Pengeluaran Lain', disabled: false }
    ]
};

const jenisSelect = document.getElementById('jenisTransaksi');
const kategoriSelect = document.getElementById('kategoriSelect');

// Fungsi untuk mengisi dropdown kategori
function updateKategori() {
    const jenis = jenisSelect.value;
    const data = kategoriData[jenis] || [];
    
    // Kosongkan dropdown
    kategoriSelect.innerHTML = '<option value="">-- Pilih Kategori --</option>';
    
    // Isi dengan data baru
    data.forEach(item => {
        const option = document.createElement('option');
        option.value = item.value;
        option.textContent = item.label;
        if (item.disabled) {
            option.disabled = true;
        }
        kategoriSelect.appendChild(option);
    });
}

// Event listener saat jenis berubah
jenisSelect.addEventListener('change', updateKategori);

// Inisialisasi saat halaman dimuat
updateKategori();
</script>
</body>
</html>