<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\KycDocument;
use App\Models\Setting;
use Illuminate\Http\Request;

class KycController extends Controller
{
    public function status(Request $request)
    {
        $user = $request->user();
        $documents = KycDocument::where('user_id', $user->id)->latest()->get();

        return response()->json([
            'kyc_status' => $user->kyc_status ?? 'not_submitted',
            'kyc_approved_at' => $user->kyc_approved_at,
            'documents' => $documents->map(fn($d) => [
                'id' => $d->id,
                'type' => $d->type,
                'type_label' => $d->getTypeLabel(),
                'status' => $d->status,
                'rejection_reason' => $d->rejection_reason,
                'submitted_at' => $d->created_at,
                'verified_at' => $d->verified_at,
            ]),
            'required_for_withdrawal' => Setting::get('kyc_required_for_withdrawal', true),
            'required_above' => Setting::get('kyc_required_above_amount', 2000),
        ]);
    }

    public function upload(Request $request)
    {
        $maxMb = Setting::get('kyc_max_file_size_mb', 10);

        $data = $request->validate([
            'type' => ['required', 'in:passport,drivers_license,national_id,utility_bill,bank_statement,selfie'],
            'document' => ['required', 'file', 'mimes:jpg,jpeg,png,pdf', "max:{$maxMb}024"],
        ]);

        $user = $request->user();

        $path = $request->file('document')->store("kyc/{$user->id}", 'local');

        $doc = KycDocument::create([
            'user_id' => $user->id,
            'type' => $data['type'],
            'file_path' => $path,
            'original_name' => $request->file('document')->getClientOriginalName(),
            'status' => Setting::get('kyc_auto_approve', false) ? 'approved' : 'pending',
        ]);

        if (Setting::get('kyc_auto_approve', false)) {
            $user->update(['kyc_status' => 'approved', 'kyc_approved_at' => now()]);
        } else {
            $user->update(['kyc_status' => 'pending']);
        }

        AuditLog::record('kyc_upload', $user->id, "Player uploaded {$data['type']} document", ['document_id' => $doc->id, 'type' => $data['type']]);

        return response()->json(['message' => 'Document uploaded successfully.', 'document' => [
            'id' => $doc->id,
            'type' => $doc->type,
            'status' => $doc->status,
        ]], 201);
    }
}
