<?php

namespace App\Http\Controllers;

// use App\Http\Controllers\Controller;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Http\Response as res;
use App\MasterEvent;
use App\EventParticipant;
use App\Users;
use Cookie;

class InvitationController extends Controller

{

  public function __construct()

   {

     //  $this->middleware('auth:api');

   }

   /**

    * Display a listing of the resource.

    *

    * @return \Illuminate\Http\Response

    */

   public function postAccept(Request $request)
   {


      $validate = MasterEvent::where('end_date','>',date('Y-m-d'))->where('id',$request->evenid)->first();

      if($validate)
      {

          $data = EventParticipant::where('invitation_code', $request->name)->where('fk_master_event',$request->evenid)->where('email',$request->email)->first();

          if($data){

              
              $data->acceptance_status = 1;
              $data->save();

              return redirect::to('/event/'.$validate->event_slug)->withCookie(cookie('invitation', $data->id,5));
            

          }else{

            // dd('you hav entered incorrect email/invitation codes or you are not invited to this event');
             return redirect::to('/event/'.$validate->event_slug)->withCookie(cookie('message', 'You have entered incorrect email/invitation code or you are not invited to this event',1));

          }

             




      }else{

          // dd('The Event that you are invited has endded');
          $slug = MasterEvent::where('id',$request->evenid)->first();
          return redirect::to('/event/'.$slug->event_slug)->withCookie(cookie('message', 'The Event that you are invited has endded',1));
      }



   }

   public function index(Request $request)
   {

       $this->validate($request, [

       'email' => 'required',

       'password' => 'required'

        ]);

       dd($request);

      $user = Users::where('email', $request->input('email'))->first();
      if($user){
      // dd(Hash::make($user->password));

         if(Hash::check($request->input('password'), $user->password)){

                if($user->api_key){

                     return response()->json(['status' => 'success','api_key' => $user->api_key]);

                }else{

                  $apikey = base64_encode(str_random(40));
                  Users::where('email', $request->input('email'))->update(['api_key' => "$apikey"]);
                  return response()->json(['status' => 'success','api_key' => $user->api_key]);

                }

                      

          }else{

              return response()->json(['status' => 'fail'],401);

          }
        }else{

            return response()->json(['status' => 'fail','message' => 'Email is not registered']);
        }

   }

}    

?>