<?php

namespace App\DataTables;

use App\Models\Visitor;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
use DB;

class EventsVisitorsDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
			// ->editColumn('email', function($row) {
            //     $visitor = "visitors";
			// 	//$email = '".$row->email."';
            //     $emailAction = $row->email.' <button  class="btn btn-sm btn-primary btn-'.$row->id.'" data-email="'.$row->email.'" onclick="editEmail('.$row->id.');">
            //                                     <i class="fa fa-edit"></i>
            //                                 </button>';
            //     return $emailAction;
            // })

            ->addColumn('details', function($row) {
                // $btn =  '<a href="'.route('visitor.detail').'?id='.$row->id.'" >
                //                 Detail
                //         </a>';

                    //     <button style="width:80%;margin-left:-10px;color:white;" class="btn btn-block bg-gradient-info btn-sm" data-toggle="tooltip" data-placement="left" title="Detail">
                    //     <i class="bx bxs-edit"></i>Detail
                    // </button>
                // $btn .= '<button type="submit" class="btn btn-primary btn-sm" data-id="'.$row->id.'" data-event_id="'.$row->event_id.'"  style="margin-top: 10px;margin-left: -7px;" onclick="showevetlist(this);">Move</button>';
                $btn = '<a data-toggle="modal" data-target="#deletePopup" data-url="'.route('visitor.destroy',$row->id).'"  data-id="'.$row->id.'"
                            onclick="deletePopupvisitor(this)">
                            <button class="btn btn-danger btn-sm" data-toggle="tooltip" data-placement="right" title="Delete " style="margin-top: 10px;margin-left: 9px;">
                                <i class="fas fa-trash" aria-hidden="true"></i>
                            </button>
                        </a>';
                return $btn;
            })
            ->addColumn('edit', function($row) {
                $btn = '<a href="'.route('visitor.edit',$row->id).'">
                            <button class="btn btn-primary btn-sm" data-toggle="tooltip" data-placement="right" title="Edit " style="margin-top: 10px;margin-left: 9px;">
                                <i class="fas fa-pen-alt" aria-hidden="true"></i>
                            </button>
                        </a>';
                return $btn;
            })
            ->addColumn('action1', function($row) {
                $visitor = "visitors";

                $action = '<button type="submit" data-modal="addVisitModal"  data-url="'.route('visit.data.modal').'" data-event_id ="'.$row->event_id.'" data-visitor_id ="'.$row->id.'" class="btn btn-primary btn-sm add_Visit" style="width: 118%;margin-left:-7px;">Add Visit</button>';
                $action .= '<button type="submit" data-modal="sendEmail_Modal"  data-url="'.route('send.email.modal').'" data-event_id ="'.$row->event_id.'" data-visitor_id ="'.$row->id.'" class="btn btn-primary btn-sm mt-2 sendEmail" style="width: 118%;margin-left:-7px;">Send Email</button>';  

				/*$action .= '<form action="'.route('send.email').'" method="post">
								<input type="hidden" name="_token" value="'.csrf_token().'">
								<div class="form-group">
									<input type="hidden" name="visitor_id" id="visitor_id" value="'.$row->id.'">
									<input type="hidden" name="email_type" value="primary">
								</div>
								<button type="submit" class="btn btn-primary btn-sm" style="width: 118%;margin-left:-7px;">Send Primary Email</button>
							</form>';
				$action .= '<form action="'.route('send.email').'" method="post">
								<input type="hidden" name="_token" value="'.csrf_token().'">
								<div class="form-group">
									<input type="hidden" name="visitor_id" id="visitor_id" value="'.$row->id.'">
									<input type="hidden" name="email_type" value="followup">
								</div>
								<button type="submit" class="btn btn-primary btn-sm" style="width:116%; margin-left: -6px;">Send FollowUp Email</button>
							</form>';*/

                // $action .=  '<a href="'.route('visitor.detail').'?id='.$row->id.'" >
                //                     '.$row->name.'
                //             </a>';
                return $action;
            })
            ->editColumn('name', function($row) {
                $visitor = "visitors";

                $action =  '<a href="'.route('visitor.detail').'?id='.$row->id.'" >
                                        '.$row->name.'
                            </a>';
				// $action .= '<form action="'.route('send.email').'" method="post">
				// 				<input type="hidden" name="_token" value="'.csrf_token().'">
				// 				<div class="form-group">
				// 					<input type="hidden" name="visitor_id" id="visitor_id" value="'.$row->id.'">
				// 					<input type="hidden" name="email_type" value="primary">
				// 				</div>
				// 				<button type="submit" class="btn btn-primary btn-sm" style="margin-top: -24px;width: 75%;margin-left:-7px;">Send Primary Email</button>
				// 			</form>';
				// $action .= '<form action="'.route('send.email').'" method="post">
				// 				<input type="hidden" name="_token" value="'.csrf_token().'">
				// 				<div class="form-group">
				// 					<input type="hidden" name="visitor_id" id="visitor_id" value="'.$row->id.'">
				// 					<input type="hidden" name="email_type" value="followup">
				// 				</div>
				// 				<button type="submit" class="btn btn-primary btn-sm" style="width:75%; margin-left: -5px;">Send FollowUp Email</button>
				// 			</form>';


                return $action;
            })
            ->addColumn('image', function($row) {
                if($row->front_image == ''){
                    $image = '../no-image.png';
                }else{
                    $image = $row->front_image;
                }
                $images = substr($image, strpos($image, '/frenzincrm_api'));
                return '<span id="viewButton">

                            <img  src="'.$images.'" alt="" data-id="' . $row->id . '" class="img" style="height: 60px;" onclick="showImage(this)">
                        </span>';
            })
            ->editColumn('mobile_no', function($row) {

                $msg = DB::table('whatsapp_msg')->first();
                if(isset($msg) && $msg != null){
                    $whatsapp_message = $msg->message;
                    $mobile_number = $row->mobile_no;

                    $whatsappLink = "https://wa.me/{$mobile_number}?text=" . urlencode($whatsapp_message);

                    if(!empty($mobile_number)){
                        $send_msg =  $mobile_number.
                                    '<a href="' . $whatsappLink . '" target="_blank">
                                        <i class="fab fa-whatsapp" style="font-size:31px;color:#25D366;margin-left: 37px;"></i>
                                    </a>';

                        // $send_msg .='<br>
                        //             <br>
                        //             <span id="viewButton">
                        //                 <button class="btn btn-primary btn-sm" data-mobile_number="' . $mobile_number . '"  onclick="showfilewithimage(this)">
                        //                     Send Borchure
                        //                 </button>
                        //             </span>';
                        return $send_msg;
                    }
                }
            })
            ->addColumn('move_id', function($row) {
                $btn  = '<input type="checkbox" class="item-checkbox" data-name="id[]" onclick="getid(this)"
                        value="'.$row->id.'" data-id="'.$row->id.'" data-event_id="'.$row->event_id.'">';
                return $btn;
            })
            ->editColumn('event_name', function($row) {
                $event_id = $row->event_id;
                $eventIds = explode(',', $row->event_ids);
                $eventIds = array_filter($eventIds, function($id) use ($event_id) {
                    return $id != $event_id;
                });
                $eventIds = array_values($eventIds);
                $eventNames = [];                
                if (!empty($eventIds)) {
                    $eventNames = DB::table('events')->whereIn('id', $eventIds)->pluck('event_name')->toArray();
                }
                $eventNamesString = implode(', ', $eventNames);
                $styledEventNames = $eventNames ? "<span style='color: gray;'>$eventNamesString</span>" : '';
                return  "<span style='color: #007bff;'>$row->event_name</span>" . ($eventNames ? ' , ' . $styledEventNames : '');
            })
            ->addColumn('Visitor_Name', function($row) {

                // select count(*) as aggregate from `visitors` where (`visitors`.`mobile_no` = '%917567123402%' or `visitors`.`email` = '%sales@asitechnology.in%');
                $get_visitordata = DB::table('visitors')
                ->where(function($query) use ($row) {
                    $query->where('visitors.mobile_no', $row->mobile_no)
                        ->where('visitors.mobile_no','!=', '')
                        ->orWhere(function ($query) use ($row) {
                            $query->where('visitors.email', $row->email)
                                   ->where('visitors.email', '!=', '');
                    });
                })
                // ->where('visitors.mobile_no','!=',"")
                ->count();

                if(($get_visitordata == 1) || ($get_visitordata == 0)){
                    return "";
                }else{
                    $MultipleData = $get_visitordata;
                    if($MultipleData != ""){
                        $btn =  '<button  class="btn btn-sm btn-primary btn"  data-id="' . $row->id . '" data-email="'.$row->email.'" data-mobile_no="'.$row->mobile_no.'" onclick="show_visitor(this);">
                                    '.$MultipleData.'
                                </button>';
                        return $btn;
                    }
                }
            })
            ->rawColumns(['email','image','details','mobile_no','move_id','name','action1','edit','Visitor_Name','event_name']);
        }

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\Visitor $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(Visitor $model)
    {
        return $model->fetchAllvisitorbyevent($this->event_id,$this->category_id,$this->sub_category_id,$this->state_id,$this->city_id,$this->is_international,$this->country_id,$this->start_date,$this->end_date,$this->action,$this->follow_up_time,$this->follow_up_start_date,$this->follow_up_end_date,$this->sourceoflead);
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->setTableId('visitors-table')
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->dom('Bfrtip')
                    ->orderBy(1)
                    // ->stateSave(true)
                    ->buttons(
                        Button::make('excel')
                    );
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            //Column::computed('move_id')->title(''),
            Column::make('id')->title('ID')->searchable(true),
            Column::computed('image'),
            Column::computed('name')->title('Client Name')->searchable(true),
            Column::computed('company_name')->title('Company Name')->searchable(true),
            Column::computed('Visitor_Name')->title('Multiple Entries'),
            Column::make('event_name','events.event_name')->title('Event/Folder_Name'),
            Column::make('remarks')->title('Remarks'),
            // Column::make('CustomerName','users.CustomerName')->title('Team_Member'),
            Column::make('mobile_no')->title('Mobile_No')->searchable(true),
            //Column::make('email')->title('Email'),
			Column::computed('email')->addClass('text-center')->searchable(true),
            Column::make('follow_up_time')->title('Followup Date'),
            Column::make('visited_date')->title('Visited Date'),
            // Column::make('updated_at')->title('Date'),
            Column::computed('edit')->title(""),
            Column::computed('details')->title(""),
            Column::computed('action1')->title("")
            // ->exportable(false)
            // ->printable(false)
            // ->width(200)
            // ->addClass('text-center'),
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'Visitors_' . date('YmdHis');
    }
}
