<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\KYCVerification;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class KYCController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show KYC form
     */
    public function index()
    {
        $kyc = KYCVerification::where('user_id', Auth::id())->first();
        
        return view('user.kyc.index', compact('kyc'));
    }

    /**
     * Submit KYC
     */
    public function submit(Request $request)
    {
        $request->validate([
            'national_id' => 'required|string|max:20',
            'first_name' => 'required|string|max:100',
            'last_name' => 'required|string|max:100',
            'birth_date' => 'required|date',
            'id_card_front' => 'required|image|max:5120',
            'id_card_back' => 'required|image|max:5120',
            'selfie' => 'required|image|max:5120',
        ]);

        $user = Auth::user();

        // Check if already submitted
        $kyc = KYCVerification::where('user_id', $user->id)->first();
        
        if ($kyc && $kyc->status === 'approved') {
            return back()->with('error', 'احراز هویت شما قبلاً تأیید شده است');
        }

        // Upload images
        $idCardFront = $request->file('id_card_front')->store('kyc/id_cards', 'public');
        $idCardBack = $request->file('id_card_back')->store('kyc/id_cards', 'public');
        $selfie = $request->file('selfie')->store('kyc/selfies', 'public');

        // Create or update KYC
        KYCVerification::updateOrCreate(
            ['user_id' => $user->id],
            [
                'national_id' => $request->national_id,
                'first_name' => $request->first_name,
                'last_name' => $request->last_name,
                'birth_date' => $request->birth_date,
                'id_card_front' => $idCardFront,
                'id_card_back' => $idCardBack,
                'selfie' => $selfie,
                'status' => 'pending',
                'level' => 'basic',
            ]
        );

        return back()->with('success', 'مدارک شما با موفقیت ارسال شد و در انتظار تأیید است');
    }

    /**
     * Get KYC status
     */
    public function status()
    {
        $kyc = KYCVerification::where('user_id', Auth::id())->first();

        if (!$kyc) {
            return response()->json([
                'status' => false,
                'message' => 'احراز هویت انجام نشده'
            ]);
        }

        return response()->json([
            'status' => true,
            'data' => [
                'kyc_status' => $kyc->status,
                'level' => $kyc->level,
                'verified_at' => $kyc->verified_at,
            ]
        ]);
    }
}
