<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\PaymentTransactionLog;
use Illuminate\Http\Request;

class PaymentTransactionController extends Controller
{
    public function index(Request $request)
    {
        $this->authorize('admin_sales_list');

        $query = PaymentTransactionLog::query()->with(['user:id,full_name,email', 'order:id,status,total_amount,currency']);

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

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

        if ($request->filled('order_id')) {
            $query->where('order_id', (int) $request->get('order_id'));
        }

        if ($request->filled('user_id')) {
            $query->where('user_id', (int) $request->get('user_id'));
        }

        $logs = $query->orderBy('created_at', 'desc')->paginate(20);

        $failedOrders = Order::where('status', Order::$fail)
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->with('user:id,full_name,email')
            ->get();

        $data = [
            'pageTitle' => trans('admin/main.payment_transactions_title'),
            'logs' => $logs,
            'failedOrders' => $failedOrders,
            'filters' => $request->all(),
        ];

        return view('admin.financial.payment_transactions.index', $data);
    }

    public function show($id)
    {
        $this->authorize('admin_sales_list');

        $log = PaymentTransactionLog::with(['user', 'order'])->findOrFail($id);

        $data = [
            'pageTitle' => trans('admin/main.payment_transaction_detail'),
            'log' => $log,
        ];

        return view('admin.financial.payment_transactions.show', $data);
    }
}
