<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include("check_installation.php");
include("fetch_settings.php");
require_once("../config/topup_helpers.php");

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

ensureTopupSchema($con);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['save_method'])) {
        $methodId = isset($_POST['method_id']) ? (int) $_POST['method_id'] : 0;
        $methodName = trim($_POST['method_name'] ?? '');
        $methodType = trim($_POST['method_type'] ?? 'other');
        $walletAddress = trim($_POST['wallet_address'] ?? '');
        $networkType = trim($_POST['network_type'] ?? '');
        $bankName = trim($_POST['bank_name'] ?? '');
        $accountName = trim($_POST['account_name'] ?? '');
        $accountNumber = trim($_POST['account_number'] ?? '');
        $instructions = trim($_POST['instructions'] ?? '');
        $requireReceipt = isset($_POST['require_receipt']) ? 1 : 0;
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if ($methodType === 'crypto') {
            $bankName = '';
            $accountName = '';
            $accountNumber = '';
        } else {
            $walletAddress = '';
            $networkType = '';
        }

        if ($methodName === '') {
            $_SESSION['message'] = ['type' => 'error', 'text' => 'Method name is required.'];
        } else {
            if ($methodId > 0) {
                $stmt = $con->prepare("
                    UPDATE payment_methods
                    SET method_name=?, method_type=?, wallet_address=?, network_type=?, bank_name=?, account_name=?, account_number=?, instructions=?, require_receipt=?, is_active=?
                    WHERE id=?
                ");
                $stmt->bind_param(
                    "ssssssssiii",
                    $methodName,
                    $methodType,
                    $walletAddress,
                    $networkType,
                    $bankName,
                    $accountName,
                    $accountNumber,
                    $instructions,
                    $requireReceipt,
                    $isActive,
                    $methodId
                );
                $stmt->execute();
                $stmt->close();
                $_SESSION['message'] = ['type' => 'success', 'text' => 'Payment method updated successfully.'];
            } else {
                $stmt = $con->prepare("
                    INSERT INTO payment_methods (method_name, method_type, wallet_address, network_type, bank_name, account_name, account_number, instructions, require_receipt, is_active)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->bind_param(
                    "ssssssssii",
                    $methodName,
                    $methodType,
                    $walletAddress,
                    $networkType,
                    $bankName,
                    $accountName,
                    $accountNumber,
                    $instructions,
                    $requireReceipt,
                    $isActive
                );
                $stmt->execute();
                $stmt->close();
                $_SESSION['message'] = ['type' => 'success', 'text' => 'Payment method created successfully.'];
            }
        }
    }

    if (isset($_POST['delete_method'])) {
        $methodId = (int) $_POST['delete_method'];
        $stmtDelete = $con->prepare("DELETE FROM payment_methods WHERE id=?");
        $stmtDelete->bind_param("i", $methodId);
        $stmtDelete->execute();
        $stmtDelete->close();
        $_SESSION['message'] = ['type' => 'success', 'text' => 'Payment method deleted successfully.'];
    }

    header("Location: payment_settings.php");
    exit;
}

$editMethod = null;
if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];
    $stmtEdit = $con->prepare("SELECT * FROM payment_methods WHERE id=? LIMIT 1");
    $stmtEdit->bind_param("i", $editId);
    $stmtEdit->execute();
    $editMethod = $stmtEdit->get_result()->fetch_assoc();
    $stmtEdit->close();
}

$methods = [];
$resultMethods = $con->query("SELECT * FROM payment_methods ORDER BY id DESC");
while ($row = $resultMethods->fetch_assoc()) {
    $methods[] = $row;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Payment Settings</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">

    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&amp;family=Poppins:wght@400;500;700&amp;display=swap">
    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/apexcharts/css/apexcharts.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<body>
<main>
    <?php include "include/sidebar.php" ?>
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        <div class="page-content-wrapper p-xxl-4">
            <div class="row">
                <div class="col-12 mb-4 mb-sm-5">
                    <h1 class="h3 mb-2 mb-sm-0">Top Up Payment Settings</h1>
                    <p class="text-muted mb-0">Create and manage methods customers can use for account top up.</p>
                </div>
            </div>

            <?php if (isset($_SESSION['message'])): $message = $_SESSION['message']; unset($_SESSION['message']); ?>
                <script>
                    document.addEventListener('DOMContentLoaded', function() {
                        Swal.fire({
                            title: '<?= $message['type'] === 'success' ? 'Success' : 'Error'; ?>',
                            text: '<?= $message['text']; ?>',
                            icon: '<?= $message['type']; ?>',
                            confirmButtonText: 'OK'
                        });
                    });
                </script>
            <?php endif; ?>

            <div class="row g-4">
                <div class="col-xl-5">
                    <div class="card shadow">
                        <div class="card-header border-bottom">
                            <h5 class="card-title mb-0"><?= $editMethod ? 'Edit Payment Method' : 'Create Payment Method'; ?></h5>
                        </div>
                        <div class="card-body">
                            <form method="post">
                                <input type="hidden" name="method_id" value="<?= (int) ($editMethod['id'] ?? 0); ?>">
                                <div class="mb-3">
                                    <label class="form-label">Method Name</label>
                                    <input type="text" name="method_name" class="form-control" required value="<?= htmlspecialchars($editMethod['method_name'] ?? ''); ?>" placeholder="e.g. Bitcoin, Ethereum, Bank Transfer">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Method Type</label>
                                    <select name="method_type" id="payment_method_type" class="form-select">
                                        <?php $currentType = $editMethod['method_type'] ?? 'other'; ?>
                                        <option value="crypto" <?= $currentType === 'crypto' ? 'selected' : ''; ?>>Crypto</option>
                                        <option value="bank" <?= $currentType === 'bank' ? 'selected' : ''; ?>>Bank Transfer</option>
                                        <option value="other" <?= $currentType === 'other' ? 'selected' : ''; ?>>Other</option>
                                    </select>
                                </div>
                                <div class="mb-3 payment-fields-crypto" id="fields_crypto">
                                    <label class="form-label">Wallet Address</label>
                                    <input type="text" name="wallet_address" class="form-control" value="<?= htmlspecialchars($editMethod['wallet_address'] ?? ''); ?>" placeholder="Wallet address shown to users">
                                    <label class="form-label mt-3">Network Type</label>
                                    <input type="text" name="network_type" class="form-control" value="<?= htmlspecialchars($editMethod['network_type'] ?? ''); ?>" placeholder="e.g. ERC-20, TRC-20, BEP-20, Bitcoin">
                                </div>
                                <div class="mb-3 payment-fields-bank" id="fields_bank">
                                    <label class="form-label">Bank Name</label>
                                    <input type="text" name="bank_name" class="form-control" value="<?= htmlspecialchars($editMethod['bank_name'] ?? ''); ?>" placeholder="Bank name for transfers">
                                    <label class="form-label mt-3">Account Name</label>
                                    <input type="text" name="account_name" class="form-control" value="<?= htmlspecialchars($editMethod['account_name'] ?? ''); ?>">
                                    <label class="form-label mt-3">Account Number</label>
                                    <input type="text" name="account_number" class="form-control" value="<?= htmlspecialchars($editMethod['account_number'] ?? ''); ?>">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Instructions</label>
                                    <textarea name="instructions" class="form-control" rows="4" placeholder="Instructions user should follow"><?= htmlspecialchars($editMethod['instructions'] ?? ''); ?></textarea>
                                </div>
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input" type="checkbox" id="require_receipt" name="require_receipt" <?= isset($editMethod['require_receipt']) && (int)$editMethod['require_receipt'] === 1 ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="require_receipt">Require receipt/screenshot upload</label>
                                </div>
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="is_active" name="is_active" <?= !isset($editMethod['is_active']) || (int)$editMethod['is_active'] === 1 ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="is_active">Method is active for users</label>
                                </div>
                                <button type="submit" name="save_method" class="btn btn-primary">
                                    <?= $editMethod ? 'Update Method' : 'Create Method'; ?>
                                </button>
                                <?php if ($editMethod): ?>
                                    <a href="payment_settings.php" class="btn btn-light">Cancel Edit</a>
                                <?php endif; ?>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-xl-7">
                    <div class="card shadow">
                        <div class="card-header border-bottom">
                            <h5 class="card-title mb-0">Configured Payment Methods</h5>
                        </div>
                        <div class="card-body">
                            <?php if (empty($methods)): ?>
                                <p class="mb-0 text-muted">No payment method has been created yet.</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table align-middle mb-0">
                                        <thead>
                                        <tr>
                                            <th>Name</th>
                                            <th>Type</th>
                                            <th>Wallet/Account</th>
                                            <th>Receipt</th>
                                            <th>Status</th>
                                            <th>Action</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <?php foreach ($methods as $method): ?>
                                            <tr>
                                                <td><?= htmlspecialchars($method['method_name']); ?></td>
                                                <td><?= htmlspecialchars(ucfirst($method['method_type'])); ?></td>
                                                <td>
                                                    <?php
                                                    if ($method['method_type'] === 'crypto') {
                                                        $w = trim((string) ($method['wallet_address'] ?? ''));
                                                        $net = trim((string) ($method['network_type'] ?? ''));
                                                        $line = $w !== '' ? $w : '—';
                                                        if ($net !== '') {
                                                            $line .= ' (' . $net . ')';
                                                        }
                                                        echo htmlspecialchars($line);
                                                    } else {
                                                        $accNumber = trim((string) $method['account_number']);
                                                        echo htmlspecialchars($accNumber !== '' ? $accNumber : '—');
                                                    }
                                                    ?>
                                                </td>
                                                <td>
                                                    <span class="badge <?= (int)$method['require_receipt'] === 1 ? 'bg-warning' : 'bg-secondary'; ?>">
                                                        <?= (int)$method['require_receipt'] === 1 ? 'Required' : 'Optional'; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span class="badge <?= (int)$method['is_active'] === 1 ? 'bg-success' : 'bg-danger'; ?>">
                                                        <?= (int)$method['is_active'] === 1 ? 'Active' : 'Inactive'; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <a href="payment_settings.php?edit=<?= (int)$method['id']; ?>" class="btn btn-sm btn-primary-soft">Edit</a>
                                                    <form method="post" style="display:inline-block;" onsubmit="return confirm('Delete this method?');">
                                                        <button type="submit" name="delete_method" value="<?= (int)$method['id']; ?>" class="btn btn-sm btn-danger-soft">Delete</button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="assets/vendor/apexcharts/js/apexcharts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="assets/js/functions.js"></script>
<script>
(function () {
    const typeSelect = document.getElementById('payment_method_type');
    const cryptoWrap = document.getElementById('fields_crypto');
    const bankWrap = document.getElementById('fields_bank');
    if (!typeSelect || !cryptoWrap || !bankWrap) return;
    const sync = () => {
        const t = typeSelect.value;
        if (t === 'crypto') {
            cryptoWrap.classList.remove('d-none');
            bankWrap.classList.add('d-none');
        } else {
            cryptoWrap.classList.add('d-none');
            bankWrap.classList.remove('d-none');
        }
    };
    typeSelect.addEventListener('change', sync);
    sync();
})();
</script>
</body>
</html>

