<?php

declare(strict_types=1);
require_once __DIR__ . '/../app/controllers/ShopController.php';
require_once __DIR__ . '/../app/config/bootstrap.php';
require_once __DIR__ . '/../app/core/Csrf.php';
require_once __DIR__ . '/../app/core/DijikalaLayout.php';
require_once __DIR__ . '/../app/models/BankCard.php';

$controller = new ShopController();
$bankCards = [];
try {
    $bankCards = (new BankCard())->active();
} catch (Throwable $e) {
    $bankCards = [];
}
$error = null;
$summary = $controller->cartSummary();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Csrf::validate($_POST['_csrf'] ?? null)) {
        $error = 'توکن امنیتی معتبر نیست.';
    } else {
        $result = $controller->startCheckout([
            'customer_name' => trim((string)($_POST['customer_name'] ?? '')),
            'customer_phone' => trim((string)($_POST['customer_phone'] ?? '')),
            'customer_address' => trim((string)($_POST['customer_address'] ?? '')),
        ]);
        if (!empty($result['success'])) {
            header('Location: ' . $result['gateway_url']);
            exit;
        }
        $error = $result['message'] ?? 'ثبت سفارش انجام نشد.';
    }
}

renderDijikalaShellStart(APP_NAME . ' | تسویه حساب', ['noindex' => true], '');
?>

<article class="container" style="padding:1.5rem 0 3rem;">
    <h2>تسویه حساب</h2>
    <?php if ($error !== null): ?>
        <p style="color:#b91c1c;margin:12px 0;"><?= htmlspecialchars($error) ?></p>
    <?php endif; ?>
    <?php if (empty($summary['items'])): ?>
        <p>سبد خرید خالی است.</p>
        <a href="<?= htmlspecialchars(appPath('/public/products.php')) ?>" class="btn-login" style="text-decoration:none;display:inline-block;margin-top:12px;">فروشگاه</a>
    <?php else: ?>
        <div style="margin-bottom:16px;">
            <p>جمع کالاها: <?= number_format((float)$summary['totals']['subtotal']) ?> تومان</p>
            <p>هزینه ارسال: <?= number_format((float)$summary['totals']['shipping']) ?> تومان</p>
            <p><strong>مبلغ نهایی: <?= number_format((float)$summary['totals']['grand_total']) ?> تومان</strong></p>
        </div>
        <?php if ($bankCards): ?>
            <section class="bank-cards-checkout" style="margin:16px 0;padding:14px;border:1px solid #e5e7eb;border-radius:10px;background:#fafafa;">
                <h4>کارت‌به‌کارت</h4>
                <ul>
                    <?php foreach ($bankCards as $bc): ?>
                        <li>
                            <strong><?= htmlspecialchars((string)$bc['bank_name']) ?></strong>
                            — <?= htmlspecialchars((string)$bc['card_number_masked']) ?>
                            — <?= htmlspecialchars((string)$bc['card_holder']) ?>
                            <?php if (!empty($bc['iban'])): ?> — شبا: <?= htmlspecialchars((string)$bc['iban']) ?><?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </section>
        <?php endif; ?>
        <form method="post" class="c-form-account">
            <input type="hidden" name="_csrf" value="<?= htmlspecialchars(Csrf::token()) ?>">
            <div class="c-form-account__title">نام مشتری</div>
            <div class="c-form-account__row">
                <label class="c-ui-input c-ui-input--account-login">
                    <input class="c-ui-input__field c-ui-input__field--right-placeholder" name="customer_name" required placeholder="نام و نام خانوادگی">
                </label>
            </div>
            <div class="c-form-account__title">شماره تماس</div>
            <div class="c-form-account__row">
                <label class="c-ui-input c-ui-input--account-login">
                    <input class="c-ui-input__field c-ui-input__field--right-placeholder" name="customer_phone" required placeholder="09...">
                </label>
            </div>
            <div class="c-form-account__title">آدرس</div>
            <div class="c-form-account__row">
                <label class="c-ui-input c-ui-input--account-login">
                    <textarea class="c-ui-input__field" name="customer_address" required rows="3" placeholder="آدرس کامل"></textarea>
                </label>
            </div>
            <div class="c-form-account__row c-form-account__row--submit">
                <button class="btn-login" type="submit">پرداخت با زرین‌پال</button>
            </div>
        </form>
    <?php endif; ?>
</article>

<?php
renderDijikalaShellEnd('checkout', 'minimal');
Performance::finish('public.checkout');
