<?php
// POST handling before any output
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/settings.php';
require_once __DIR__ . '/../includes/zoho.php';
auth_require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    foreach (($_POST['settings'] ?? []) as $key => $value) {
        // The default-payout-fee field is shown in Rand for human-friendliness
        // but stored in cents. Convert before save.
        if ($key === 'zoho.payfast_payout_fee_default_cents') {
            $value = (int)round(((float)$value) * 100);
        }
        $row = db_row('SELECT `key`,`type` FROM app_settings WHERE `key`=:k', ['k'=>$key]);
        if (!$row) {
            setting_set($key, $value, 'string');
            continue;
        }
        setting_set($key, $value, $row['type']);
    }
    header('Location: payment-fees.php?msg=saved'); exit;
}

$page_title = 'Payment Fees';
require __DIR__ . '/_guard.php';

$gateway_fees = setting_all_in_category('gateway_fees');

// Pull expense accounts from Zoho for the picker
$expense_accounts = [];
$bank_accounts    = [];
$zoho_load_error  = null;
if (zoho_is_configured()) {
    $r = zoho_request('GET', '/chartofaccounts?filter_by=AccountType.Expense&per_page=200');
    if ($r['ok']) {
        $expense_accounts = $r['data']['chartofaccounts'] ?? [];
    } else {
        $zoho_load_error = 'Could not load expense accounts from Zoho (HTTP ' . $r['status'] . ').';
    }
    // Load bank accounts (these are in the /bankaccounts endpoint, not chartofaccounts)
    $rb = zoho_request('GET', '/bankaccounts');
    if ($rb['ok']) {
        $bank_accounts = $rb['data']['bankaccounts'] ?? [];
    }
}
$current_fee_account     = setting_get('gateway_fee_account_id', '');
$current_payfast_account = setting_get('zoho.payfast_account_id', '');
$current_netcash_account = setting_get('zoho.netcash_account_id', '');
$current_real_bank       = setting_get('zoho.real_bank_account_id', '');
$payout_fee_default_cents = (int)setting_get('zoho.payfast_payout_fee_default_cents', 1000);
$auto_email_invoice      = (int)setting_get('zoho.auto_email_invoice', 0);
?>

<style>
.set-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.5rem;margin-bottom:1.25rem;}
.set-grid{display:grid;grid-template-columns:repeat(3, 1fr);gap:1rem;}
@media(max-width:800px){.set-grid{grid-template-columns:1fr;}}
.set-grid label{font-weight:600;font-size:.85rem;}
.set-grid .desc{font-size:.78rem;color:var(--ink-muted);margin:.15rem 0 .35rem;}
.set-input-wrap{position:relative;}
.set-input-wrap input{padding-right:2.5rem;}
.set-input-wrap .suffix{position:absolute;right:.7rem;top:50%;transform:translateY(-50%);color:var(--ink-muted);font-size:.85rem;pointer-events:none;}
</style>

<?php
$settings_section = 'payment_fees';
require __DIR__ . '/_settings_open.php';
?>

<div class="settings-page-head">
    <h1>Payment Fees</h1>
    <p class="crumb">Gateway fee rates and accounting category for auto-recording fees.</p>
</div>

<?php if (isset($_GET['msg']) && $_GET['msg']==='saved'): ?>
    <div class="alert alert-success" data-autohide>Settings saved.</div>
<?php endif; ?>

<form method="post">
    <?= csrf_field() ?>

    <div class="set-card">
        <h2 style="margin-top:0;font-size:1.05rem;">Zoho expense category</h2>
        <p class="muted" style="font-size:.88rem;margin:0 0 1rem;">
            Pick which Zoho Books expense account to charge gateway fees against. This should be
            "Bank Charges", "Merchant Fees", "Bank fees", or similar — <strong>not</strong> Bad Debt or Cost of Goods Sold.
            If you don't have a suitable account in Zoho yet, create one in
            <em>Zoho Books → Accountant → Chart of Accounts → New Account</em> and refresh this page.
        </p>

        <?php if ($zoho_load_error): ?>
            <div class="alert alert-error"><?= htmlspecialchars($zoho_load_error) ?></div>
        <?php elseif (empty($expense_accounts)): ?>
            <div class="alert alert-info">
                No expense accounts found in your Zoho Books. Create one in Zoho first.
            </div>
        <?php else: ?>
            <label>Expense account</label>
            <select name="settings[gateway_fee_account_id]">
                <option value="">— auto-detect (looks for "Bank Charges") —</option>
                <?php foreach ($expense_accounts as $a):
                    $aid = (string)($a['account_id'] ?? '');
                    $name = (string)($a['account_name'] ?? '');
                ?>
                    <option value="<?= htmlspecialchars($aid) ?>" <?= $current_fee_account === $aid ? 'selected' : '' ?>>
                        <?= htmlspecialchars($name) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <p class="desc" style="font-size:.78rem;color:var(--ink-muted);margin:.35rem 0 0;">
                Currently selected: <strong><?php
                    if ($current_fee_account) {
                        $found = null;
                        foreach ($expense_accounts as $a) {
                            if ((string)$a['account_id'] === $current_fee_account) { $found = $a['account_name']; break; }
                        }
                        echo htmlspecialchars($found ?: 'unknown account');
                    } else {
                        echo 'auto-detect';
                    }
                ?></strong>
            </p>
        <?php endif; ?>
    </div>

    <div class="set-card">
        <h2 style="margin-top:0;font-size:1.05rem;">Gateway bank accounts in Zoho</h2>
        <p class="muted" style="font-size:.88rem;margin:0 0 1rem;">
            Pick which Zoho Books bank account represents each gateway. When a payment comes in, the
            customer payment AND the gateway fee are recorded against this account. If you don't have a
            "PayFast" bank account in Zoho yet, create one in
            <em>Zoho Books → Banking → Add Bank Account</em> as a manual account (no live feed needed).
        </p>

        <?php if (empty($bank_accounts) && zoho_is_configured()): ?>
            <div class="alert alert-info">
                No bank accounts found in your Zoho Books. Create one called "PayFast" in Zoho first.
            </div>
        <?php else: ?>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
                <div>
                    <label>PayFast → Zoho bank account</label>
                    <select name="settings[zoho.payfast_account_id]">
                        <option value="">— not set (Zoho automation off for PayFast) —</option>
                        <?php foreach ($bank_accounts as $b):
                            $bid = (string)($b['account_id'] ?? '');
                            $bn  = (string)($b['account_name'] ?? '');
                        ?>
                            <option value="<?= htmlspecialchars($bid) ?>" <?= $current_payfast_account===$bid?'selected':'' ?>>
                                <?= htmlspecialchars($bn) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>Netcash → Zoho bank account</label>
                    <select name="settings[zoho.netcash_account_id]">
                        <option value="">— not set —</option>
                        <?php foreach ($bank_accounts as $b):
                            $bid = (string)($b['account_id'] ?? '');
                            $bn  = (string)($b['account_name'] ?? '');
                        ?>
                            <option value="<?= htmlspecialchars($bid) ?>" <?= $current_netcash_account===$bid?'selected':'' ?>>
                                <?= htmlspecialchars($bn) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-top:1rem;">
                <div>
                    <label>Destination bank account (for PayFast payouts)</label>
                    <p class="desc" style="font-size:.78rem;color:var(--ink-muted);margin:.15rem 0 .35rem;">
                        Where PayFast deposits land. Used by the Payouts page to record transfers from PayFast → Bank.
                    </p>
                    <select name="settings[zoho.real_bank_account_id]">
                        <option value="">— not set (Payouts disabled) —</option>
                        <?php foreach ($bank_accounts as $b):
                            $bid = (string)($b['account_id'] ?? '');
                            $bn  = (string)($b['account_name'] ?? '');
                        ?>
                            <option value="<?= htmlspecialchars($bid) ?>" <?= $current_real_bank===$bid?'selected':'' ?>>
                                <?= htmlspecialchars($bn) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>Default PayFast payout fee (R, incl VAT)</label>
                    <p class="desc" style="font-size:.78rem;color:var(--ink-muted);margin:.15rem 0 .35rem;">
                        Pre-fills the Payouts form. PayFast charges R8.70 + 15% VAT = R10.00.
                    </p>
                    <input type="number" step="0.01" min="0"
                           name="settings[zoho.payfast_payout_fee_default_cents]"
                           value="<?= number_format($payout_fee_default_cents/100, 2, '.', '') ?>"
                           data-cents="1">
                </div>
            </div>

            <label style="display:flex;align-items:center;gap:.5rem;font-weight:normal;cursor:pointer;margin-top:1rem;">
                <input type="hidden" name="settings[zoho.auto_email_invoice]" value="0">
                <input type="checkbox" name="settings[zoho.auto_email_invoice]" value="1" <?= $auto_email_invoice?'checked':'' ?>>
                <span>Have Zoho automatically email the invoice (with PDF) to the customer when payment is recorded</span>
            </label>
            <p class="muted" style="font-size:.78rem;margin:.25rem 0 0 1.5rem;">
                The site will still send its own <code>payment_received</code> email regardless. This adds the formal Zoho invoice email on top.
            </p>
        <?php endif; ?>
    </div>

    <div class="set-card">
        <h2 style="margin-top:0;font-size:1.05rem;">Gateway rates</h2>
        <p class="muted" style="font-size:.88rem;margin:0 0 1rem;">
            These rates are used to auto-record gateway fee expenses against your bank account when payments come in.
            Edit these to match your actual contract rates with PayFast and Netcash.
        </p>

        <h3 style="font-size:.95rem;margin:1.25rem 0 .5rem;">PayFast</h3>
        <div class="set-grid">
            <?php
            $payfast_keys = array_filter($gateway_fees, fn($s) => str_starts_with($s['key'], 'payfast.'));
            foreach ($payfast_keys as $s):
                $suffix = str_contains($s['key'], 'percent') ? '%' : 'R';
            ?>
                <div>
                    <label><?= htmlspecialchars($s['label']) ?></label>
                    <p class="desc"><?= htmlspecialchars($s['description']) ?></p>
                    <div class="set-input-wrap">
                        <input type="number" step="0.01" name="settings[<?= htmlspecialchars($s['key']) ?>]"
                               value="<?= htmlspecialchars($s['value']) ?>">
                        <span class="suffix"><?= $suffix ?></span>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <h3 style="font-size:.95rem;margin:1.5rem 0 .5rem;">Netcash</h3>
        <div class="set-grid">
            <?php
            $netcash_keys = array_filter($gateway_fees, fn($s) => str_starts_with($s['key'], 'netcash.'));
            foreach ($netcash_keys as $s):
                $suffix = str_contains($s['key'], 'percent') ? '%' : 'R';
            ?>
                <div>
                    <label><?= htmlspecialchars($s['label']) ?></label>
                    <p class="desc"><?= htmlspecialchars($s['description']) ?></p>
                    <div class="set-input-wrap">
                        <input type="number" step="0.01" name="settings[<?= htmlspecialchars($s['key']) ?>]"
                               value="<?= htmlspecialchars($s['value']) ?>">
                        <span class="suffix"><?= $suffix ?></span>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <button type="submit" class="btn">Save settings</button>
</form>

<?php require __DIR__ . '/_settings_close.php'; ?>

<?php require __DIR__ . '/_footer.php'; ?>