<?php

namespace App\Http\Controllers;

use Session;
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\Consultant;
use App\Models\User;
use App\Models\Project;
use App\Models\ProjectRequest;
use App\Models\pec_register_consultant;
use Illuminate\Support\Facades\DB;
use Mail;

class ConsultantController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $consultants = Consultant::all();
        return view('dashboard.consultants.index', compact('consultants'));
    }

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


        return view("register");
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
     {
        if (empty($request->otp) || $request->otp != Session::get('otp'))   //check all validations are fine, if not then redirect and show error messages
        {
            return back()->withInput()->withErrors(['OTP is not correct.']);
        }
         $validator = Validator::make($request->all(), [
            // 'pec_register' => 'string',
            // 'user_title' => 'string',   // required and email format validation
            // 'mname' =>'string', // required and number field validation
            // 'fname' => 'string',
            // 'lname' => 'string',
            // 'gender' => 'string',
            // 'country' => 'string',
            // 'individual_firm' => 'string',
            // 'email1' => 'email', 'max:255', 'unique:users',
            'pec_no' => 'required|string',
            'otp' => 'string',
            'password' => 'string|min:8',


        ]);
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {
            return back()->withInput()->withErrors($validator);
        } else {

            // $Consultant = new Consultant;
            // $Consultant->pec_register = $request->pec_register;
            // $Consultant->client_reg = $request->client_reg;
            // $Consultant->user_title = $request->user_title;
            // $Consultant->mname = $request->mname;
            // $Consultant->fname = $request->fname;
            // $Consultant->lname = $request->lname;
            // $Consultant->gender = $request->gender;
            // $Consultant->country = $request->country;
            // $Consultant->individual_firm = $request->individual_firm;
            // $Consultant->otp = $request->otp;
            // $Consultant->email1 = $request->email1;

            // $Consultant->save();

            $response= DB::table("pec_register_consultant")
            ->where('pec_no' ,"=" , $request->pec_no)->first();

            $user = User::create([
                'fname' => $response->first_name,
                'lname' => $response->last_name,
                'password' => bcrypt($request->password),
                'email' => $response->pec_no,
                'menuroles' => 'consultant',
            ]);
            $user->assignRole('consultant');

            // event(new Registered($user));

            if (auth()->attempt(array('email' => $request->pec_no, 'password' => $request->password),true)) {
                return redirect("/login/consultant")->with('success', 'You have successfully registered, Login to access your dashboard');
            }


        }
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Consultant  $consultant
     * @return \Illuminate\Http\Response
     */
    public function edit(Consultant $consultant)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Consultant  $consultant
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {

           $validator = Validator::make($request->all(), [
            'pec_register' => 'string',
            'user_title' => 'required|string',   // required and email format validation
            'client_reg' => 'required|string',
            'mname' =>'required|string', // required and number field validation
            'fname' => 'required|string',
            'lname' => 'required|string',
            'gender' => 'required|string',
            'country' => 'required|string',
            'employee' => 'string',
            'individual_firm' => 'string',
            'company_name' => 'string',
            'ownership' => 'string',
            'mailing_address' => 'string',
            'parnanent_address' => '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',
            'postal_code' => 'string',
            'website_link' => 'string',
            'engineering' => 'string',
            'allied' => 'string',
            'alternative_email' => 'string',
        ]); // create the validations

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

        } else {
            //validations are passed, save new user in database
            $Consultant = Consultant::where('email1', Auth::user()->email)->first();

            if ($request->hasfile('pec_certificate')) {

                $file = $request->file('pec_certificate');
                $extension = $file->getClientOriginalExtension();
                $filename  = time() . '.' . $extension;
                $file->move('co/files/', $filename);
                $Consultant->pec_certificate = $filename;

            }
            $Consultant->pec_register = $request->pec_register;
            $Consultant->client_reg = $request->client_reg;
            $Consultant->user_title = $request->user_title;
            $Consultant->mname = $request->mname;
            $Consultant->fname = $request->fname;
            $Consultant->lname = $request->lname;
            $Consultant->gender = $request->gender;
            $Consultant->country = $request->country;
            $Consultant->individual_firm = $request->individual_firm;
            $Consultant->company_name = $request->company_name;
            $Consultant->ADB = $request->ADB;
            $Consultant->ownership = $request->ownership;
            $Consultant->mailing_address = $request->mailing_address;
            $Consultant->parnanent_address = $request->parnanent_address;
            $Consultant->street_address = $request->street_address;
            $Consultant->city = $request->city;
            $Consultant->region = $request->region;
            $Consultant->province = $request->province;
            $Consultant->phone = $request->phone;
            $Consultant->fax = $request->fax;
            $Consultant->project_profile_codes = $request->project_profile_codes;
            $Consultant->description = $request->description;
            $Consultant->postal_code = $request->postal_code;
            $Consultant->website_link = $request->website_link;
            $Consultant->engineering = $request->engineering;
            $Consultant->allied = $request->allied;
            $Consultant->alternative_email = $request->alternative_email;
            $Consultant->employee = $request->employee;
            $Consultant->save();
            return redirect("consultant/profile");
        }
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function edit_profile()
    {
        $user = Consultant::where('email1', Auth::user()->email)->first();
        return view('dashboard.consultants.profile', compact('user'));
    }

    public function applied_projects()
    {
        $project_requests = ProjectRequest::where('consultant_id', Auth::user()->id)->latest()->get();
        return view('dashboard.consultants.applied_projects', compact('project_requests'));
    }
    public function send_email(Request $request , $id)
    {
       $this->validate($request, [
          'otp' => 'required',
          'email1' => 'required'
       ]);

$otp = new pec_register_consultant();
$otp->otp = $request->otp;
$otp->save();
        $pec_register_consultant = pec_register_consultant::where('id','=', $id)->first();
        $user= User::where('email','=',  $request->email1)->first();
        if (filter_var(Auth::user()->email , FILTER_VALIDATE_EMAIL)){

            Mail::send('otp_email',
                 array(
                     'id' => $pec_register_consultant->id,
                    //  'user_id' => $user->id,
                 ),
                  function($message)
                  use ($pec_register_consultant ,$user)
                   {
                      if(Auth::user()){
                      $message->from("info@PEC.com");
                      }else{
                      $message->from("info@PEC.com");
                      }
                      $message->to($user->email);
                      $message->subject("PEC PORTAL - Dear Client  for the project");
                      $message->bcc("kashifali@a2zcreatorz.com");
                       $message->bcc("maham@a2zcreatorz.com");
                      $message->bcc("taimoor@a2zcreatorz.com");
                   });

                }
                return redirect('register');
                return redirect('register');
    }

   public function get_otp_email(Request $request)
   {

        $attr = $request->validate([
            'pec_no' => 'required|string'
        ]);

    $response= DB::table("pec_register_consultant")
    ->select('email' , 'consultant')
    ->where('pec_no' ,"=" , $request->pec_no)->first();

    if (!$response) {
            return response()->json([
                'status' => 'Failed',
                'message' => 'Please check your PEC No!',
                'data' => ''
            ], 404);
    }

if (filter_var($response->email , FILTER_VALIDATE_EMAIL)){

    \Mail::send('otp_email',
         array(
             'consultant' => $response->consultant,
         ),
          function($message)
          use ($response )
           {
              if($response->email){
              $message->from("info@pec.org.pk");
              }else{
              $message->from("info@pec.org.pk");
              }
              $message->to($response->email);
              $message->subject("PEC E-GATEWAY");
            //   $message->bcc("kashifali@a2zcreatorz.com");
            //    $message->bcc("maham@a2zcreatorz.com");
            //   $message->bcc("taimoor@a2zcreatorz.com");
           });
        }
        return response()->json($response);

        // return redirect("/login/consultant")->with('success', 'You have successfully registered, Login to access your dashboard');

// $response = DB::select(DB::raw("SELECT email  FROM `pec_register_consultant` WHERE pec_no = $request->client_reg"));

// return response()->json($response);
   }

}
