<?php
// --- LOGIC BLOCK ---
require_once '../includes/db.php';
if (!isset($_SESSION['admin_logged_in'])) { header("Location: ../login.php"); exit(); }

$message = '';
// ACTION HANDLING for Manual Methods (ADD/EDIT/DELETE)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // --- DELETE ---
    if (isset($_POST['delete_method'])) {
        $id = intval($_POST['id']);
        // Delete old QR code if it exists
        $stmt_img = $conn->prepare("SELECT qr_code_url FROM payment_methods WHERE id = ?");
        $stmt_img->bind_param("i", $id);
        $stmt_img->execute();
        if ($row = $stmt_img->get_result()->fetch_assoc()) {
            if (!empty($row['qr_code_url']) && file_exists('../' . $row['qr_code_url'])) {
                unlink('../' . $row['qr_code_url']);
            }
        }
        $stmt = $conn->prepare("DELETE FROM payment_methods WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $message = '<div class="alert alert-success">Payment method deleted successfully.</div>';
    }
    // --- SAVE (ADD/EDIT) ---
    elseif (isset($_POST['save_method'])) {
        $id = intval($_POST['id'] ?? 0);
        $method_name = trim($_POST['method_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;
        $qr_code_url = $_POST['current_qr_code_url'] ?? '';

        if (isset($_FILES['qr_code']) && $_FILES['qr_code']['error'] == 0) {
            $target_dir = "../uploads/qrcodes/";
            if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
            $target_file = $target_dir . "qr-" . uniqid() . basename($_FILES["qr_code"]["name"]);
            if (move_uploaded_file($_FILES["qr_code"]["tmp_name"], $target_file)) {
                // Delete old QR code if a new one is uploaded during an edit
                if ($id > 0 && !empty($qr_code_url) && file_exists('../' . $qr_code_url)) {
                    unlink('../' . $qr_code_url);
                }
                $qr_code_url = str_replace('../', '', $target_file);
            }
        }

        if ($id > 0) { // Update
            $stmt = $conn->prepare("UPDATE payment_methods SET method_name=?, account_name=?, account_number=?, instructions=?, qr_code_url=?, is_active=? WHERE id=?");
            $stmt->bind_param("sssssii", $method_name, $account_name, $account_number, $instructions, $qr_code_url, $is_active, $id);
            $message = '<div class="alert alert-success">Payment method updated successfully.</div>';
        } else { // Insert
            $stmt = $conn->prepare("INSERT INTO payment_methods (method_name, account_name, account_number, instructions, qr_code_url, is_active) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssssi", $method_name, $account_name, $account_number, $instructions, $qr_code_url, $is_active);
            $message = '<div class="alert alert-success">New payment method added successfully.</div>';
        }
        $stmt->execute();
        $stmt->close();
    }
}

// Fetch a manual method for editing
$edit_method = null;
if (isset($_GET['edit'])) {
    $stmt = $conn->prepare("SELECT * FROM payment_methods WHERE id = ?");
    $stmt->bind_param("i", $_GET['edit']);
    $stmt->execute();
    $edit_method = $stmt->get_result()->fetch_assoc();
}

// The $site_settings variable is already loaded from admin-header.php

// --- PRESENTATION BLOCK ---
include 'admin-header.php';
?>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Manage Payment Methods</h1>
</div>
<?php echo $message; ?>

<div class="card shadow-sm mb-4">
    <div class="card-header fw-bold"><i class="bi bi-robot me-2"></i>Automated Payment Gateways</div>
    <div class="list-group list-group-flush">
        <div class="list-group-item d-flex justify-content-between align-items-center">
            <div>
                <h6 class="mb-0">PayMongo (GCash, Maya, etc.)</h6>
                <small class="text-muted">Automated e-wallet payments.</small>
            </div>
            <div>
                <?php if (isset($site_settings['paymongo_enabled']) && $site_settings['paymongo_enabled'] == '1'): ?>
                    <span class="badge bg-success">Active</span>
                <?php else: ?>
                    <span class="badge bg-secondary">Inactive</span>
                <?php endif; ?>
                <a href="site-settings.php" class="btn btn-sm btn-outline-primary">Configure</a>
            </div>
        </div>
        <div class="list-group-item d-flex justify-content-between align-items-center">
            <div>
                <h6 class="mb-0">PayPal</h6>
                <small class="text-muted">International card payments.</small>
            </div>
            <div>
                <?php if (isset($site_settings['paypal_enabled']) && $site_settings['paypal_enabled'] == '1'): ?>
                    <span class="badge bg-success">Active</span>
                <?php else: ?>
                    <span class="badge bg-secondary">Inactive</span>
                <?php endif; ?>
                <a href="site-settings.php" class="btn btn-sm btn-outline-primary">Configure</a>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm mb-4">
    <div class="card-header fw-bold"><i class="bi bi-pencil-square me-2"></i><?php echo $edit_method ? 'Edit Manual Method' : 'Add New Manual Method'; ?></div>
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data" action="manage-payment-methods.php">
            <input type="hidden" name="id" value="<?php echo $edit_method['id'] ?? 0; ?>">
            <div class="row">
                <div class="col-md-4 mb-3"><label>Method Name</label><input type="text" name="method_name" class="form-control" value="<?php echo htmlspecialchars($edit_method['method_name'] ?? ''); ?>" placeholder="e.g., GCash" required></div>
                <div class="col-md-4 mb-3"><label>Account Name</label><input type="text" name="account_name" class="form-control" value="<?php echo htmlspecialchars($edit_method['account_name'] ?? ''); ?>" placeholder="e.g., Juan Dela Cruz" required></div>
                <div class="col-md-4 mb-3"><label>Account / Phone Number</label><input type="text" name="account_number" class="form-control" value="<?php echo htmlspecialchars($edit_method['account_number'] ?? ''); ?>" placeholder="e.g., 09171234567" required></div>
            </div>
            <div class="mb-3"><label>Instructions for User</label><textarea name="instructions" class="form-control" rows="3"><?php echo htmlspecialchars($edit_method['instructions'] ?? ''); ?></textarea></div>
            <div class="mb-3">
                <label>QR Code Image (Optional)</label><input type="file" name="qr_code" class="form-control" accept="image/*">
                <input type="hidden" name="current_qr_code_url" value="<?php echo htmlspecialchars($edit_method['qr_code_url'] ?? ''); ?>">
                <?php if (!empty($edit_method['qr_code_url'])): ?><div class="mt-2"><img src="../<?php echo htmlspecialchars($edit_method['qr_code_url']); ?>" style="max-height: 150px;" class="img-thumbnail"></div><?php endif; ?>
            </div>
            <div class="form-check form-switch mb-3"><input type="checkbox" class="form-check-input" id="is_active" name="is_active" value="1" <?php echo (isset($edit_method['is_active']) && $edit_method['is_active']) || !$edit_method ? 'checked' : ''; ?>><label class="form-check-label" for="is_active">Enable this payment method</label></div>
            <button type="submit" name="save_method" class="btn btn-primary"><?php echo $edit_method ? 'Save Changes' : 'Add Method'; ?></button>
            <?php if ($edit_method): ?><a href="manage-payment-methods.php" class="btn btn-secondary">Cancel Edit</a><?php endif; ?>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header fw-bold">Existing Manual Methods</div>
    <div class="table-responsive">
        <table class="table table-hover align-middle">
            <thead class="table-dark"><tr><th>Method</th><th>Account Details</th><th>Status</th><th>Actions</th></tr></thead>
            <tbody>
            <?php $result = $conn->query("SELECT * FROM payment_methods ORDER BY method_name ASC"); while ($row = $result->fetch_assoc()): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($row['method_name']); ?></strong></td>
                    <td><?php echo htmlspecialchars($row['account_name']); ?><br><small class="text-muted"><?php echo htmlspecialchars($row['account_number']); ?></small></td>
                    <td><span class="badge <?php echo $row['is_active'] ? 'bg-success' : 'bg-secondary'; ?>"><?php echo $row['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                    <td>
                        <a href="?edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                        <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure?');"><input type="hidden" name="id" value="<?php echo $row['id']; ?>"><button type="submit" name="delete_method" class="btn btn-sm btn-danger">Delete</button></form>
                    </td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>
<?php include 'admin-footer.php'; ?>
