<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\ClientKYCDoc;
use App\Models\ClientKYCDocTemplate;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class ClientKYCDocTemplateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $lists = ClientKYCDocTemplate::orderBy('name', 'asc')->get();
        $history = [];

        return view('setup-client-kyc-docs', compact('lists', 'history'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return view('libs.add-client-kyc-docs');
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function getKYCDOcsForm($type)
    {
        $lists = [];
        if(ClientKYCDocTemplate::where('status',1)->where('client_type', $type)->first()){
            $lists = ClientKYCDocTemplate::where('client_type', $type)->where('status',1)->orderBy('name', 'asc')->get();
        }

        return view('libs.client-kyc-docs', compact('lists'));
    }


    /**
     */
    public function uploadDocuments($type,Request $request)
    {
        $required_docs = ClientKYCDocTemplate::where('client_type', $type)->where('status', 1)->orderBy('name','asc')->get();
        $required_no = count($required_docs);
        $docNames =  [];

        foreach ($required_docs as $doc){
            $allowedfileExtension=['pdf','jpg','png', 'jpeg'];
            //$allowedfileExtension=['doc'];
            if($request[$doc->name_title] == "" && !$request->hasFile($doc->title)){
                $docNames[] = 'empty name and file';
            }elseif($request[$doc->name_title] == ""){
                $docNames[] = 'empty name';
            }elseif (!$request->hasFile($doc->title)){
                $docNames[] = 'missing file';
            }elseif(!in_array(strtolower($request->file($doc->title)->getClientOriginalExtension()), $allowedfileExtension)){
                $docNames[] = 'wrong file format';
            }
            else{
                $docNames[] = $request[$doc->name_title];
            }
        }
        if(in_array('empty name', $docNames)){
            $res = 'missing doc name';
        }elseif(in_array('empty name and file', $docNames)){
            $res = 'name and file missing';
        }elseif(in_array('missing file', $docNames)){
            $res = 'File Missing';
        }elseif(in_array('wrong file format', $docNames)){
            $res = 'Wrong file format';
        }else{
            $results = [];
            $randomStamp = new RandomNumbersController;
            $stamp = $randomStamp->getRandomNumbers(5);
            if(!ClientKYCDoc::firstWhere('c_id', $stamp)){
                foreach ($required_docs as $doc){
                    $filepath = $request->file($doc->title);
                    $name = $request[$doc->name_title];
                    $filename = $name."_".time().$filepath->getClientOriginalName();

                    //store the file now
                    $path = $filepath->storeAs('public/docs/clients/kyc', $filename, 'local');
                    if($path){
                        $init = new ClientKYCDoc;

                        $init->c_id = $stamp;
                        $init->doc_id = $doc->id;
                        $init->filename = $name;
                        $init->path = $path;
                        $init->status = '0';
                        $init->created_by = auth()->user()->id;
                        if($init->save()){
                            $results[] = 'success';
                        }else{
                            $results[] = 'error';
                        }
                    }
                }
                if(in_array('error', $results)){
                    $res = 'error';
                }else{
                    $res = $stamp;
                }
            }else{
                $res = 'stamp error';
            }
        }
        return  $res;
    }

    /**Store Item**/
    public function store(Request $request):string
    {
        $last_record = ClientKYCDocTemplate::orderBy('name_title', 'desc')->first();
        $type = $request['client-type'];
        $name = $request['name'];
        $details = $request['details'];

        $res = 'empty type';
        if(!empty($type)){
            $res = 'empty fields';
            if(!empty($name)){
                $res = 'exist';
                if(!ClientKYCDocTemplate::where('name', $name)->first()){
                    $init = new ClientKYCDocTemplate;
                    $last_doc_title_no = $last_name_title_no = 0;
                    if($last_record){
                        $last_doc_title_no = substr($last_record->title, -1);
                        $last_name_title_no = substr($last_record->name_title, -1);
                    }
                    $new_doc_no = $last_doc_title_no + 1;
                    $new_nm_no = $last_name_title_no + 1;

                    $new_no_title = 'doc'.$new_doc_no;
                    $new_nm_title = 'name'.$new_nm_no;

                    $init->client_type = $type;
                    $init->name = $name;
                    $init->name_title = $new_nm_title;
                    $init->title = $new_no_title;
                    $init->details = $details;
                    $init->created_by = auth()->user()->id;
                    if($init->save()){
                        $res = 'success';
                    }else{
                        $res = 'error';
                    }
                }
            }
        }
        return $res;
    }

    /**Show a Section to Upload Client Files**/
    public function showUploadClientFiles($id){
        $client = Client::where('c_id', $id)->first();

        return view('libs.upload-client-files', compact('client'));
    }

    /**Store the Uploaded Files**/
    public function storeUploadClientFiles($id, Request $request){
        $uploadType = $request['upload-type'];
        $res = 'empty';
        if(!empty($uploadType)){
            /**Upload Local Files**/
            if($uploadType == 'local'){

                /**Upload File 1**/
                if($request->hasFile('upload-doc-one')){
                    $res = 'empty name one';
                    if(!empty($request['file-name-one'])){
                        $filepathOne = $request->file('upload-doc-one');
                        $nameOne = $request['file-name-one'];
                        $fileExtension = $filepathOne->getClientOriginalExtension();
                        $filenameOne = $nameOne."_".time().".".$fileExtension;

                        /**By Default - We define the Destination Path **/
                        $destinationPath = 'uploads/docs/clients/kyc';
                        //store the file now
                        $pathOne = $request['upload-doc-one']->move(public_path($destinationPath), $filenameOne);
                        $res = 'error uploading';
                        if($pathOne){
                            /**Store the Info into the Documents table **/
                            $res = 'error';
                            if(ClientKYCDoc::create([
                                'c_id' => $id,
                                'filename' => $nameOne,
                                'path' => $destinationPath."/".$filenameOne,
                                'status' => 0,
                                'created_by' => auth()->user()->id,
                            ])){
                                $res = 'success';
                            }
                        }
                    }
                }
                /**Upload File 2**/
                if($request->hasFile('upload-doc-two')){
                    $res = 'empty name two';
                    if(!empty($request['file-name-two'])){
                        $filepathTwo = $request->file('upload-doc-two');
                        $nameTwo = $request['file-name-two'];
                        $fileExtension = $filepathTwo->getClientOriginalExtension();
                        $filenameTwo = $nameTwo."_".time().".".$fileExtension;

                        /**By Default - We define the Destination Path **/
                        $destinationPath = 'uploads/docs/clients/kyc';
                        //store the file now
                        $pathTwo = $request['upload-doc-two']->move(public_path($destinationPath), $filenameTwo);
                        $res = 'error uploading';
                        if($pathTwo){
                            /**Store the Info into the Documents table **/
                            $res = 'error';
                            if(ClientKYCDoc::create([
                                'c_id' => $id,
                                'filename' => $nameTwo,
                                'path' => $destinationPath."/".$filenameTwo,
                                'status' => 0,
                                'created_by' => auth()->user()->id,
                            ])){
                                $res = 'success';
                            }
                        }
                    }
                }


                /**Upload File 3**/
                if($request->hasFile('upload-doc-three')){
                    $res = 'empty name three';
                    if(!empty($request['file-name-three'])){
                        $filepathThree = $request->file('upload-doc-three');
                        $nameThree = $request['file-name-three'];
                        $fileExtension = $filepathThree->getClientOriginalExtension();
                        $filenameThree = $nameThree."_".time().".".$fileExtension;

                        /**By Default - We define the Destination Path **/
                        $destinationPath = 'uploads/docs/clients/kyc';
                        //store the file now
                        $pathThree = $request['upload-doc-three']->move(public_path($destinationPath), $filenameThree);
                        $res = 'error uploading';
                        if($pathThree){
                            /**Store the Info into the Documents table **/
                            $res = 'error';
                            if(ClientKYCDoc::create([
                                'c_id' => $id,
                                'filename' => $nameThree,
                                'path' => $destinationPath."/".$filenameThree,
                                'status' => 0,
                                'created_by' => auth()->user()->id,
                            ])){
                                $res = 'success';
                            }
                        }
                    }
                }

                /**Upload File 4**/
                if($request->hasFile('upload-doc-four')){
                    $res = 'empty name four';
                    if(!empty($request['file-name-four'])){
                        $filepathFour = $request->file('upload-doc-four');
                        $nameFour = $request['file-name-four'];
                        $fileExtension = $filepathFour->getClientOriginalExtension();
                        $filenameFour = $nameFour."_".time().".".$fileExtension;

                        /**By Default - We define the Destination Path **/
                        $destinationPath = 'uploads/docs/clients/kyc';
                        //store the file now
                        $pathFour = $request['upload-doc-four']->move(public_path($destinationPath), $filenameFour);
                        $res = 'error uploading';
                        if($pathFour){
                            /**Store the Info into the Documents table **/
                            $res = 'error';
                            if(ClientKYCDoc::create([
                                'c_id' => $id,
                                'filename' => $nameFour,
                                'path' => $destinationPath."/".$filenameFour,
                                'status' => 0,
                                'created_by' => auth()->user()->id,
                            ])){
                                $res = 'success';
                            }
                        }
                    }
                }

                /**Upload File 5**/
                if($request->hasFile('upload-doc-five')){
                    $res = 'empty name five';
                    if(!empty($request['file-name-five'])){
                        $filepathFive = $request->file('upload-doc-five');
                        $nameFive = $request['file-name-five'];
                        $fileExtension = $filepathFive->getClientOriginalExtension();
                        $filenameFive = $nameFive."_".time().".".$fileExtension;

                        /**By Default - We define the Destination Path **/
                        $destinationPath = 'uploads/docs/clients/kyc';
                        //store the file now
                        $pathFive = $request['upload-doc-five']->move(public_path($destinationPath), $filenameFive);
                        $res = 'error uploading';
                        if($pathFive){
                            /**Store the Info into the Documents table **/
                            $res = 'error';
                            if(ClientKYCDoc::create([
                                'c_id' => $id,
                                'filename' => $nameFive,
                                'path' => $destinationPath."/".$filenameFive,
                                'status' => 0,
                                'created_by' => auth()->user()->id,
                            ])){
                                $res = 'success';
                            }
                        }
                    }
                }
            }
        }
        return $res;
    }
}
