<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\BaseController;
use App\Models\Transaction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminTransactionController extends BaseController
{
    public function index(Request $request): JsonResponse
    {
        $query = Transaction::with('user');

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

        if ($type = $request->get('type')) {
            $query->where('type', $type);
        }

        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('reference', 'like', "%{$search}%")
                  ->orWhere('customer_number', 'like', "%{$search}%")
                  ->orWhere('provider_reference', 'like', "%{$search}%");
            });
        }

        if ($dateFrom = $request->get('from')) {
            $query->whereDate('created_at', '>=', $dateFrom);
        }

        if ($dateTo = $request->get('to')) {
            $query->whereDate('created_at', '<=', $dateTo);
        }

        $transactions = $query->orderBy('created_at', 'desc')
            ->paginate($request->get('per_page', 20));

        return $this->paginatedResponse($transactions);
    }

    public function show(Transaction $transaction): JsonResponse
    {
        $transaction->load(['user', 'billService', 'billVariation', 'providerTransaction']);
        return $this->successResponse($transaction);
    }

    public function refund(Request $request, Transaction $transaction): JsonResponse
    {
        $validated = $request->validate([
            'reason' => ['required', 'string', 'max:500'],
        ]);

        app(\App\Modules\Transactions\Interfaces\TransactionServiceInterface::class)
            ->refundTransaction($transaction->reference, $validated['reason']);

        return $this->successResponse(null, 'Transaction refunded successfully');
    }
}
