<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Util\CodeGeneratorService;
use App\Models\KycDetails;
use App\Models\Facilities;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class KycController extends Controller
{

    private $createdStatusCode = 201;
    private $successStatusCode = 200;
    private $errorStatusCode = 422;

    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function registerKyc(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'businessName' => 'required|string|max:255',
            'businessAddress' => 'required|string|max:255',
            'productName' => 'required|string|max:255',
            'otherBusinessName' => 'nullable|string',
            'website' => 'nullable|string',
            'facilities' => 'required|array',
            'coupon' => 'nullable|string'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()->all()], 422);
        }

        $userId = auth()->user()->id;
        $userObj = User::find((string)$userId);
        $facilityCount = count($request->facilities);
        if ($userObj->kyc_status == 1) {
            return response()->json(['data' => 'Kyc Already updated'], $this->errorStatusCode);
        } else {
            $couponList = ['LASWARCOREGOFF', 'LASWARCO100OFF', 'LASWARCOALLOFF'];
            if (in_array($request->coupon, $couponList)) {
                $code = CodeGeneratorService::generateRegisterV2();
                User::where('id', (string)$userId)->update([ 'registration_number' => $code]);
            } else {
                return  response()->json(['data' => 'Incorrect/Expired coupon'], $this->errorStatusCode);
            }
            $kycInfo = new KycDetails();
            $kycInfo->business_name = $request->businessName;
            $kycInfo->business_address = $request->businessAddress;
            $kycInfo->product_name = $request->productName;
            $kycInfo->other_business_name = $request->OtherBusinessName;
            $userObj->kycDetails()->save($kycInfo);
            for ($i = 0; $i < $facilityCount; $i++) {
                // var_dump($facilityCount);die();
                $facilityInfo = new Facilities();
                $facilityInfo->type = $request["facilities"][$i];
                $userObj->Facilities()->save($facilityInfo);
            }
            User::where('id', (string)$userId)->update(['kyc_status' => 1]);
            $kycresult = KycDetails::where('user_id', $userId)->first();
            return response()->json(['data' => $kycresult], $this->successStatusCode);
        }
    }
}
