<?php

declare(strict_types=1);

namespace App\Http\Controllers\Wallet;

use App\Http\Controllers\Controller;
use App\Http\Requests\Concerns\NormalizesBooleanQueryParams;
use App\Http\Resources\WalletTransactionResource;
use App\Models\WalletTransaction;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class WalletTransactionController extends Controller
{
    use NormalizesBooleanQueryParams;

    public function index(Request $request)
    {
        Gate::authorize('viewAny', WalletTransaction::class);

        if ($request->has('noPaginate')) {
            $request->merge([
                'noPaginate' => filter_var($request->input('noPaginate'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? false,
            ]);
        }

        $query = WalletTransaction::query()
            ->with(['project', 'invoice', 'payment'])
            ->where('user_id', $request->user()->id);

        if ($request->filled('type')) {
            $types = is_array($request->input('type'))
                ? $request->input('type')
                : explode(',', (string) $request->string('type'));
            $query->whereIn('type', array_filter(array_map('trim', $types)));
        }

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

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

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

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

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

        $query->latest();

        $perPage = min($request->integer('per_page', 15), 50);

        return WalletTransactionResource::collection(
            $request->boolean('noPaginate') ? $query->get() : $query->paginate($perPage)
        );
    }

    public function show(Request $request, WalletTransaction $walletTransaction)
    {
        Gate::authorize('view', $walletTransaction);

        if ($walletTransaction->user_id !== $request->user()->id && ! $request->user()->hasRole('admin')) {
            return ApiResponse::forbidden('دسترسی مجاز نیست.');
        }

        return new WalletTransactionResource(
            $walletTransaction->load(['project', 'invoice', 'payment'])
        );
    }
}
