<?php

namespace App\Http\Controllers;

use Auth;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Auth\Events\Registered;
use App\Models\Client as ClientMDL;
use App\Models\User;
use App\Models\Country;
use App\Models\Project;
use App\Models\ClientOTP;
use Twilio\Rest\Client;
use DateTime;
use Session;
use DateInterval;
use DB;
class ClientController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       $clients = ClientMDL::all();
        return view('dashboard.clients.index', compact('clients'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view("client_register");
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
     {
        
        $validator = Validator::make($request->all(), [

            
            'fname'     => 'required|string|max:200',
            'lname'     => 'string|max:100',
            'contact_number' => 'required|numeric|unique:users',
            'password' => 'required|min:6',
            'password_confirmation' => 'required|min:6|same:password',


        ]); // create the validations
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {

            return back()->withInput()->withErrors($validator);
            // validation failed redirect back to form
            if (request()->hasFile('filename')){
                request()->validate([
                    'filename' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
                ]);
            }
            if (request()->hasFile('imgname')){
                request()->validate([
                    'imgname' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
                ]);
            }
            if (request()->hasFile('imagename')){
                request()->validate([
                    'imagename' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
                ]);
            }

        } else {
            
            $is_valid_otp = 0; 
            $enterd_otp = $request->otp;
            $otp_response = ClientOTP::where([
                'mobile_no' => $request->contact_number,
                'otp_code' => $request->otp,
                'status' => 1,

            ])->get()->first();
            
             if(!empty($otp_response)){
                // check token expir time
                 if($otp_response->expired_at < date('Y-m-d H:i:s')){
                    
                    return redirect()->back()->with('otp_error', 'Your OTP has been expired. please generate again.');
                   
                 }else{
                             
                    $is_valid_otp = 1;
                   
                 }
                   
            }else{
                return redirect()->back()->with('otp_error', 'Invalid OTP');
                
            }
            if($is_valid_otp == 1){

                
                $Client = new ClientMDL;
                $Client->fname = $request->fname;
                $Client->lname = $request->lname;
                $Client->phone = $request->contact_number;
                $Client->email1 = $request->email;
                $Client->whatsapp_account = $request->whatsapp_no;
                $Client->website_url = $request->website_url;
                $Client->fax_number = $request->fax_number;
                $Client->save();

                $user = User::create([
                    'fname' => $request->fname,
                    'lname' => $request->lname,
                    'password' => bcrypt($request->password),
                    'email' => $request->contact_number,
                    'contact_number'=> $request->mobile_no,
                    'menuroles' => 'client',
                ]);

                $user->assignRole('client');
                 event(new Registered($user));

                if (auth()->attempt(array('email' => $request->contact_number, 'password' => $request->password),true)) {
                    return redirect("/client_dashboard")->with('success', 'You have successfully registered, Login to access your dashboard');
                }
            }else{
                return redirect()->back()->with('otp_error', 'Invalid OTP');
            }


        }
    }
     public function sendClientEmail(Request $request)
    {
        $mobile_no = $request->mobile_no;
        
        $characters = '123456789';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < 4; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        
        $otp=$randomString;
        // for testing purpose make it constant
        //$otp = '1122';
        
        $result = ClientOTP::where('mobile_no',$mobile_no)->first();
        $dt = new DateTime("now", new \DateTimeZone('Asia/Karachi'));
        $minutes_to_add = 15;
        $dt->add(new DateInterval('PT' . $minutes_to_add . 'M'));
        $expired_at =  $dt->format('Y-m-d, H:i:s');

        if(empty($result)){
            ClientOTP::create([
                'mobile_no' => $mobile_no,
                'otp_code' => $otp,
                'expired_at' => $expired_at,
            ]);
        }else{
            // udpate
            ClientOTP::where(['mobile_no' =>$mobile_no])->update([
                'otp_code' => $otp,
                'expired_at' => $expired_at,
            ]);
        }
        
        $number = "+".trim($mobile_no);
       
        $message = "Dear User, Your OTP is ".$otp.". Please don't share your OTP with others for own security.";
        
        $account_sid = getenv("TWILIO_SID");
        $auth_token = getenv("TWILIO_AUTH_TOKEN");
        $twilio_number = getenv("TWILIO_NUMBER");

        $client = new Client($account_sid, $auth_token);
        
        $response = $client->messages->create($number, array('from' => $twilio_number, 'body' => $message));
        
        return response()->json(["success"=> $response]);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\client  $client
     * @return \Illuminate\Http\Response
     */
    public function show(ClientMDL $client)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\client  $client
     * @return \Illuminate\Http\Response
     */
    public function edit(ClientMDL $client)
    {
        // return view('clients.edit', ['client' => $client]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\client  $client
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [

        'user_title' => 'string',   // required and email format validation
        'mname' =>'string', // required and number field validation
        'fname' => 'string',
        'lname' => 'string',
        'gender' => 'string',
        'country' => 'required|string',
        'company_name' => 'string',
        'ADB' => 'string',
        'ownership' => 'string',
        'mailing_address' => 'string',
        'parnanent_address' => 'string',
        'experience' => 'string',
        'street_address' => 'string',
        'city' => 'string',
        'region' => 'string',
        'province' => 'string',
        'phone' => 'string',
        'fax' => 'string',
        'project_profile_codes' => 'string',
        'description' => 'string',
        'pec_certificate' => 'sometimes|files|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
        'pec_register' => 'string',
        'postal_code' => 'string',
        'website_link' => 'string',
        'filename' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
        'imgname' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
        'imagename' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
        'engineering' => 'string',
        'allied' => 'string',
        'alternative_email' => 'string',
        'employee' => 'string',
        ]);

    if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
    {

        return back()->withInput()->withErrors($validator);
        // validation failed redirect back to form
        if (request()->hasFile('filename')){
            request()->validate([
                'filename' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
            ]);
        }
        if (request()->hasFile('imgname')){
            request()->validate([
                'imgname' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
            ]);
        }
        if (request()->hasFile('imagename')){
            request()->validate([
                'imagename' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
            ]);
        }

    } else {
        //validations are passed, save new user in database

        $Client = ClientMDL::where('email1', Auth::user()->email)->first();
            if ($request->hasfile('filename')) {
                $file = $request->file('filename');
                $extension = $file->getClientOriginalExtension();
                $filename  = time() . '.' . $extension;
                $file->move('files/clients/', $filename);
                $Client->filename = $filename;
            }
            if ($request->hasfile('imgname')) {
                $file = $request->file('imgname');
                $extension = $file->getClientOriginalExtension();
                $filename  = time() . '.' . $extension;
                $file->move('files/clients/', $filename);
                $Client->imgname = $filename;
            }
            if ($request->hasfile('imagename')) {
                $file = $request->file('imagename');
                $extension = $file->getClientOriginalExtension();
                $filename  = time() . '.' . $extension;
                $file->move('files/clients/', $filename);
                $Client->imagename = $filename;
            }
        $Client->user_title = $request->user_title;
        $Client->mname = $request->mname;
        $Client->fname = $request->fname;
        $Client->lname = $request->lname;
        $Client->gender = $request->gender;
        $Client->country = $request->country;
        $Client->company_name = $request->company_name;
        $Client->ADB = $request->ADB;
        $Client->ownership = $request->ownership;
        $Client->mailing_address = $request->mailing_address;
        $Client->parnanent_address = $request->parnanent_address;
        $Client->experience = $request->experience;
        $Client->street_address = $request->street_address;
        $Client->city = $request->city;
        $Client->region = $request->region;
        $Client->province = $request->province;
        $Client->phone = $request->phone;
        $Client->fax = $request->fax;
        $Client->pec_register = $request->pec_register;
        $Client->postal_code = $request->postal_code;
        $Client->website_link = $request->website_link;
        $Client->engineering = $request->engineering;
        $Client->allied = $request->allied;
        $Client->alternative_email = $request->alternative_email;
        $Client->employee = $request->employee;
        $Client->save();

        return redirect("client/profile");
    }
}
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\client  $client
     * @return \Illuminate\Http\Response
     */
    public function destroy($id, Request $request)
    {
        $client = ClientMDL::where('id', '=', $id)->first();
        $client->delete();
        $request->session()->flash('message', "Successfully deleted Client");
        $request->session()->flash('back', 'clients.index');
        return view('dashboard.shared.universal-info');
    }

    public function edit_profile()
    {
        $user = ClientMDL::where('phone', Auth::user()->email)->first();
        return view('dashboard.clients.profile', compact('user'));
    }

    public function post_project()
    {
        $countries = Country::all();
        return view('dashboard.clients.post_project', compact('countries'));
    }

    public function my_projects()
    {
        $projects = Project::where('user_id', Auth::user()->id)->get();
        return view('dashboard.clients.projects', compact('projects'));
    }
    /*
    Author : Enayat
    Date   :  06-05-2022
    */ 
    public function getConsultant()
    {
        $consultants = DB::table("excel_consultants")->get();
        // dd($consultants);
        return view('dashboard.clients.consultants', compact('consultants'));
    }
    public function consultantDetail($id)
    {
        $consultant_detail = DB::table('excel_consultant_contact_details as d')
                                 ->join('excel_consultant_service_codes as s','d.License_No','s.License_No','left') 
                                 ->join('excel_consultant_specialization_code as sc','d.License_No','sc.License_No','left')
                                 ->get();

       
        return view('dashboard.clients.consultants_detail',compact('consultant_detail'));                             

    }
}
