<?php

declare(strict_types=1);

require_once __DIR__ . '/../app/config/bootstrap.php';
require_once __DIR__ . '/../app/models/Order.php';
require_once __DIR__ . '/../app/services/PaymentService.php';
require_once __DIR__ . '/../app/services/OrderService.php';
require_once __DIR__ . '/../app/services/CartService.php';
require_once __DIR__ . '/../app/core/PublicLayout.php';

$authority = trim((string)($_GET['Authority'] ?? ''));
$status = trim((string)($_GET['Status'] ?? ''));
$message = 'پرداخت تایید نشد.';
$success = false;
$order = null;

if ($authority !== '') {
    $order = (new Order())->findByAuthority($authority);
    if ($order && $status === 'OK') {
        $verify = (new PaymentService())->verify($authority, (float)$order['total_amount']);
        if (!empty($verify['success'])) {
            (new OrderService())->markPaid((int)$order['id'], (string)$verify['ref_id'], $authority);
            (new CartService())->clear();
            $success = true;
            $message = 'پرداخت با موفقیت تایید شد.';
        } else {
            (new OrderService())->markFailed((int)$order['id'], $verify['message'] ?? 'verify_failed', $authority);
            $message = $verify['message'] ?? 'تایید پرداخت ناموفق بود.';
        }
    } elseif ($order) {
        (new OrderService())->markFailed((int)$order['id'], 'cancelled_by_user', $authority);
        $message = 'پرداخت توسط کاربر لغو شد.';
    }
}
?>
<?php renderPublicShellStart('نتیجه پرداخت', 'payment'); ?>
<div class="container section">
    <h1>نتیجه پرداخت</h1>
    <p><?= htmlspecialchars($message) ?></p>
    <?php if ($order): ?>
        <p>شماره سفارش: <?= (int)$order['id'] ?></p>
        <?php if (!empty($order['order_tracking_id'])): ?>
            <p>شناسه پیگیری سفارش: <code><?= htmlspecialchars((string)$order['order_tracking_id']) ?></code></p>
        <?php endif; ?>
    <?php endif; ?>
    <?php if ($success && $order): ?>
        <?php
        $trackQs = 'phone=' . rawurlencode((string)$order['customer_phone']);
        if (!empty($order['order_tracking_id'])) {
            $trackQs = 'order_tracking_id=' . rawurlencode((string)$order['order_tracking_id']) . '&' . $trackQs;
        } else {
            $trackQs = 'id=' . (int)$order['id'] . '&' . $trackQs;
        }
        ?>
        <a class="btn btn-primary" href="<?= htmlspecialchars(appPath('/public/order-tracking.php')) ?>?<?= $trackQs ?>">پیگیری سفارش</a>
    <?php else: ?>
        <a class="btn btn-secondary" href="<?= htmlspecialchars(appPath('/public/checkout.php')) ?>">تلاش مجدد</a>
    <?php endif; ?>
</div>
<?php renderPublicShellEnd('payment'); ?>
<?php Performance::finish('public.payment-callback'); ?>