<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/payments.php';

$tenantParam = tenant_param();
$_GET['tenant'] = $tenantParam;
$tenant = resolve_tenant_from_host();
if (!$tenant) {
    http_response_code(404);
    echo 'Shop not found.';
    exit;
}
$tenantId = (int) $tenant['id'];
$paymentId = (int) ($_GET['payment_id'] ?? 0);
$cancelled = isset($_GET['cancel']);
$sessionId = trim((string) ($_GET['session_id'] ?? ''));
$token = trim((string) ($_GET['token'] ?? ''));

$pay = null;
if ($paymentId > 0) {
    $stmt = db()->prepare('SELECT * FROM payments WHERE id = ? AND tenant_id = ?');
    $stmt->execute([$paymentId, $tenantId]);
    $pay = $stmt->fetch() ?: null;
}
if (!$pay && $sessionId !== '') {
    $pay = payment_find_by_external('stripe', $sessionId);
}
if (!$pay && $token !== '') {
    $pay = payment_find_by_external('paypal', $token);
}
if ($pay && (int) $pay['tenant_id'] !== $tenantId) {
    $pay = null;
}

if ($pay && !$cancelled && $pay['status'] !== 'paid' && $pay['provider'] !== 'manual') {
    $external = (string) ($pay['external_id'] ?: ($sessionId ?: $token));
    if ($external !== '') {
        try {
            $gw = payment_gateway($tenantId, (string) $pay['provider']);
            $status = $gw->fetchStatus($external);
            if (($status['status'] ?? '') === 'paid') {
                payment_mark_paid((int) $pay['id'], $status['external_id'] ?? $external, $status['raw'] ?? null);
                $pay['status'] = 'paid';
            }
        } catch (Throwable $e) {
            // webhook may still settle
        }
    }
}

// Reminders after booking deposit clears
if ($pay && ($pay['status'] ?? '') === 'paid' && ($pay['reference_type'] ?? '') === 'booking') {
    require_once dirname(__DIR__) . '/lib/reminders.php';
    reminder_schedule_for_booking((int) $pay['reference_id']);
}

$ok = $pay && $pay['status'] === 'paid';
$refType = $pay['reference_type'] ?? '';
$refId = (int) ($pay['reference_id'] ?? 0);

if ($refType === 'shop_order' && $refId > 0) {
    $dest = APP_BASE . '/checkout.php?tenant=' . urlencode($tenantParam) . '&done=' . $refId
        . ($ok ? '&paid=1' : ($cancelled ? '&pay_cancel=1' : '&pay_pending=1'));
} elseif ($refType === 'booking' && $refId > 0) {
    $dest = APP_BASE . '/?tenant=' . urlencode($tenantParam)
        . ($ok ? '&booked=1' : ($cancelled ? '&book_pay_cancel=1' : '&book_pay_pending=1'))
        . '#book';
} else {
    $dest = APP_BASE . '/?tenant=' . urlencode($tenantParam);
}
header('Location: ' . $dest);
exit;
