<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\VisitorEntry;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use App\Helpers\LogActivity;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Carbon;
use App\Models\Notification;
use App\Helpers\Frontend;
use App\Models\Sessionotp;
use App\Models\Vehicle;
use App\Models\Identity;
use App\Models\State;
use App\Models\Country;

class VisitorApiController extends Controller
{
    private $allData,$data,$res;

    public function visitorRegister(Request $request)
    {
       
        $this->allData = $request->all();      
       // return $this->allData;
        $validator = Validator::make($this->allData, [
            'email' => 'required|email|unique:users',
            'mobile'=>'required|numeric|unique:users',
            'password' => 'required',
            'organization_id'=> 'required'
        ]);

        if($validator->fails())
        {
            return response()->json(['message' => $validator->messages()->first(),'status'=>0], 422);
        }
        else
        {
            $this->allData['password'] = Hash::make($request->password);
            $this->allData['type'] = "gatekeeper";
            $this->allData['admin_id'] = $request->organization_id;
            unset( $this->allData['orgnization_id']);

            $user = User::create($this->allData);           

            if($user)
            {
                //$user['token'] =  $user->createToken('Edukrypt')->plainTextToken;
                return response()->json([
                    "status"=>1,
                    "message"=>"Visitor Register Successfully",
                    "data"=>$user,
                ],200);
                
            }            
            else
            {
                return response()->json([
                    "status"=>0,
                    "message"=>"Registeration Failed !"                    
                ],409);
            }

        }
    }
    public function visitorEntry(Request $request)
    {
        $this->allData = $request->all();   

        $user = [];   
       // return $this->allData;
        $validator = Validator::make($this->allData, [
            'admin_id' => 'required',
            'visitor_name' => 'required',
            "gender"=> "required",
            "id_type"=> "required",
            "id_number"=> "required",
            "visitor_mobile"=> "required|numeric",
            "address"=> "required",
            "city"=> "required",
            "state"=> "required",
            "pincode"=> "required",
            'visitor_category_id' => 'required',
            "purpose_of_visit" => 'required',
            "contact_no" => 'required|numeric',
            "check_in_time" => 'required',
            "check_out_time" => 'required',
            "gate" => 'required',
            "profile_pic"=>'image|mimes:jpeg,png,jpg,gif|max:2048',
            "host_id" => "required",
            "host_department" => "required",
            "visit_date" => "required"
        ]);

        if($validator->fails())
        {
            return response()->json(['message' => $validator->messages()->first(),'status'=>0], 422);
        }
        else
        {
            if($request->has('profile_pic') && !empty($request->file('profile_pic')))
            {
                $image = $request->file("profile_pic");
                $filename = time().'.'.$image->getClientOriginalExtension();
                $path = "/admin/visitor/";

                $image->move(public_path($path),$filename);
                $this->allData['profile_pic'] = $path.$filename;

                $user = User::where('mobile',$this->allData["visitor_mobile"])->get();

                if($user->count() == 0)
                {
                    User::create([
                        "admin_id"=> $this->allData["admin_id"],
                        "name"=> $this->allData["visitor_name"],
                        "visitor_id" => $this->allData["id_type"],
                        "id_number" => $this->allData["id_number"],
                        "organization" => $this->allData["organization"],
                        "designation" => $this->allData["designation"],
                        "mobile" => $this->allData["visitor_mobile"],
                        "address" => $this->allData["address"],
                        "city" => $this->allData["city"],
                        "state" => $this->allData["state"],
                        "country" => $this->allData["country"],
                        "pincode" => $this->allData["pincode"],
                        "email" => $this->allData["visitor_mobile"]."@gamil.com",
                        "password" => Hash::make("123456"),
                        "type" => "visitor"
                    ]);
                }
                
                
                $this->res = VisitorEntry::create($this->allData);
                if($this->res)
                {
                    return response()->json([
                        "status"=>1,
                        "message"=>"Entry Save Successfully",
                        "data"=>$this->res
                    ],200);
                }
                else
                {
                    return response()->json([
                        "status"=>0,
                        "message"=>"Failed",
                    ],409);
                }

            }
            else
            {
                unset($this->allData["profile_pic"]);
                $user = User::where('mobile',$this->allData["visitor_mobile"])->get();

                if($user->count() == 0)
                {
                    User::create([
                        "admin_id"=> $this->allData["admin_id"],
                        "name"=> $this->allData["visitor_name"],
                        "visitor_id" => $this->allData["id_type"],
                        "id_number" => $this->allData["id_number"],
                        "organization" => $this->allData["organization"],
                        "designation" => $this->allData["designation"],
                        "mobile" => $this->allData["visitor_mobile"],
                        "address" => $this->allData["address"],
                        "city" => $this->allData["city"],
                        "state" => $this->allData["state"],
                        "country" => $this->allData["country"],
                        "pincode" => $this->allData["pincode"],
                        "email" => $this->allData["visitor_mobile"]."@gamil.com",
                        "password" => Hash::make("123456")
                    ]);
                }

                $this->res = VisitorEntry::create($this->allData);
                if($this->res)
                {
                    return response()->json([
                        "status"=>1,
                        "message"=>"Entry Save Successfully",
                        "data"=>$this->res
                    ],200);
                }
                else
                {
                    return response()->json([
                        "status"=>0,
                        "message"=>"Failed",
                    ],409);
                }
            }
            
        }
    }

    public function allVisit(Request $request)
    {
        $this->allData = $request->all();

        $validator = Validator::make($this->allData, [
            'getekeeper_id' => 'required'           
        ]);

        if($validator->fails())
        {
            return response()->json(['message' => $validator->messages()->first(),'status'=>0], 422);
        }
        else
        {
            $this->res = VisitorEntry::with('host')->where('gatekeeper_id',$request->getekeeper_id)->orderBy('check_in_time','desc')->get();
            if($this->res->count() != 0)
            {
                return response()->json([
                    "status"=>1,
                    "message"=>"success",
                    "data"=>$this->res
                ],200);
            }
            else
            {
                return response()->json([
                    "status"=>0,
                    "message"=>"Failed",
                ],404);
            }
        }
    }

    public function getCategory(Request $request)
    {
        $this->data["vehicles"] = Vehicle::select('id','vehicle_type')->get();
        $this->data["id_types"] = Identity::select('id','id_type')->get();
        
        $this->data["hosts"] = User::where('organization_id',$request->organization_id)->select('id','name','designation','organization','department','organization_id')->get();
        
        if($this->data)
        {
            return response()->json([
                "status"=>1,
                "message"=>"success",
                "data"=>$this->data
            ],200);
        }
        else
        {
            return response()->json([
                "status"=>0,
                "message"=>"Failed",
            ],404);
        }
    }

    public function getCountryState()
    {
        $this->data["country"] = Country::select('id','name')->get();
        $this->data["states"] = State::select('id','state_name')->get();

        if($this->data)
        {
            return response()->json([
                "status"=>1,
                "message"=>"success",
                "data"=>$this->data
            ],200);
        }
        else
        {
            return response()->json([
                "status"=>0,
                "message"=>"Failed",
            ],404);
        }
    }

    /*
    public function visitorNotification($orgnization_id)
    {
        
          $this->res = $this->res = Notification::where('admin_id',$orgnization_id)->get();
            if($this->res)
            {
                return response()->json([
                    "status"=>1,
                    "message"=>"success",
                    "data"=>$this->res
                ],200);
            }
            else
            {
                return response()->json([
                    "status"=>0,
                    "message"=>"Failed",
                ],404);
            }
        
    }

    */
    public function gateKeeperLogin(Request $request)
    {
        $this->allData = $request->all();      
       //return $this->allData;
       
        $validator = Validator::make($this->allData, [
            'mobile' => 'required',
        ]);

        if($validator->fails())
        {
            return response()->json(['message' => $validator->messages()->first(),'status'=>0], 422);
        }
        else
        {
            $otp = rand(1111, 9999); 
            
            /*$html = "<div style='border:5px groove blue;text-align:center'><h1>Your opt is : <strong>".$otp."</strong></h1></div>";
            $resMail = Frontend::sendMailPostal($request->email,"VisitorKrypt Login OTP",$html);
            
            if($resMail)
            {
                if (!empty($resMail->message_id))
                {
                    Sessionotp::create(['email'=>$request->mobile,'otp'=>$otp,'status'=>'active']);
                    return response()->json([
                        "status"=>1,
                        "message"=>"success",
                        "data" => "OTP send to your email : ".$request->email
                    ],200);
                }
            }*/
            $res = Sessionotp::create(['email'=>$request->mobile,'otp'=>1111,'status'=>'active']);
            
            if($res)
            {
                
                return response()->json([
                    "status"=>1,
                    "message"=>"success",
                    "data" => "OTP send to your mobile : ".$request->mobile,
                    "otp_id" => $res->id
                ],200);
            }
            else
            {
                return response()->json([
                    "status"=>0,
                    "message"=>"failed ! Try later"
                ],409);
            }  
        }
    }

    public function forgotPassword(Request $request)
    {
        $this->allData = $request->all();

        $validator = Validator::make($this->allData, [
            'email' => 'required|email'           
        ]);

        if($validator->fails())
        {
            return response()->json(['message' => $validator->messages()->first(),'status'=>0], 422);
        }
        else
        {
            
            $otp = rand(1111, 9999); 
            
            $html = "<div style='border:5px groove blue;text-align:center'><h1>Your opt is : <strong>".$otp."</strong></h1></div>";
            $resMail = Frontend::sendMailPostal($request->email,"SchoolKrypt Forgot Password OTP",$html);
            
            if($resMail)
            {
                if (!empty($resMail->message_id))
                {
                    Sessionotp::create(['email'=>$request->email,'otp'=>$otp,'status'=>'active']);
                    return response()->json([
                        "status"=>1,
                        "message"=>"success",
                        "data" => "OTP send to your email : ".$request->email
                    ],200);
                }
            }
            else
            {
                return response()->json([
                    "status"=>0,
                    "message"=>"failed ! Try later"
                ],409);
            }               
            
           
        }
    }

    public function otpVerify(Request $request)
    {
        $this->allData = $request->all();
        

        $validator = Validator::make($this->allData, [
            'mobile' => 'required',
            'otp_id' => 'required',
            'otp' => 'required'           
        ]);

        if($validator->fails())
        {
            return response()->json(['message' => $validator->messages()->first(),'status'=>0], 422);
        }
        else
        {
            
            $this->res = Sessionotp::where([
                        ['id','=',$request->otp_id],
                        ['otp','=',$request->otp]
                ])->first();
            if($this->res)
            {
                $otpCreatedAt = Carbon::parse($this->res->created_at);

                // Add two minutes to the created_at timestamp
                $twoMinutesAfterCreatedAt = $otpCreatedAt->addMinutes(2);
                
                // Get the current date and time
                $currentDateTime = Carbon::now();

                if ($twoMinutesAfterCreatedAt->gt($currentDateTime)) 
                {                                
                    $response = Sessionotp::where('id',$request->otp_id)->update(['status'=>'inactive']);
                    
                    if($response)
                    { 
                        
                            $res = User::where(['mobile' => $request->mobile])->select("id","admin_id","organization_id","organization","email","mobile","gender","id_type","id_number","address","city","state","pincode","profile_pics")->first();
                            if($res)
                            {
                                //Log Activity
                                //$logMessage = "user logged in";
                                //LogActivity::addToLog($logMessage);

                                return response()->json([
                                    "status"=>1,
                                    "message"=>"OTP match successfully !",
                                    "data"=>$res
                                ],200);
                            }                  
                        
                            else
                            {
                                return response()->json([
                                    "status"=>0,
                                    "message"=>"User not found !"
                                ],404);
                            }
                        
                    }
                    else
                    {
                        return response()->json([
                            "status"=>0,
                            "message"=>"OTP match failed !"
                        ],404);
                    }
                    
                }
                else
                {
                    return response()->json([
                        "status"=>0,
                        "message"=>"OTP expired !"
                    ],404);
                }
            }
            else
            {
                return response()->json([
                    "status"=>0,
                    "message"=>"OTP not matched !"
                ],404);
            }
                
        }   
    }
    public function resetPassword(Request $request)
    {
        //return $request->all();
        $this->allData = $request->all();      
       // return $this->allData;
        $validator = Validator::make($this->allData, [
            'email' => 'required|email',
            'password' => 'required',
            'confirm_password' => "required|same:password",
        ],
            [
            "confirm_password.same" => "The password confirmation does not match",
            ]
        );

        if($validator->fails())
        {
            return response()->json(['message' => $validator->messages()->first(),'status'=>0], 422);
        }
        else
        {
            $password = Hash::make($request->password);
            $this->res = User::where('email',$request->email)->update(['password'=>$password]);
            if($this->res)
            {
                $html = "<div style='border:5px groove blue;text-align:center'><h1>Your password is : <strong>".$request->password."</strong></h1></div>";
                Frontend::sendMailPostal($request->email,"Password Reset",$html);

                return response()->json([
                    "status"=>1,
                    "message"=>"Password Upade Successfully check your email"
                ],200);
            }
            else
            {
                return response()->json([
                    "status"=>0,
                    "message"=>"failed !"
                ],409);
            }
        }
    }

    /*
    public function logout()
    {
         // Log Activity
         $logMessage = "user logout";
         LogActivity::addToLog($logMessage);
 
         $this->res = Auth::logout();
         
        if($this->res)
        {
            return response()->json([
                "status"=>1,
                "message"=>"Logout Successfully"
            ],200);
        }
        else
        {
            return response()->json([
                "status"=>0,
                "message"=>"failed !"
            ],409);
        }
    }*/

}
