<?php
// ============================================================
//  Checkout: one-off payment for branding cart
// ============================================================
//
//  Flow:
//    1. Member clicks "Pay now" on cart.php
//    2. We create/find an invoice for the cart
//    3. We build the PayFast fields and redirect
//    4. PayFast calls payfast-itn.php async on success
//    5. Member lands at payment-return.php (sync thank-you)
//
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/payfast.php';

auth_require_login();
$member = auth_user();

// Find the cart
$cart = db_row(
    'SELECT * FROM orders WHERE member_id = :m AND status IN ("cart","pending_payment") LIMIT 1',
    ['m' => $member['id']]
);
if (!$cart || (int)$cart['total_cents'] <= 0) {
    header('Location: cart.php?error=empty'); exit;
}

// Find or create the invoice for this order
$invoice = db_row('SELECT * FROM invoices WHERE order_id = :o LIMIT 1', ['o' => $cart['id']]);
if (!$invoice) {
    $number = 'ORD-' . date('Y') . '-' . str_pad((string)$cart['id'], 4, '0', STR_PAD_LEFT);
    $inv_id = db_insert('invoices', [
        'member_id'    => $member['id'],
        'type'         => 'order',
        'order_id'     => $cart['id'],
        'number'       => $number,
        'description'  => 'Buy Local branding order',
        'amount_cents' => (int)$cart['total_cents'],
        'status'       => 'unpaid',
        'issued_at'    => date('Y-m-d'),
        'due_at'       => date('Y-m-d', strtotime('+14 days')),
    ]);
    // Record the charge in the ledger
    db_insert('transactions', [
        'member_id'    => $member['id'],
        'invoice_id'   => $inv_id,
        'type'         => 'charge',
        'amount_cents' => (int)$cart['total_cents'],
        'description'  => 'Branding order ' . $number,
    ]);
    $invoice = db_row('SELECT * FROM invoices WHERE id = :id', ['id' => $inv_id]);
}

db_exec('UPDATE orders SET status = "pending_payment" WHERE id = :id', ['id' => $cart['id']]);

// Build the PayFast payment fields
$fields = pf_build_payment_fields([
    'm_payment_id'  => $invoice['number'],
    'amount'        => pf_cents_to_amount((int)$invoice['amount_cents']),
    'item_name'     => 'Buy Local order ' . $invoice['number'],
    'item_description' => $invoice['description'],
    'email_address' => $member['email'],
    'name_first'    => $member['first_name'],
    'name_last'     => $member['last_name'],
    'custom_str1'   => 'invoice:' . $invoice['id'],
    'custom_str2'   => 'member:'  . $member['id'],
    'custom_str3'   => 'type:order',
]);

$action = pf_process_url();
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Redirecting to PayFast&hellip;</title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
<section class="section">
    <div class="container" style="max-width:520px;text-align:center;">
        <h1>Redirecting to PayFast&hellip;</h1>
        <p class="muted">Please wait. If you're not redirected in a moment, click the button below.</p>

        <form id="pf-form" method="post" action="<?= htmlspecialchars($action) ?>">
            <?php foreach ($fields as $k => $v): ?>
                <input type="hidden" name="<?= htmlspecialchars($k) ?>" value="<?= htmlspecialchars((string)$v) ?>">
            <?php endforeach; ?>
            <button type="submit" class="btn mt-3">Continue to PayFast &rarr;</button>
        </form>

        <p class="muted mt-3" style="font-size:.85rem;">
            Invoice <code><?= htmlspecialchars($invoice['number']) ?></code> &middot;
            Total R <?= number_format($invoice['amount_cents']/100, 2, '.', ' ') ?>
        </p>
    </div>
</section>

<script>
    // Auto-submit after 300ms to give the user a chance to see the loading screen
    setTimeout(function () { document.getElementById('pf-form').submit(); }, 300);
</script>
</body>
</html>
