<?php

/**
 * [FIX] Root cause of "بعضی سفارش‌ها ثبت نمیشه، نه خطایی به کاربر میره نه به ادمین":
 *
 * payment/zarinpal.php, payment/iranpay1.php, payment/tronado.php and payment/aqayepardakht.php
 * all mark Payment_report.payment_Status = 'paid' and then call DirectPayment($order_id) directly,
 * with NO try/catch around it and no register_shutdown_function safety net (unlike nowpayment.php,
 * which already has both). DirectPayment() does a lot of work — panel API calls, DB writes, building
 * the delivery message — and if anything inside it throws (a panel timeout that bubbles up as an
 * uncaught Throwable, a DB hiccup, a PHP8 TypeError from an unexpected null, etc.) the whole gateway
 * callback page dies right there:
 *
 *   - The customer just sees a blank/broken page instead of their service or a real error message.
 *   - Payment_status is ALREADY 'paid', so nothing will ever automatically retry this invoice again.
 *   - The invoice stays Status='unpaid' forever with no service ever created.
 *   - Nothing is sent to the admin Telegram channel, because there is no catch block to send it from.
 *
 * That is exactly the stuck "unpaid" order admins then find days later with no explanation, and the
 * only thing they can do with it from the panel is delete it.
 *
 * nm_safe_direct_payment() wraps the same call so that no matter what goes wrong inside
 * DirectPayment(), (1) the page always finishes cleanly, (2) the admin channel always gets a message
 * with the order id and the exact exception, and (3) the customer gets told support is on it instead
 * of silence.
 */
if (!function_exists('nm_safe_direct_payment')) {
    function nm_safe_direct_payment(string $orderId, ?string $imagePath = null): bool
    {
        try {
            if ($imagePath !== null) {
                DirectPayment($orderId, $imagePath);
            } else {
                DirectPayment($orderId);
            }
            return true;
        } catch (Throwable $e) {
            @error_log('[nm_safe_direct_payment] DirectPayment threw for order ' . $orderId . ': ' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine());

            try {
                $setting = function_exists('select') ? select('setting', '*', null, null, 'select') : [];
                $channel = is_array($setting) ? (string)($setting['Channel_Report'] ?? '') : '';
                $errorTopic = function_exists('select')
                    ? (select('topicid', 'idreport', 'report', 'errorreport', 'select')['idreport'] ?? null)
                    : null;

                if ($channel !== '' && function_exists('telegram')) {
                    $text = "⭕️ <b>خطا در تحویل خودکار سرویس بعد از پرداخت</b>\n"
                          . "پرداخت با موفقیت ثبت شد اما هنگام ساخت/تحویل سرویس یک خطای پیش‌بینی‌نشده رخ داد و پردازش متوقف شد. این سفارش نیاز به بررسی دستی دارد.\n\n"
                          . "🛒 کد سفارش: <code>" . htmlspecialchars($orderId, ENT_QUOTES, 'UTF-8') . "</code>\n"
                          . "✍️ خطا: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . "\n"
                          . "📄 محل خطا: " . htmlspecialchars(basename($e->getFile()) . ':' . $e->getLine(), ENT_QUOTES, 'UTF-8');
                    telegram('sendmessage', array_filter([
                        'chat_id'           => $channel,
                        'message_thread_id' => $errorTopic,
                        'text'              => $text,
                        'parse_mode'        => 'HTML',
                    ]));
                }
            } catch (Throwable $e2) {
                @error_log('[nm_safe_direct_payment] also failed to notify admin channel: ' . $e2->getMessage());
            }

            try {
                $report = function_exists('select') ? select('Payment_report', '*', 'id_order', $orderId, 'select') : null;
                if (is_array($report) && !empty($report['id_user']) && function_exists('sendmessage')) {
                    sendmessage(
                        (string)$report['id_user'],
                        "⏳ کاربر عزیز پرداخت شما با موفقیت ثبت شد، اما در تحویل خودکار سرویس مشکلی پیش آمد. تیم پشتیبانی مطلع شد و به‌زودی سرویس شما را بررسی و تحویل می‌دهد.",
                        null,
                        'HTML'
                    );
                }
            } catch (Throwable $e3) {
                // fail-open — the admin report above is the important one
            }

            return false;
        }
    }
}
