<?php
require_once __DIR__ . '/includes/functions.php';
requireLogin();
$pageTitle = 'Akun Kas / Bank';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'save') {
        $id = $_POST['id'] ?? '';
        $params = [
            'nama_akun'   => trim($_POST['nama_akun']),
            'jenis'       => $_POST['jenis'],
            'no_rekening' => trim($_POST['no_rekening']),
            'saldo_awal'  => (float)str_replace('.', '', $_POST['saldo_awal']),
            'keterangan'  => trim($_POST['keterangan']),
            'status'      => $_POST['status'],
        ];
        if ($id) {
            $params['id'] = $id;
            $pdo->prepare("UPDATE akun_kas SET nama_akun=:nama_akun, jenis=:jenis, no_rekening=:no_rekening, saldo_awal=:saldo_awal, keterangan=:keterangan, status=:status WHERE id=:id")->execute($params);
            flash('success', 'Akun berhasil diperbarui.');
        } else {
            $pdo->prepare("INSERT INTO akun_kas (nama_akun,jenis,no_rekening,saldo_awal,keterangan,status) VALUES (:nama_akun,:jenis,:no_rekening,:saldo_awal,:keterangan,:status)")->execute($params);
            flash('success', 'Akun berhasil ditambahkan.');
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'];
        $cek = $pdo->prepare("SELECT COUNT(*) FROM transaksi WHERE akun_id=:id");
        $cek->execute(['id'=>$id]);
        if ($cek->fetchColumn() > 0) {
            flash('error', 'Akun tidak dapat dihapus karena sudah memiliki transaksi.');
        } else {
            $pdo->prepare("DELETE FROM akun_kas WHERE id=:id")->execute(['id'=>$id]);
            flash('success', 'Akun berhasil dihapus.');
        }
    }
    header('Location: akun_kas.php');
    exit;
}

$data = $pdo->query("
    SELECT a.*,
        (a.saldo_awal
         + COALESCE((SELECT SUM(jumlah) FROM transaksi WHERE akun_id=a.id AND tipe='pemasukan'),0)
         - COALESCE((SELECT SUM(jumlah) FROM transaksi WHERE akun_id=a.id AND tipe='pengeluaran'),0)
        ) as saldo_sekarang
    FROM akun_kas a ORDER BY a.nama_akun
")->fetchAll();

include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">Master Akun Kas &amp; Bank</h5>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalAkun" onclick="resetForm()">
        <i class="bi bi-plus-lg"></i> Tambah Akun
    </button>
</div>

<div class="row g-3">
<?php foreach ($data as $row): ?>
    <div class="col-md-4">
        <div class="card stat-card p-3 h-100">
            <div class="d-flex justify-content-between">
                <div class="icon-box bg-primary-subtle text-primary"><i class="bi bi-<?= $row['jenis']==='bank' ? 'bank' : 'cash-coin' ?>"></i></div>
                <div>
                    <button class="btn btn-sm btn-outline-primary" onclick='editRow(<?= htmlspecialchars(json_encode($row), ENT_QUOTES) ?>)'><i class="bi bi-pencil"></i></button>
                    <form method="POST" class="d-inline" onsubmit="return confirmDelete()">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?= $row['id'] ?>">
                        <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                    </form>
                </div>
            </div>
            <div class="mt-2">
                <div class="fw-bold"><?= htmlspecialchars($row['nama_akun']) ?></div>
                <div class="text-muted small"><?= htmlspecialchars($row['no_rekening'] ?: '-') ?></div>
                <div class="mt-2 h5 mb-0"><?= rupiah($row['saldo_sekarang']) ?></div>
                <span class="badge <?= $row['status']==='aktif' ? 'text-bg-success' : 'text-bg-secondary' ?> mt-1"><?= ucfirst($row['status']) ?></span>
            </div>
        </div>
    </div>
<?php endforeach; ?>
</div>

<div class="modal fade" id="modalAkun" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Tambah Akun</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" id="f_id">
                <div class="mb-3">
                    <label class="form-label">Nama Akun</label>
                    <input type="text" name="nama_akun" id="f_nama_akun" class="form-control" required placeholder="contoh: Kas Tunai, Bank BRI">
                </div>
                <div class="row">
                    <div class="col-6 mb-3">
                        <label class="form-label">Jenis</label>
                        <select name="jenis" id="f_jenis" class="form-select">
                            <option value="kas">Kas Tunai</option>
                            <option value="bank">Bank</option>
                        </select>
                    </div>
                    <div class="col-6 mb-3">
                        <label class="form-label">No. Rekening</label>
                        <input type="text" name="no_rekening" id="f_no_rekening" class="form-control">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Saldo Awal</label>
                    <input type="text" name="saldo_awal" id="f_saldo_awal" class="form-control" oninput="formatRupiahInput(this)" placeholder="0">
                </div>
                <div class="mb-3">
                    <label class="form-label">Keterangan</label>
                    <input type="text" name="keterangan" id="f_keterangan" class="form-control">
                </div>
                <div class="mb-3">
                    <label class="form-label">Status</label>
                    <select name="status" id="f_status" class="form-select">
                        <option value="aktif">Aktif</option>
                        <option value="nonaktif">Nonaktif</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button>
                <button type="submit" class="btn btn-primary">Simpan</button>
            </div>
        </form>
    </div>
</div>

<script>
function resetForm() {
    document.getElementById('modalTitle').innerText = 'Tambah Akun';
    document.getElementById('f_id').value = '';
    document.getElementById('f_nama_akun').value = '';
    document.getElementById('f_jenis').value = 'kas';
    document.getElementById('f_no_rekening').value = '';
    document.getElementById('f_saldo_awal').value = '';
    document.getElementById('f_keterangan').value = '';
    document.getElementById('f_status').value = 'aktif';
}
function editRow(row) {
    document.getElementById('modalTitle').innerText = 'Edit Akun';
    document.getElementById('f_id').value = row.id;
    document.getElementById('f_nama_akun').value = row.nama_akun;
    document.getElementById('f_jenis').value = row.jenis;
    document.getElementById('f_no_rekening').value = row.no_rekening;
    document.getElementById('f_saldo_awal').value = new Intl.NumberFormat('id-ID').format(row.saldo_awal);
    document.getElementById('f_keterangan').value = row.keterangan;
    document.getElementById('f_status').value = row.status;
    new bootstrap.Modal(document.getElementById('modalAkun')).show();
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>