<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Models\{KycDocument,Merchant};
use App\Support\ApiResponse;
use Illuminate\Http\Request;
final class OperatorKycController extends Controller {
 public function index(Request $r){$q=KycDocument::with('merchant')->latest('id');if($r->filled('status'))$q->where('status',$r->string('status'));if($r->filled('merchant_id'))$q->whereHas('merchant',fn($m)=>$m->where('public_id',$r->string('merchant_id'))->orWhere('id',$r->input('merchant_id')));$page=$q->paginate(min(max($r->integer('per_page',20),1),100));return ApiResponse::success(collect($page->items())->map(fn($d)=>$this->resource($d))->values(),200,['pagination'=>['page'=>$page->currentPage(),'per_page'=>$page->perPage(),'total'=>$page->total(),'last_page'=>$page->lastPage()]]);}
 public function approve(Request $r,string $id){$doc=KycDocument::where('public_id',$id)->first();if(!$doc)return ApiResponse::error('KYC_DOCUMENT_NOT_FOUND','The requested KYC document does not exist.',404);$doc->update(['status'=>'approved','reviewed_by'=>$r->user()->id,'reviewed_at'=>now(),'rejection_reason'=>null]);Merchant::where('id',$doc->merchant_id)->update(['kyc_status'=>'approved','kyc_reviewed_at'=>now()]);return ApiResponse::success($this->resource($doc->fresh('merchant')));}
 public function reject(Request $r,string $id){$data=$r->validate(['reason'=>['required','string','max:1000']]);$doc=KycDocument::where('public_id',$id)->first();if(!$doc)return ApiResponse::error('KYC_DOCUMENT_NOT_FOUND','The requested KYC document does not exist.',404);$doc->update(['status'=>'rejected','reviewed_by'=>$r->user()->id,'reviewed_at'=>now(),'rejection_reason'=>$data['reason']]);Merchant::where('id',$doc->merchant_id)->update(['kyc_status'=>'rejected','kyc_reviewed_at'=>now()]);return ApiResponse::success($this->resource($doc->fresh('merchant')));}
 private function resource(KycDocument $d):array{return ['id'=>$d->public_id,'merchant'=>['id'=>$d->merchant?->public_id,'email'=>$d->merchant?->email,'name'=>$d->merchant?->name],'type'=>$d->type,'status'=>$d->status,'original_filename'=>$d->original_filename,'mime_type'=>$d->mime_type,'size_bytes'=>(int)$d->size_bytes,'rejection_reason'=>$d->rejection_reason,'submitted_at'=>$d->created_at?->utc()->toIso8601String(),'reviewed_at'=>$d->reviewed_at?->utc()->toIso8601String()];}
}