<?php
namespace App\Http\Controllers\Api\V1\Admin;use App\Http\Controllers\Controller;use App\Http\Resources\ExchangeRateResource;use App\Http\Requests\Admin\RateStoreRequest;use App\Models\ExchangeRate;use App\Services\AuditService;use Illuminate\Http\Request;
class RateController extends Controller {public function index(){return ExchangeRateResource::collection(ExchangeRate::query()->selectRaw('exchange_rates.*')->whereIn('id',function($q){$q->from('exchange_rates')->selectRaw('MAX(id)')->where('effective_from','<=',now())->groupBy('from_currency','to_currency');})->get());}public function store(RateStoreRequest $r,AuditService $a){$rate=ExchangeRate::create($r->validated()+['created_by'=>$r->user()->id,'created_at'=>now()]);$a->record('rate.created',$rate,[],$rate->toArray());return (new ExchangeRateResource($rate))->response()->setStatusCode(201);}public function history(Request $r){return ExchangeRateResource::collection(ExchangeRate::when($r->from_currency,fn($q,$v)=>$q->where('from_currency',$v))->when($r->to_currency,fn($q,$v)=>$q->where('to_currency',$v))->latest('effective_from')->paginate(min($r->integer('per_page',20),100)));}}
