<?php

namespace Modules\KYC\App\Http\Controllers\API;

use Exception;
use App\Helper\EmailHelper;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

use Illuminate\Support\Facades\Log;
use Modules\KYC\App\Models\KycType;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Modules\KYC\App\Models\KycInformation;
use Session, Auth, Image, File, Str, Mail;
use Modules\KYC\App\Emails\KycVerificationEmail;


class KycController extends Controller
{
    public function kyc()
    {

        $user = Auth::guard('api')->user();

        $kyc = KycInformation::where(['user_id' => $user->id])->first();
        $kycType = KycType::orderBy('id', 'desc')->get();

        return response()->json(['kyc' => $kyc, 'kycType' => $kycType]);
    }

    public function kycSubmit(Request $request)
    {
        $user = Auth::guard('api')->user();

        $kyc = KycInformation::where(['user_id' => $user->id])->first();

        if ($kyc) {
            $notify_message = trans('KYC already submited');
            return response()->json([
                'message' => $notify_message
            ], 403);
        }

        $rules = [
            'kyc_id' => 'required',
            'file' => 'required',
        ];
        $customMessages = [
            'kyc_id.required' => trans('translate.Type of is required'),
            'file' => trans('translate.File is required'),
        ];

        $request->validate($rules, $customMessages);

        $kyc = new KycInformation();

        if ($request->file) {
            $file_path = uploadPublicFile($request->file, 'uploads/custom-images');
            $kyc->file = $file_path;
        }

        $kyc->kyc_id = $request->kyc_id;
        $kyc->user_id = $user->id;
        $kyc->message = $request->message;
        $kyc->status = 0;
        $kyc->save();

        $notify_message = trans('translate.Information Submited Successfully. Pls Wait for Conformation');
        EmailHelper::mail_setup();

        $subject = trans('translate.KYC Verifaction');
        $message = 'Name: ' . $user->name . '<br>' . $notify_message;

        try {
            Mail::to($user->email)->send(new KycVerificationEmail($message, $subject));
        } catch (Exception $ex) {
            Log::info($ex->getMessage());
        }


        return response()->json([
            'message' => $notify_message
        ]);
    }
}
