<?php
// ============================================================
// FILE: admin/rekening.php — CRUD Rekening Bank
// ============================================================
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
requireAdmin();

$pdo = db(); $errors = []; $mode = 'list'; $editData = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $aksi = $_POST['aksi'] ?? '';

    if ($aksi === 'tambah' || $aksi === 'edit') {
        $namaBank  = trim($_POST['nama_bank']   ?? '');
        $noRek     = trim($_POST['no_rekening'] ?? '');
        $atasNama  = trim($_POST['atas_nama']   ?? '');
        $isAktif   = isset($_POST['is_aktif']) ? 1 : 0;
        if (!$namaBank) $errors[] = 'Nama bank wajib diisi.';
        if (!$noRek)    $errors[] = 'Nomor rekening wajib diisi.';
        if (!$atasNama) $errors[] = 'Nama pemilik rekening wajib diisi.';

        if (empty($errors)) {
            if ($aksi === 'tambah') {
                $pdo->prepare("INSERT INTO rekening_bank (nama_bank,no_rekening,atas_nama,is_aktif) VALUES (?,?,?,?)")
                    ->execute([$namaBank,$noRek,$atasNama,$isAktif]);
                setFlash('success', 'Rekening berhasil ditambahkan.');
            } else {
                $kid = (int)($_POST['kid'] ?? 0);
                $pdo->prepare("UPDATE rekening_bank SET nama_bank=?,no_rekening=?,atas_nama=?,is_aktif=? WHERE id=?")
                    ->execute([$namaBank,$noRek,$atasNama,$isAktif,$kid]);
                setFlash('success', 'Rekening berhasil diperbarui.');
            }
            redirect(BASE_URL . '/admin/rekening.php');
        }
        $mode = $aksi;
        $editData = ['nama_bank'=>$namaBank,'no_rekening'=>$noRek,'atas_nama'=>$atasNama,'is_aktif'=>$isAktif];
    }

    if ($aksi === 'hapus') {
        $pdo->prepare("DELETE FROM rekening_bank WHERE id=?")->execute([(int)$_POST['kid']]);
        setFlash('success', 'Rekening berhasil dihapus.');
        redirect(BASE_URL . '/admin/rekening.php');
    }

    if ($aksi === 'toggle') {
        $kid = (int)($_POST['kid'] ?? 0);
        $r = $pdo->prepare("SELECT is_aktif FROM rekening_bank WHERE id=?"); $r->execute([$kid]);
        $cur = (int)$r->fetchColumn();
        $pdo->prepare("UPDATE rekening_bank SET is_aktif=? WHERE id=?")->execute([!$cur,$kid]);
        redirect(BASE_URL . '/admin/rekening.php');
    }
}

if (isset($_GET['edit'])) {
    $kid = (int)$_GET['edit'];
    $s   = $pdo->prepare("SELECT * FROM rekening_bank WHERE id=? LIMIT 1");
    $s->execute([$kid]); $editData = $s->fetch();
    if ($editData) $mode = 'edit';
}
if (isset($_GET['tambah'])) $mode = 'tambah';

$rekList = $pdo->query("SELECT * FROM rekening_bank ORDER BY is_aktif DESC, id ASC")->fetchAll();
$pageTitle = 'Rekening Bank';
include __DIR__ . '/admin_layout.php';
?>

<div class="adm-page-header mb-4">
  <div>
    <h4 class="adm-page-title"><i class="bi bi-bank2 me-2"></i>Rekening Bank</h4>
    <p class="adm-page-sub mb-0">Rekening tujuan transfer pelanggan</p>
  </div>
  <?php if ($mode === 'list'): ?>
    <a href="?tambah=1" class="btn btn-primary-brand btn-sm">
      <i class="bi bi-plus-lg me-1"></i>Tambah Rekening
    </a>
  <?php endif; ?>
</div>

<div class="row g-4">
  <div class="col-lg-<?= ($mode!=='list')?'7':'12' ?>">
    <div class="admin-card">
      <div class="admin-card-header"><h6 class="mb-0">Daftar Rekening</h6></div>
      <div class="table-responsive">
        <table class="table table-hover admin-table mb-0">
          <thead>
            <tr><th>Bank</th><th>No. Rekening</th><th>Atas Nama</th><th class="text-center">Status</th><th class="text-center">Aksi</th></tr>
          </thead>
          <tbody>
            <?php if (empty($rekList)): ?>
              <tr><td colspan="5" class="text-center py-4 text-muted">Belum ada rekening.</td></tr>
            <?php endif; ?>
            <?php foreach ($rekList as $r): ?>
              <tr class="<?= !$r['is_aktif']?'adm-row--inactive':'' ?>">
                <td>
                  <div class="fw-bold text-primary"><?= e($r['nama_bank']) ?></div>
                </td>
                <td>
                  <code class="fs-6 fw-bold"><?= e($r['no_rekening']) ?></code>
                </td>
                <td><?= e($r['atas_nama']) ?></td>
                <td class="text-center">
                  <form method="POST" class="d-inline">
                    <input type="hidden" name="aksi" value="toggle">
                    <input type="hidden" name="kid" value="<?= $r['id'] ?>">
                    <button class="btn btn-xs <?= $r['is_aktif']?'btn-success':'btn-secondary' ?>"
                            title="<?= $r['is_aktif']?'Aktif — klik nonaktifkan':'Nonaktif — klik aktifkan' ?>">
                      <i class="bi bi-<?= $r['is_aktif']?'toggle-on':'toggle-off' ?>"></i>
                      <?= $r['is_aktif']?'Aktif':'Nonaktif' ?>
                    </button>
                  </form>
                </td>
                <td class="text-center">
                  <div class="d-flex gap-1 justify-content-center">
                    <a href="?edit=<?= $r['id'] ?>" class="btn btn-xs btn-outline-warning"><i class="bi bi-pencil"></i></a>
                    <form method="POST" onsubmit="return confirm('Hapus rekening ini?')">
                      <input type="hidden" name="aksi" value="hapus">
                      <input type="hidden" name="kid" value="<?= $r['id'] ?>">
                      <button class="btn btn-xs btn-outline-danger"><i class="bi bi-trash3"></i></button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <?php if ($mode !== 'list'): ?>
    <div class="col-lg-5">
      <div class="admin-card">
        <div class="admin-card-header">
          <h6 class="mb-0">
            <i class="bi bi-<?= $mode==='edit'?'pencil':'plus-circle' ?> me-2"></i>
            <?= $mode==='edit' ? 'Edit Rekening' : 'Tambah Rekening' ?>
          </h6>
        </div>
        <div class="p-4">
          <?php if (!empty($errors)): ?>
            <div class="alert alert-danger small mb-3">
              <?php foreach($errors as $e): ?><div><i class="bi bi-exclamation-circle me-1"></i><?= $e ?></div><?php endforeach; ?>
            </div>
          <?php endif; ?>
          <form method="POST">
            <input type="hidden" name="aksi" value="<?= $mode ?>">
            <?php if ($mode==='edit'): ?>
              <input type="hidden" name="kid" value="<?= $editData['id'] ?>">
            <?php endif; ?>
            <div class="mb-3">
              <label class="ck-label">Nama Bank <span class="text-danger">*</span></label>
              <input type="text" name="nama_bank" class="form-control ck-input"
                     value="<?= e($editData['nama_bank'] ?? '') ?>"
                     placeholder="BCA, BRI, Mandiri, BNI, dll." required>
            </div>
            <div class="mb-3">
              <label class="ck-label">Nomor Rekening <span class="text-danger">*</span></label>
              <input type="text" name="no_rekening" class="form-control ck-input"
                     value="<?= e($editData['no_rekening'] ?? '') ?>"
                     placeholder="1234567890" required>
            </div>
            <div class="mb-3">
              <label class="ck-label">Atas Nama <span class="text-danger">*</span></label>
              <input type="text" name="atas_nama" class="form-control ck-input"
                     value="<?= e($editData['atas_nama'] ?? '') ?>"
                     placeholder="Sesuai nama di buku tabungan" required>
            </div>
            <div class="mb-4">
              <div class="form-check form-switch">
                <input type="checkbox" class="form-check-input" role="switch"
                       id="swAktifRek" name="is_aktif" value="1"
                       <?= ($editData['is_aktif'] ?? 1) ? 'checked' : '' ?>>
                <label class="form-check-label fw-semibold" for="swAktifRek">
                  Tampilkan ke Pelanggan
                </label>
              </div>
            </div>
            <div class="d-flex gap-2">
              <button type="submit" class="btn btn-primary-brand flex-grow-1">
                <i class="bi bi-check-lg me-1"></i>
                <?= $mode==='edit'?'Simpan':'Tambah Rekening' ?>
              </button>
              <a href="<?= BASE_URL ?>/admin/rekening.php" class="btn btn-outline-secondary">Batal</a>
            </div>
          </form>
        </div>
      </div>
    </div>
  <?php endif; ?>
</div>

<?php include __DIR__ . '/admin_footer.php'; ?>