<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/zoho.php';
auth_require_admin();

$flash = null;

// ── POST handling ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? '';

    if ($action === 'record_payout') {
        $payout_rand = (float)($_POST['payout_amount'] ?? 0);
        $fee_rand    = (float)($_POST['fee_amount']    ?? 0);
        $payout_date = $_POST['payout_date'] ?? date('Y-m-d');
        $notes       = trim((string)($_POST['notes'] ?? ''));

        if ($payout_rand <= 0) {
            $flash = ['err'=>'Payout amount must be greater than zero'];
        } elseif (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $payout_date)) {
            $flash = ['err'=>'Invalid date'];
        } else {
            $payout_cents = (int)round($payout_rand * 100);
            $fee_cents    = (int)round($fee_rand * 100);

            // Create local row first so we can track even if Zoho fails
            $local_id = db_insert('payfast_payouts', [
                'payout_amount_cents' => $payout_cents,
                'fee_cents'           => $fee_cents,
                'payout_date'         => $payout_date,
                'notes'               => $notes ?: null,
                'status'              => 'processing',
                'created_by'          => (int)($_SESSION['admin_id'] ?? 0) ?: null,
            ]);

            // Push to Zoho
            $r = zoho_record_payfast_payout($payout_cents, $fee_cents, $payout_date, $notes);

            if ($r['ok']) {
                db_exec(
                    "UPDATE payfast_payouts
                        SET zoho_transfer_id = :tr, zoho_expense_id = :ex,
                            status = 'created', sync_error = NULL
                      WHERE id = :id",
                    ['tr'=>$r['transfer_id'], 'ex'=>$r['expense_id'] ?: null, 'id'=>$local_id]
                );
                $flash = ['ok'=>'Payout recorded in Zoho.' . (empty($r['expense_id']) && $fee_cents > 0
                    ? ' (Fee expense couldn\'t be created — check that "Bank Charges" expense account exists in Zoho.)'
                    : '')];
                app_log("PayFast payout #$local_id recorded — transfer={$r['transfer_id']}, expense={$r['expense_id']}");
            } else {
                db_exec(
                    "UPDATE payfast_payouts SET status='error', sync_error=:e WHERE id=:id",
                    ['e'=>mb_substr((string)$r['error'], 0, 1000), 'id'=>$local_id]
                );
                $flash = ['err'=>'Zoho sync failed: ' . ($r['error'] ?? 'unknown')];
                app_log("PayFast payout #$local_id sync failed: " . ($r['error'] ?? 'unknown'));
            }
            header('Location: payfast-payouts.php?msg='.urlencode($flash['ok'] ?? '').'&err='.urlencode($flash['err'] ?? ''));
            exit;
        }
    }

    if ($action === 'mark_received') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            db_exec(
                "UPDATE payfast_payouts SET status='matched', matched_at=NOW() WHERE id=:id AND status='created'",
                ['id'=>$id]
            );
        }
        header('Location: payfast-payouts.php?msg=' . urlencode('Marked as received.'));
        exit;
    }

    if ($action === 'retry') {
        $id = (int)($_POST['id'] ?? 0);
        $row = db_row('SELECT * FROM payfast_payouts WHERE id=:id', ['id'=>$id]);
        if ($row && $row['status'] === 'error') {
            $r = zoho_record_payfast_payout(
                (int)$row['payout_amount_cents'],
                (int)$row['fee_cents'],
                (string)$row['payout_date'],
                (string)($row['notes'] ?? '')
            );
            if ($r['ok']) {
                db_exec(
                    "UPDATE payfast_payouts
                        SET zoho_transfer_id=:tr, zoho_expense_id=:ex,
                            status='created', sync_error=NULL
                      WHERE id=:id",
                    ['tr'=>$r['transfer_id'], 'ex'=>$r['expense_id'] ?: null, 'id'=>$id]
                );
                $flash = ['ok'=>'Retry succeeded.'];
            } else {
                db_exec(
                    "UPDATE payfast_payouts SET sync_error=:e WHERE id=:id",
                    ['e'=>mb_substr((string)$r['error'], 0, 1000), 'id'=>$id]
                );
                $flash = ['err'=>'Retry failed: ' . ($r['error'] ?? 'unknown')];
            }
            header('Location: payfast-payouts.php?msg='.urlencode($flash['ok'] ?? '').'&err='.urlencode($flash['err'] ?? ''));
            exit;
        }
    }

    if ($action === 'delete') {
        // Only allows deleting an "error" row (one that never made it to Zoho)
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            db_exec("DELETE FROM payfast_payouts WHERE id=:id AND status='error'", ['id'=>$id]);
        }
        header('Location: payfast-payouts.php?msg=' . urlencode('Removed.'));
        exit;
    }
}

$page_title = 'PayFast Payouts';
require __DIR__ . '/_guard.php';

// ── Read state ──────────────────────────────────────────────
$tab          = $_GET['tab'] ?? 'pending';   // pending | matched | error | all
$where_status = '1=1';
switch ($tab) {
    case 'pending': $where_status = "status='created'"; break;
    case 'matched': $where_status = "status='matched'"; break;
    case 'error':   $where_status = "status IN ('error','processing')"; break;
}

$payouts = db_all(
    "SELECT * FROM payfast_payouts WHERE $where_status
      ORDER BY payout_date DESC, id DESC LIMIT 200"
);

// Counts for the tab badges
$counts = db_row("
    SELECT
        SUM(CASE WHEN status='created'  THEN 1 ELSE 0 END) AS pending,
        SUM(CASE WHEN status='matched'  THEN 1 ELSE 0 END) AS matched,
        SUM(CASE WHEN status IN ('error','processing') THEN 1 ELSE 0 END) AS errored,
        COUNT(*) AS total
      FROM payfast_payouts
");

// Settings — to know whether the form is operable
$payfast_account_id   = (string)setting_get('zoho.payfast_account_id', '');
$real_bank_account_id = (string)setting_get('zoho.real_bank_account_id', '');
$payout_fee_default   = (int)setting_get('zoho.payfast_payout_fee_default_cents', 1000);
$config_ok            = ($payfast_account_id !== '' && $real_bank_account_id !== '' && zoho_is_configured());

function payout_status_pill(string $status): string {
    $map = [
        'processing' => ['label'=>'Processing',    'style'=>'background:#e5e7eb;color:#374151;'],
        'created'    => ['label'=>'Pending bank',  'style'=>'background:#dbeafe;color:#1e40af;'],
        'matched'    => ['label'=>'Received',      'style'=>'background:#dcfce7;color:#166534;'],
        'error'      => ['label'=>'Error',         'style'=>'background:#fee2e2;color:#991b1b;'],
    ];
    $info = $map[$status] ?? ['label'=>ucfirst($status), 'style'=>'background:#e5e7eb;color:#374151;'];
    return '<span style="' . $info['style'] . 'display:inline-block;padding:.15em .55em;border-radius:3px;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;">' . htmlspecialchars($info['label']) . '</span>';
}

function rand_fmt(int $cents): string {
    return 'R&nbsp;' . number_format($cents/100, 2, '.', ',');
}
?>

<style>
.flash{padding:.85rem 1rem;border-radius:6px;margin-bottom:1rem;font-size:.9rem;}
.flash.ok{background:#dcfce7;color:#166534;border:1px solid #86efac;}
.flash.err{background:#fee2e2;color:#991b1b;border:1px solid #fca5a5;}

.card-form{background:#fff;border:1px solid var(--line);border-radius:8px;padding:1.5rem;margin-bottom:1.5rem;}
.form-grid{display:grid;grid-template-columns:repeat(3, 1fr);gap:1rem;margin-bottom:1rem;}
@media(max-width:800px){.form-grid{grid-template-columns:1fr;}}
.form-grid label{font-weight:600;font-size:.85rem;display:block;margin-bottom:.25rem;}
.form-grid input{width:100%;padding:.55rem .7rem;border:1px solid var(--line);border-radius:6px;font-size:.9rem;font-family:inherit;}
.form-grid .hint{font-size:.75rem;color:var(--ink-muted);margin-top:.25rem;}

.tabs{display:flex;gap:.5rem;flex-wrap:wrap;margin-bottom:1rem;}
.tab{padding:.4rem .9rem;border-radius:999px;border:1px solid var(--line);text-decoration:none;color:var(--ink);font-size:.85rem;background:#fff;display:inline-flex;align-items:center;gap:.4rem;}
.tab.on{background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);}
.tab .ct{font-size:.7rem;background:rgba(0,0,0,.1);padding:.05em .45em;border-radius:999px;}
.tab.on .ct{background:rgba(255,255,255,.25);}

.po-tbl{width:100%;border-collapse:collapse;font-size:.875rem;}
.po-tbl th{padding:.55rem 1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
.po-tbl th.r{text-align:right;}
.po-tbl td{padding:.7rem 1rem;border-bottom:1px solid var(--line);vertical-align:top;}
.po-tbl td.r{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums;}
.po-tbl tr:hover td{background:#fafaf8;}
.po-tbl .err-msg{font-size:.78rem;color:#991b1b;margin-top:.25rem;}
.po-tbl button.linkbtn{background:none;border:none;padding:0;color:var(--brand-primary);cursor:pointer;font-size:.85rem;font-family:inherit;}
.po-tbl button.linkbtn:hover{text-decoration:underline;}
.po-tbl button.linkbtn.danger{color:#991b1b;}

.cfg-warn{background:#fef3c7;border:1px solid #fde68a;color:#92400e;padding:1rem 1.25rem;border-radius:8px;margin-bottom:1.5rem;font-size:.9rem;}
.cfg-warn strong{display:block;margin-bottom:.25rem;}
</style>

<section class="section"><div class="container">

<p style="margin:0 0 .75rem;font-size:.85rem;">
    <a href="accounting.php" style="color:var(--ink-muted);text-decoration:none;">← Back to accounting</a>
</p>

<div style="display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:1rem;margin-bottom:1rem;">
    <div>
        <h1 style="margin:0;">PayFast Payouts</h1>
        <p class="muted" style="margin:.25rem 0 0;font-size:.85rem;">
            Record a payout from PayFast → bank. We'll create the transfer and the payout fee
            in Zoho automatically. PayFast holding-account drops by total deducted; the matching
            deposit on your real bank account arrives via the bank feed.
        </p>
    </div>
</div>

<?php if (!empty($_GET['msg'])): ?>
    <div class="flash ok"><?= htmlspecialchars((string)$_GET['msg']) ?></div>
<?php endif; ?>
<?php if (!empty($_GET['err'])): ?>
    <div class="flash err"><?= htmlspecialchars((string)$_GET['err']) ?></div>
<?php endif; ?>

<?php if (!$config_ok): ?>
    <div class="cfg-warn">
        <strong>Configuration incomplete</strong>
        Before recording payouts, set both the <em>PayFast Zoho bank account</em> and the
        <em>Destination bank account</em> in
        <a href="payment-fees.php"><strong>Settings → Payment Fees</strong></a>.
    </div>
<?php endif; ?>

<!-- Record payout form -->
<div class="card-form">
    <h2 style="margin-top:0;font-size:1.05rem;">Record a payout</h2>
    <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="record_payout">

        <div class="form-grid">
            <div>
                <label for="payout_amount">Payout amount (R)</label>
                <input type="number" step="0.01" min="0" id="payout_amount" name="payout_amount"
                       placeholder="0.00" required <?= !$config_ok ? 'disabled' : '' ?>>
                <div class="hint">Gross amount PayFast paid out to your bank.</div>
            </div>
            <div>
                <label for="fee_amount">PayFast fee (R, incl VAT)</label>
                <input type="number" step="0.01" min="0" id="fee_amount" name="fee_amount"
                       value="<?= number_format($payout_fee_default/100, 2, '.', '') ?>"
                       <?= !$config_ok ? 'disabled' : '' ?>>
                <div class="hint">Default editable in Settings → Payment Fees.</div>
            </div>
            <div>
                <label for="payout_date">Date</label>
                <input type="date" id="payout_date" name="payout_date"
                       value="<?= date('Y-m-d') ?>" required <?= !$config_ok ? 'disabled' : '' ?>>
                <div class="hint">Use the date PayFast initiated the payout.</div>
            </div>
        </div>
        <div style="margin-bottom:1rem;">
            <label for="notes" style="font-weight:600;font-size:.85rem;display:block;margin-bottom:.25rem;">Notes (optional)</label>
            <input type="text" id="notes" name="notes" maxlength="200"
                   placeholder="e.g. PayFast batch #1234"
                   style="width:100%;padding:.55rem .7rem;border:1px solid var(--line);border-radius:6px;font-size:.9rem;font-family:inherit;"
                   <?= !$config_ok ? 'disabled' : '' ?>>
        </div>

        <button type="submit" class="btn" <?= !$config_ok ? 'disabled' : '' ?>>Record payout</button>
    </form>
</div>

<!-- Tabs -->
<div class="tabs">
    <a href="?tab=pending" class="tab <?= $tab==='pending' ? 'on' : '' ?>">
        Pending bank match <span class="ct"><?= (int)$counts['pending'] ?></span>
    </a>
    <a href="?tab=matched" class="tab <?= $tab==='matched' ? 'on' : '' ?>">
        Received <span class="ct"><?= (int)$counts['matched'] ?></span>
    </a>
    <a href="?tab=error" class="tab <?= $tab==='error' ? 'on' : '' ?>">
        Errors <span class="ct"><?= (int)$counts['errored'] ?></span>
    </a>
    <a href="?tab=all" class="tab <?= $tab==='all' ? 'on' : '' ?>">
        All <span class="ct"><?= (int)$counts['total'] ?></span>
    </a>
</div>

<!-- Payouts table -->
<?php if (empty($payouts)): ?>
    <div class="card" style="text-align:center;padding:2.5rem 1rem;">
        <p class="muted" style="margin:0;">No payouts in this view yet.</p>
    </div>
<?php else: ?>

<div class="card" style="padding:0;overflow:auto;">
    <table class="po-tbl">
        <thead>
            <tr>
                <th>Date</th>
                <th>Notes</th>
                <th class="r">Payout</th>
                <th class="r">Fee</th>
                <th class="r">Total deducted</th>
                <th>Status</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($payouts as $p):
            $payout = (int)$p['payout_amount_cents'];
            $fee    = (int)$p['fee_cents'];
            $total  = $payout + $fee;
        ?>
            <tr>
                <td style="font-size:.85rem;white-space:nowrap;">
                    <?= htmlspecialchars(date('j M Y', strtotime($p['payout_date']))) ?>
                </td>
                <td style="font-size:.85rem;">
                    <?= htmlspecialchars($p['notes'] ?? '') ?>
                    <?php if ($p['status'] === 'error' && !empty($p['sync_error'])): ?>
                        <div class="err-msg"><?= htmlspecialchars(mb_substr($p['sync_error'], 0, 200)) ?></div>
                    <?php endif; ?>
                </td>
                <td class="r"><?= rand_fmt($payout) ?></td>
                <td class="r" style="color:#991b1b;">
                    <?= $fee > 0 ? '−'.rand_fmt($fee) : '<span class="muted">—</span>' ?>
                </td>
                <td class="r" style="font-weight:600;"><?= rand_fmt($total) ?></td>
                <td><?= payout_status_pill($p['status']) ?></td>
                <td style="text-align:right;white-space:nowrap;">
                    <?php if ($p['status'] === 'created'): ?>
                        <form method="post" style="display:inline;"
                              onsubmit="return confirm('Mark this payout as received in your bank account?\n\nThis only updates the local status — it does NOT touch Zoho.');">
                            <?= csrf_field() ?>
                            <input type="hidden" name="action" value="mark_received">
                            <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                            <button type="submit" class="linkbtn">✓ Mark received</button>
                        </form>
                    <?php elseif ($p['status'] === 'error'): ?>
                        <form method="post" style="display:inline;">
                            <?= csrf_field() ?>
                            <input type="hidden" name="action" value="retry">
                            <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                            <button type="submit" class="linkbtn">↻ Retry</button>
                        </form>
                        &nbsp;·&nbsp;
                        <form method="post" style="display:inline;"
                              onsubmit="return confirm('Delete this errored payout? Only safe if Zoho never received it.');">
                            <?= csrf_field() ?>
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                            <button type="submit" class="linkbtn danger">✕ Delete</button>
                        </form>
                    <?php elseif ($p['status'] === 'matched' && !empty($p['matched_at'])): ?>
                        <span class="muted" style="font-size:.78rem;">
                            <?= htmlspecialchars(date('j M', strtotime($p['matched_at']))) ?>
                        </span>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php endif; ?>

</div></section>

<?php require __DIR__ . '/_footer.php'; ?>