<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Ticket;
use App\Models\Event;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class OrganiserController extends Controller
{

    public function __construct()
    {
        $this->middleware(['common']);

        $this->ticket   = new Ticket;
        $this->user     = new User;
    }

    /**
     * show all events of particular organiser
     */

    public function show($organisation_url)
    {
        if(empty($organisation_url))
            return abort('404');
        
        $organisation_url           = (string) $organisation_url;
        $organiser      =  User::where('organisation_url', $organisation_url)->first();
       
        if(empty($organiser))
            return abort('404');
            
        $events  = Event::leftJoin("categories", "categories.id", '=', "events.category_id")
                        ->select(["events.*", "categories.name as category_name"])
                        ->where(['events.user_id' => $organiser['id'], 'events.publish' => 1, 
                                    'events.status'   => 1, 'categories.status' => 1])
                        ->selectRaw("(SELECT CN.country_name FROM countries CN WHERE CN.id = events.country_id) country_name")
                        ->selectRaw("(SELECT SD.repetitive_type  FROM schedules SD WHERE SD.event_id = events.id limit 1 ) 
                            repetitive_type")
                        ->selectRaw("(SELECT U.name FROM users U WHERE U.id = events.user_id) organiser_name")->get();

        $event_ids       = [];

        foreach($events as $key => $value)
            $event_ids[] = $value->id;

        // pass events ids
        // tickets
        $events_tickets     = $this->ticket->get_events_tickets($event_ids);
                
        $events_data             = [];
        
        foreach($events as $key => $value)
        {
            // online event - yes or no
            $value                  = $value->makeVisible('online_location');
            // check event is online or not
            $value->online_location    = (!empty($value->online_location)) ? 1 : 0; 

            $events_data[$key]             = $value;
            
            foreach($events_tickets as $key1 => $value1)
            {
                // check relevant event_id with ticket id
                if($value->id == $value1['event_id'])
                {
                    $events_data[$key]->tickets[]       = $value1;
                }
            }

            //CUSTOM
            // sale tickets
            $sale_tickets = Ticket::where('sale_start_date', '<=', Carbon::now()->timezone(setting('regional.timezone_default'))->toDateTimeString())
            ->where('sale_end_date', '>', Carbon::now()->timezone(setting('regional.timezone_default'))->toDateTimeString())
            ->whereNotNull('sale_start_date')
            ->where(['event_id' => $value->id])
            ->orderBy('sale_start_date')
            ->get();    

            $events_data[$key]->sale_tickets  = $sale_tickets;
            //CUSTOM
        }
        
        $events = collect($events_data);
        
        $activeEvents   = [];
        $expiredEvents  = [];
        
        if($events->isNotEmpty())
        {
             // for active events
            $activeEvents = $events->reject(function ($value, $key) {
                
                // Attach venues to the event
                $activeEvents['venues'] = $value->venues->toArray();

                // for without repeative event 
                if($value->repetitive == 0)
                    return Carbon::today()->toDateString() > $value->end_date;

                // for repeative event 
                return Carbon::today()->toDateString() > $value->end_date;
            });


            // for expired events
            $expiredEvents = $events->reject(function ($value, $key) {
                
                // Attach venues to the event
                $expiredEvents['venues'] = $value->venues->toArray();

                // for without repeative event 
                if($value->repetitive == 0)
                    return Carbon::today()->toDateString() < $value->end_date;
                    
                // for repeative event 
                return Carbon::today()->toDateString() < $value->end_date;
            });
            
        }    

        $customerUser = Auth::check() && Auth::user()->hasRole('customer')  ? Auth::user()  : null;

        $currency            = setting('regional.currency_default');

        $organiser_d          = (object) [
            'id'                => $organiser->id,
            'name'              => $organiser->name,
            'email'             => $organiser->email,
            'avatar'            => $organiser->avatar,
            'organisation'      => $organiser->organisation,
            'address'           => $organiser->address,
            'phone'             => $organiser->phone,
            'org_description'   => $organiser->org_description,
            'org_facebook'      => $organiser->org_facebook,
            'org_instagram'     => $organiser->org_instagram,
            'org_youtube'       => $organiser->org_youtube,
            'org_twitter'       => $organiser->org_twitter,
            'org_website'       => $organiser->org_website,
            'org_join'          => $organiser->created_at,
            'customerUser'      => $customerUser,
        ];

        if(checkPrefix()){  
            return response()->json([  
                'status' => true,
                'data' => [
                    'organiser_d' => $organiser_d,
                    'activeEvents' => [...$activeEvents],
                    'expiredEvents' => [...$expiredEvents],
                    'currency' => $currency
                ],
            ], 200);
        }

        return view('organiser.show',compact(['activeEvents', 'expiredEvents', 'currency', 'organiser_d']));
    }

    // send contact email to Organiser
    public function contactOrganiser(Request $request)
    {

        $param = [
            'id' => $request->organiser_id
        ];
   
         // check this event id have login user or not
        $user      = $this->user->get_user($param);
        
        if(empty($user))
        {
            return error('access denied', Response::HTTP_BAD_REQUEST );
        }

        $request->validate([
            'name'           => 'required|min:3|max:256',
            'email'          => 'required|email',
            'phone'          => 'nullable',
            'message'        => 'required|min:2|max:2000',
        ]);

        $data = [
            'name'          => $request->name,
            'email'         => $request->email,
            'phone'         => $request->phone,
            'message'       => $request->message,
            'organiser_response' => $request->organiser_response ?? 0,
        ];
        
        // ====================== Notification ====================== 
        //send notification after bookings
        $msg[]                  = __('eventmie-pro::em.name').' - '.$data['name'];
        $msg[]                  = __('eventmie-pro::em.email').' - '.$data['email'];
        $msg[]                  = __('eventmie-pro::em.phone').' - '.$data['phone'];
        $msg[]                  = __('eventmie-pro::em.message').' - '.$data['message'];

        

        $mail['mail_subject']   = __('eventmie-pro::em.message_sent');
        $mail['mail_message']   = '';
        $mail['action_title']   = __('eventmie-pro::em.view').' '.__('eventmie-pro::em.all').' '.__('eventmie-pro::em.events');
        $mail['n_type']         = "organizer_contact";

        $mail['contact']        =  array('name' => $data['name'], 'email' => $data['email'], 'phone' => $data['phone'], 'message' => $data['message'], 'organiser_response' => $data['organiser_response']) ;

        try {
            //CUSTOM
            \App\Jobs\RegistrationEmailJob::dispatch($mail, $user, 'organizer_contact')->delay(now()->addSeconds(10));
            // test
            // return view('email_templates.contact', compact('mail'));
            //CUSTOM
        } catch (\Throwable $th) {
            // dd($th->getMessage());
        }
        // ====================== Notification ====================== 

        if(checkPrefix()){
            return response()->json([
                'status' => true,
                'message' => 'Message sent successfully',
            ], 200);
        }
        
        return redirect()->back()->with('msg', __('eventmie-pro::em.message_sent')); 
    }

    
}
