<?php

namespace App\Http\Controllers;

use Auth;
use App\Models\Buyer;
use App\Models\Exporter;
use App\Models\Meeting;
use App\Models\User;
use Illuminate\Http\Request;
use App\Mail\VerifyUserEmail;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
class BuyerController extends Controller
{
        use RegistersUsers;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $meeting = Meeting::select('*')->where('notify', 0)->where('buyer_id', Auth::user()->buyer_exporter_id)->count('*');
        $booth_number = "";
        if(str_contains(Auth::user()->menuroles, "exporter")){
            $booth_number = Exporter::where('id', Auth::user()->buyer_exporter_id)->value('booth_number');
        }
        $buyers = Buyer::all();
        $industries = Buyer::select('industry')->distinct()->orderBy('industry')->get()->toArray();
        $industries = array_column($industries, 'industry');

        return view('dashboard.buyers.index', array(
            'buyers' => $buyers,
            'industries' => $industries,
            'booth_number' => $booth_number,
        ), compact('meeting'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store_buyer(Request $request)
    {
        // dd($request->all());
        $request->validate([
         'contact_name'  => 'required|max:50',
         'category' => 'required',
         'phone'   => 'required|max:50',
         'country_code' => 'required',
         'email'  => 'required|unique:users|max:100',
         'country'  => 'required',
         'website'  => 'required|max:250' ,
         'company_name'  => 'required|max:250',
        //  'password' => ['string',
        //     'min:8',             
        //     'regex:/[a-z]/',      
        //     'regex:/[A-Z]/',      
        //     'regex:/[0-9]/',  'regex:/[@$!%*#?&]/'],
            
        //  ]);
           'password' => ['string','min:4'],
            ]);
         $buyer = new Buyer();
         $buyer->contact_name = $request->contact_name;
         $buyer->country  = $request->country;
         $buyer->email  = $request->email;
         $buyer->country_code = $request->country_code;
         $buyer->password = Hash::make($request->password);
         $buyer->phone = $request->country_code.''.$request->phone;
         $buyer->company_name = $request->company_name;
         $buyer->whatsapp = $request->phone;
         $buyer->website =$request->website;
         $buyer->industry = $request->category;
        //  $buyer->about_us= $request->about_us;
        //  $buyer->services_offered = $request->services_offered;
        //  dd($buyer);
         $buyer->save();

            $user = new user();
             $token = Str::random(40);    
             $user->name = $request->contact_name;
             $user->email = $request->email;
             $user->menuroles = 'buyer';
             $user->password= Hash::make($request->password);
             $user->activation_token = $token;
             $user->buyer_exporter_id = $buyer->id;
            //  dd($user);
             if($user->save())
             {
                $user->assignRole('buyer');
                $data['name'] = $request->contact_name;
                $data['token'] = $token;
                $data['email'] = $request->email;
                $response= Mail::to($request->email)->send(new VerifyUserEmail($data));
                
                $request->session()->flash('message', 'Thank you, You have been registered as  APICTA DELEGATE successfully. An email has been sent to your email address containing an activation link. Please check your email and click on the link to activate your account. If you do not click the link your account will remain inactive and you will not be able to login. If you do not receive the email within a few minutes, please check your spam folder.');
                
                return redirect()->route('login');
             }
             else
             {
                $request->session()->flash('message', 'Something went wrong!');
                // return redirect()->route('login');
             }

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Buyer  $buyer
     * @return \Illuminate\Http\Response
     */
    public function show(Buyer $buyer)
    {
        return view('dashboard.buyers.show', $buyer);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Buyer  $buyer
     * @return \Illuminate\Http\Response
     */
    public function edit(Buyer $buyer)
    {
        return view('dashboard.buyers.edit', array('buyer' => $buyer));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Buyer  $buyer
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Buyer $buyer)
    {
        $validated = $request->validate([
            'password' => 'required'
        ]);
        $buyer->password = Hash::make($request->input('password'));
        $buyer->save();

        $request->session()->flash('message', 'Successfully updated buyer');
        return redirect()->route('buyers.edit', $buyer->id);
    }

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

     public function available_time_slots(Request $request)
    {
        $date = $request->input('date');
        $buyer_id = $request->input('buyer_id');
        $booked_slots = Meeting::where('buyer_id', $buyer_id)->where('date', $date)->pluck('time')->all();
        $all_time_slots = [
            
               '09:00 - 09:25',
             '09:30 - 09:55',
             '10:00 - 10:25',
             '10:30 - 10:55',
             '11:00 - 11:25',
             '11:30 - 11:55',
             '12:00 - 12:25',
             '12:30 - 12:55',
             '13:00 - 13:25',
             '13:30 - 13:55'
        ];
        $available_time_slots = array_diff($all_time_slots,$booked_slots);
        echo json_encode($available_time_slots);
    }
    
    
     public function view_profile($id)
    {
    
        $user= User::where('id', $id)->first();
        
        if($user->menuroles == 'buyer')
        {
              $buyer = Buyer::where('id', $user->buyer_exporter_id)->first();
               return view('edit_profile_buyer', compact('user','buyer'));
        }
        if($user->menuroles == 'exporter')
        {
            $exporter = Exporter::where('id', $user->buyer_exporter_id)->first();
             return view('edit_profile_exporter', compact('user', 'exporter'));
        }
     
    }
    
    public function update_profile(Request $request, $id)
    {
          $user= User::where('id', $id)->first();
        //  dd($user);
          if($user->menuroles == 'buyer')
        {
             
        $request->validate([
         'contact_name'  => 'required',
         'category' => 'required',
         'phone'   => 'required',
         'country_code' => 'required',
          'country'  => 'required',
         'website'  => 'required' ,
         'company_name'  => 'required',
       
            
         ]);
           
         $buyer = Buyer::where('id', $user->buyer_exporter_id)->first();
         $buyer->contact_name = $request->contact_name;
         $buyer->country  = $request->country;
        //  $buyer->email  = $request->email;
        //  $buyer->password = Hash::make($request->password);
         $buyer->country_code = $request->country_code;
         $buyer->phone = $request->country_code.''.$request->phone;
         $buyer->company_name = $request->company_name;
         $buyer->whatsapp = $request->phone;
         $buyer->website =$request->website;
          if ($request->category == "Other") {
          
            $buyer->industry  = $request->other_category_buyer;
        }
        else
        {
             $buyer->industry  = $request->category;
        }
        
         $buyer->save();

           
             $user->name = $request->contact_name;
            //  $user->email = $request->email;
           
           if($user->save())
           {
               return redirect()->back()->with('message', 'Profile has been updated succesfully');
               }
               
            //   return view('edit_profile_buyer', compact('buyer'));
        }
        if($user->menuroles == 'exporter')
        {
           $request->validate([
            'contact_name'  => 'required',
            'category' => 'required',
            'phone'   => 'required',
            'country_code' => 'required',
            'country'  => 'required',
            'website'  => 'required',
            'company_name'  => 'required',
            'is_pasha_member' => 'required',
            
            'services_offered' => 'required',
            'about_us' => 'required'
         
        ]);

       $exporter = Exporter::where('id', $user->buyer_exporter_id)->first();
        $exporter->contact_name = $request->contact_name;
        $exporter->country  = $request->country;
        // $exporter->email  = $request->email;
        $exporter->country_code = $request->country_code;
        $exporter->phone = $request->country_code.''.$request->phone;
        $exporter->website = $request->website;
        $exporter->company_name = $request->company_name;
        $exporter->services_offered = $request->services_offered;
        $exporter->about_us = $request->about_us;
        if ($request->category == "Other") {
            // $request->category = $request->other_category_buyer;
            $exporter->industry = $request->other_category;
        }
        else
        {
             $exporter->industry = $request->category;
        }
       
        $exporter->is_pasha_member = $request->is_pasha_member;
        $exporter->save();

         
        $user->name = $request->contact_name;
        // $user->email = $request->email;
         if($user->save())
           {
               return redirect()->back()->with('message', 'Profile has been updated succesfully');
               } 
            
           
            
            //  return view('edit_profile_exporter', compact('user', 'exporter'));
        }
         
    }
    
}
