<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Setting;
use App\Services\TorobPayService;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class TorobPayAdminController extends Controller
{
    public function orders(Request $request, TorobPayService $torobPay)
    {
        $query = Order::query()
            ->with(['user:id,first_name,last_name,mobile', 'transactions' => function ($q) {
                $q->where('gateway', 'torobpay')->latest('id');
            }])
            ->where('payment_method', 'torobpay');

        if ($request->filled('order_number')) {
            $query->where('order_number', 'like', '%' . trim($request->order_number) . '%');
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('mobile')) {
            $mobile = trim($request->mobile);
            $query->whereHas('user', fn ($q) => $q->where('mobile', 'like', "%{$mobile}%"));
        }

        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $orders = $query->latest('id')->paginate(20)->withQueryString();

        $lastUpdate = (int) Setting::get('torobpay_last_status_update', 0);
        $configured = $torobPay->isConfigured();

        // Auto-refresh verification for current page (throttled, like plugin batch on load)
        if ($configured && $orders->isNotEmpty() && (time() - $lastUpdate) >= 60) {
            $torobPay->refreshOrdersVerification($orders->getCollection());
            $lastUpdate = (int) Setting::get('torobpay_last_status_update', 0);
            $orders->getCollection()->load(['transactions' => function ($q) {
                $q->where('gateway', 'torobpay')->latest('id');
            }]);
        }

        $statuses = [
            'failed'   => 'در انتظار پرداخت',
            'paid'     => 'در انتظار ارسال',
            'sent'     => 'ارسال شده',
            'canceled' => 'لغو شده',
            'returned' => 'عودت شده',
        ];

        return view('admin.settings.torobpay-orders', compact(
            'orders', 'statuses', 'lastUpdate', 'configured'
        ));
    }

    public function refresh(Request $request, TorobPayService $torobPay)
    {
        $ids = array_filter(array_map('intval', (array) $request->input('order_ids', [])));

        $orders = Order::query()
            ->with('transactions')
            ->where('payment_method', 'torobpay')
            ->when($ids, fn ($q) => $q->whereIn('id', $ids))
            ->latest('id')
            ->limit($ids ? 100 : 50)
            ->get();

        $count = $torobPay->refreshOrdersVerification($orders);

        return back()->with('success', "وضعیت {$count} سفارش از ترب‌پی بروزرسانی شد.");
    }

    public function refund(Request $request, TorobPayService $torobPay)
    {
        $request->validate([
            'order_id'  => 'nullable|integer',
            'order_ids' => 'nullable|array',
            'order_ids.*' => 'integer',
        ]);

        $ids = $request->filled('order_id')
            ? [(int) $request->order_id]
            : array_map('intval', (array) $request->input('order_ids', []));

        if (empty($ids)) {
            return back()->with('error', 'سفارشی انتخاب نشده است.');
        }

        $orders = Order::query()
            ->with(['transactions', 'user'])
            ->where('payment_method', 'torobpay')
            ->whereIn('id', $ids)
            ->whereIn('status', ['paid', 'sent'])
            ->get();

        if ($orders->isEmpty()) {
            return back()->with('error', 'سفارش قابل عودتی یافت نشد (فقط سفارش‌های پرداخت‌شده/ارسال‌شده).');
        }

        $ok = 0;
        $fail = 0;
        $messages = [];

        foreach ($orders as $order) {
            $result = $torobPay->cancelPayment($order);
            if ($result['success'] ?? false) {
                $order->update(['status' => 'returned']);
                $ok++;
            } else {
                $fail++;
                $messages[] = $order->order_number . ': ' . ($result['message'] ?? 'خطا');
            }
        }

        if ($ok && !$fail) {
            return back()->with('success', "عودت {$ok} سفارش در ترب‌پی با موفقیت انجام شد.");
        }

        if ($ok && $fail) {
            return back()->with('error', "{$ok} موفق، {$fail} ناموفق. " . implode(' | ', $messages));
        }

        return back()->with('error', 'عودت ناموفق بود. ' . implode(' | ', $messages));
    }

    public function export(Request $request): StreamedResponse
    {
        $ids = array_filter(array_map('intval', (array) $request->input('order_ids', [])));

        $query = Order::query()
            ->with(['user:id,first_name,last_name,mobile', 'transactions' => function ($q) {
                $q->where('gateway', 'torobpay')->latest('id');
            }])
            ->where('payment_method', 'torobpay');

        if ($ids) {
            $query->whereIn('id', $ids);
        }

        $orders = $query->latest('id')->limit(5000)->get();

        $filename = 'torobpay-orders-' . now()->format('Y-m-d') . '.csv';

        return response()->streamDownload(function () use ($orders) {
            $out = fopen('php://output', 'w');
            fwrite($out, "\xEF\xBB\xBF");
            fputcsv($out, [
                'شماره سفارش',
                'تاریخ',
                'شماره موبایل',
                'نام مشتری',
                'وضعیت سفارش',
                'وضعیت تراکنش در ترب‌پی',
                'مبلغ (تومان)',
            ]);

            foreach ($orders as $order) {
                $tx = $order->transactions->first();
                $gw = is_array($tx?->gateway_response) ? $tx->gateway_response : [];
                $status = $gw['torobpay_verification_status'] ?? null;
                $apiTx  = $gw['torobpay_api_transaction_id'] ?? $tx?->track_id;

                fputcsv($out, [
                    $order->order_number,
                    optional($order->paid_at ?? $order->created_at)->format('Y-m-d H:i'),
                    $order->user?->mobile ?? '',
                    trim(($order->user?->first_name ?? '') . ' ' . ($order->user?->last_name ?? '')),
                    $order->statusLabel(),
                    TorobPayService::verificationStatusLabel($status, $apiTx),
                    $order->payable_amount,
                ]);
            }

            fclose($out);
        }, $filename, [
            'Content-Type' => 'text/csv; charset=UTF-8',
        ]);
    }

    public function support()
    {
        return view('admin.settings.torobpay-support', [
            'ordersUrl' => route('admin.settings.torobpay.orders'),
            'settingsUrl' => route('admin.settings.torobpay'),
        ]);
    }
}
