<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner_or_admin();
require_once __DIR__ . '/../includes/header_admin.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$errors = [];
$editMethod = null;

// Handle Edit Mode
if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];
    $stmt = $pdo->prepare('SELECT * FROM payment_methods WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editMethod = $stmt->fetch();
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Toggle Active Status
    if ($action === 'toggle') {
        $id = (int) ($_POST['id'] ?? 0);
        $stmt = $pdo->prepare('UPDATE payment_methods SET is_active = IF(is_active = 1, 0, 1) WHERE id = ?');
        $stmt->execute([$id]);
        flash_message('success', 'Status metode pembayaran diperbarui.');
        redirect(base_url('admin/payment_methods.php'));
    }

    // Delete Method
    if ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);
        // Check if used in orders
        $check = $pdo->prepare('SELECT COUNT(*) FROM orders WHERE payment_method_id = ?');
        $check->execute([$id]);
        if ($check->fetchColumn() > 0) {
            flash_message('error', 'Gagal hapus: Metode ini pernah digunakan dalam transaksi.');
        } else {
            $stmt = $pdo->prepare('DELETE FROM payment_methods WHERE id = ?');
            $stmt->execute([$id]);
            flash_message('success', 'Metode pembayaran berhasil dihapus.');
        }
        redirect(base_url('admin/payment_methods.php'));
    }

    // Create or Update
    if ($action === 'save') {
        $id = (int) ($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $account_name = trim($_POST['account_name'] ?? '');
        $account_number = trim($_POST['account_number'] ?? '');
        $instructions = trim($_POST['instructions'] ?? '');
        $is_active = isset($_POST['is_active']) ? 1 : 0;

        if ($name === '') $errors['name'] = 'Nama metode wajib diisi.';
        if ($account_name === '') $errors['account_name'] = 'Nama pemilik rekening wajib diisi.';
        if ($account_number === '') $errors['account_number'] = 'Nomor rekening wajib diisi.';

        if (!$errors) {
            if ($id === 0) {
                // Insert
                $stmt = $pdo->prepare('INSERT INTO payment_methods (name, account_name, account_number, instructions, is_active) VALUES (?, ?, ?, ?, ?)');
                $stmt->execute([$name, $account_name, $account_number, $instructions, $is_active]);
                flash_message('success', 'Metode pembayaran baru berhasil ditambahkan.');
            } else {
                // Update
                $stmt = $pdo->prepare('UPDATE payment_methods SET name = ?, account_name = ?, account_number = ?, instructions = ?, is_active = ? WHERE id = ?');
                $stmt->execute([$name, $account_name, $account_number, $instructions, $is_active, $id]);
                flash_message('success', 'Metode pembayaran berhasil diperbarui.');
            }
            redirect(base_url('admin/payment_methods.php'));
        }
    }
}

$methods = $pdo->query('SELECT * FROM payment_methods ORDER BY is_active DESC, name ASC')->fetchAll();
?>

<h2 class="fw-bold mb-4">Metode Pembayaran</h2>

<div class="row">
    <!-- Form Column -->
    <div class="col-md-4 mb-4">
        <div class="card shadow-sm">
            <div class="card-body">
                <h5 class="fw-bold mb-3"><?= $editMethod ? 'Edit Metode' : 'Tambah Metode Baru'; ?></h5>
                <form method="post">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="id" value="<?= $editMethod ? (int)$editMethod['id'] : 0; ?>">
                    
                    <div class="mb-3">
                        <label class="form-label">Nama Bank / E-Wallet</label>
                        <input type="text" class="form-control" name="name" value="<?= $editMethod ? sanitize($editMethod['name']) : ''; ?>" placeholder="Contoh: Bank BCA / GoPay" required>
                        <?php if (isset($errors['name'])): ?><small class="text-danger"><?= $errors['name']; ?></small><?php endif; ?>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Nomor Rekening / HP</label>
                        <input type="text" class="form-control" name="account_number" value="<?= $editMethod ? sanitize($editMethod['account_number']) : ''; ?>" placeholder="Contoh: 1234567890" required>
                        <?php if (isset($errors['account_number'])): ?><small class="text-danger"><?= $errors['account_number']; ?></small><?php endif; ?>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Atas Nama</label>
                        <input type="text" class="form-control" name="account_name" value="<?= $editMethod ? sanitize($editMethod['account_name']) : ''; ?>" placeholder="Contoh: Al-Qanuni Store" required>
                        <?php if (isset($errors['account_name'])): ?><small class="text-danger"><?= $errors['account_name']; ?></small><?php endif; ?>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Instruksi Pembayaran</label>
                        <textarea class="form-control" name="instructions" rows="3" placeholder="Contoh: Transfer dan upload bukti transfer."><?= $editMethod ? sanitize($editMethod['instructions']) : ''; ?></textarea>
                    </div>

                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="is_active" id="activeCheck" <?= (!$editMethod || $editMethod['is_active']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="activeCheck">Aktifkan Metode Ini</label>
                    </div>

                    <button type="submit" class="btn btn-primary w-100"><?= $editMethod ? 'Simpan Perubahan' : 'Tambah Metode'; ?></button>
                    <?php if ($editMethod): ?>
                        <a href="<?= base_url('admin/payment_methods.php'); ?>" class="btn btn-outline-secondary w-100 mt-2">Batal Edit</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>

    <!-- Table Column -->
    <div class="col-md-8">
        <div class="card shadow-sm">
            <div class="card-body table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>Metode</th>
                            <th>No. Rekening</th>
                            <th>Atas Nama</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($methods)): ?>
                            <tr><td colspan="5" class="text-center py-4 text-muted">Belum ada metode pembayaran.</td></tr>
                        <?php else: ?>
                            <?php foreach ($methods as $method): ?>
                                <tr>
                                    <td>
                                        <strong><?= sanitize($method['name']); ?></strong>
                                    </td>
                                    <td class="font-monospace"><?= sanitize($method['account_number']); ?></td>
                                    <td><?= sanitize($method['account_name']); ?></td>
                                    <td>
                                        <form method="post" class="d-inline">
                                            <input type="hidden" name="action" value="toggle">
                                            <input type="hidden" name="id" value="<?= (int)$method['id']; ?>">
                                            <button class="btn btn-sm <?= $method['is_active'] ? 'btn-success' : 'btn-secondary'; ?>" style="font-size: 0.7em;">
                                                <?= $method['is_active'] ? 'Aktif' : 'Nonaktif'; ?>
                                            </button>
                                        </form>
                                    </td>
                                    <td>
                                        <a href="<?= base_url('admin/payment_methods.php?edit=' . (int)$method['id']); ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-pencil me-1"></i> Edit
                                        </a>
                                        <?php 
                                            // Check usage first to possibly disable delete button visually (optional, but handled in backend)
                                            // For now just show delete
                                        ?>
                                        <button class="btn btn-sm btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteMethod<?= (int)$method['id']; ?>">
                                            <i class="bi bi-trash me-1"></i> Hapus
                                        </button>
                                    </td>
                                </tr>

                                <!-- Delete Modal -->
                                <div class="modal fade" id="deleteMethod<?= (int)$method['id']; ?>" tabindex="-1" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title">Hapus Metode</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">
                                                <p>Yakin ingin menghapus <strong><?= sanitize($method['name']); ?></strong>?</p>
                                                <small class="text-danger">Metode yang sudah pernah dipakai transaksi tidak bisa dihapus (hanya bisa dinonaktifkan).</small>
                                            </div>
                                            <div class="modal-footer">
                                                <form method="post">
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="id" value="<?= (int)$method['id']; ?>">
                                                    <button type="submit" class="btn btn-danger">Hapus</button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_admin.php'; ?>
