<?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;
use App\Models\Product;

class ClientVisitorsDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {

        return datatables()
            ->eloquent($query)
            ->addColumn('name', function($row) {
                $visitor = "visitors";

                $action =  '<a href="'.route('visitor.detail').'?id='.$row->visitors_id.'" >
                                        '.$row->name.'
                            </a>';

                return $action;
            })
            ->addColumn('company_name', function($row) {
                return $row->company_name;
            })
            ->addColumn('email', function($row) {
                return $row->email;
            })
            ->addColumn('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>';

                        return $send_msg;
                    }
                }else{
                    return $row->mobile_no;
                }
            })
            ->addColumn('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 : '');
            })
            ->editColumn('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;
                    }
                }
            })
            ->addColumn('visit_action', function($row) {
                return $row->visit_action;
            })
            ->addColumn('CustomerName', function($row) {
                return $row->CustomerName;
            })

            ->addColumn('product_data', function($row) {

                $productname = '';
                $products = $row->products;
                if(count($products) > 0){
                    for ($i=0; $i < count($products); $i++) {
                        $fk_product_id = $products[$i]->fk_product_id;
                        $Product = Product::find($fk_product_id);
                        $productname = $productname . $Product->name. '<br>';
                    }
                }
                return $productname;
            })

            ->rawColumns(['name','event_name','mobile_no','product_data']);
        }

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

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

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        $columns = [
            Column::make('fk_visitor_id')->title('ID')->searchable(true),

        ];
        $contactFieldValue = session('contact_detail_fields.name');

        if (empty($contactFieldValue) || !isset($contactFieldValue['hide']) || $contactFieldValue['hide'] === false) {
            $title = empty($contactFieldValue['display']) ? 'Client Name' : $contactFieldValue['display'];
            $columns[] = Column::make('name','visitors.name')->title($title)->searchable(true);
        }
        $contactFieldValue = session('contact_detail_fields.company_name');

        if (empty($contactFieldValue) || !isset($contactFieldValue['hide']) || $contactFieldValue['hide'] === false) {
            $title = empty($contactFieldValue['display']) ? 'Company Name' : $contactFieldValue['display'];
            $columns[] =  Column::make('company_name','visitors.company_name')->title($title)->searchable(true);
        }
        $columns = array_merge($columns, [
            Column::computed('event_name','events.event_name')->title('Event/Folder_Name')->searchable(false),
            Column::make('CustomerName','users.CustomerName')->title('Team Member')->searchable(true)]);
            $contactFieldValue = session('contact_detail_fields.mobile1');

            if (empty($contactFieldValue) || !isset($contactFieldValue['hide']) || $contactFieldValue['hide'] === false) {
                $title = empty($contactFieldValue['display']) ? 'Mobile_No' : $contactFieldValue['display'];
                $columns[] = Column::make('mobile_no','visitors.mobile_no')->title($title)->searchable(true);
            }

                //Column::make('email')->title('Email'),
                $contactFieldValue = session('contact_detail_fields.email1');

                if (empty($contactFieldValue) || !isset($contactFieldValue['hide']) || $contactFieldValue['hide'] === false) {
                    $title = empty($contactFieldValue['display']) ? 'Email' : $contactFieldValue['display'];
                    $columns[] = Column::make('email','visitors.email')->title($title)->addClass('text-center')->searchable(true);
                }
            $columns = array_merge($columns, [

            Column::make('visit_time')->title('Visited Date')->searchable(true)
            ]);

            $contactFieldValue = session('contact_detail_fields.action');

            if (empty($contactFieldValue) || !isset($contactFieldValue['hide']) || $contactFieldValue['hide'] === false) {
                $title = empty($contactFieldValue['display']) ? 'Visit Action' : $contactFieldValue['display'];
                $columns[] =  Column::make('visit_action','visit_data.action')->title($title)->searchable(true);
            }

            $contactFieldValue = session('contact_detail_fields.products');

            if (empty($contactFieldValue) || !isset($contactFieldValue['hide']) || $contactFieldValue['hide'] === false) {
                $title = empty($contactFieldValue['display']) ? 'Products' : $contactFieldValue['display'];
                $columns[] =  Column::make('product_data')->title($title)->searchable(true);
            }
            $contactFieldValue = session('contact_detail_fields.remarks');

            if (empty($contactFieldValue) || !isset($contactFieldValue['hide']) || $contactFieldValue['hide'] === false) {
                $title = empty($contactFieldValue['display']) ? 'Remarks' : $contactFieldValue['display'];
                $columns[] =  Column::make('visit_remarks')->title($title)->searchable(false);
            }


        return $columns;
    }

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