<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Services\DigiPayService;
use Illuminate\Http\Request;

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

        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}%"));
        }

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

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

        return view('admin.settings.digipay-orders', [
            'orders'     => $orders,
            'statuses'   => $statuses,
            'configured' => $digiPay->isConfigured(),
        ]);
    }

    public function refund(Request $request, DigiPayService $digiPay)
    {
        $request->validate([
            'order_id' => 'required|integer',
        ]);

        $order = Order::with('transactions')
            ->where('payment_method', 'digipay')
            ->findOrFail((int) $request->order_id);

        if (!in_array($order->status, ['paid', 'sent'], true)) {
            return back()->with('error', 'فقط سفارش‌های پرداخت‌شده قابل عودت هستند.');
        }

        $result = $digiPay->cancelPayment($order);
        if (!($result['success'] ?? false)) {
            return back()->with('error', $result['message'] ?? 'عودت ناموفق بود.');
        }

        $order->update(['status' => 'returned']);

        return back()->with('success', $result['message'] ?? 'عودت ثبت شد.');
    }

    public function support()
    {
        return view('admin.settings.digipay-support', [
            'ordersUrl'   => route('admin.settings.digipay.orders'),
            'settingsUrl' => route('admin.settings.digipay'),
            'callbackUrl' => url('/checkout/callback/digipay'),
            'docsUrl'     => 'https://www.mydigipay.com/developers/docs/upg/',
        ]);
    }
}
