<?php

namespace App\DataTables\Admin;

use App\Helper\Util;
use App\Models\Lead;
use App\Models\LeadTeam;
use App\Models\Team;
use App\Models\Website;
use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\EloquentDataTable;

/**
 * Class LeadDataTable
 * @package App\DataTables\Admin
 */
class LeadDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public $user_ids       = null;
    public $team_id        = null;
    public $teams          = null;
    public $web            = null;
    public $website_id     = null;
    public $users          = null;
    public $lead_status    = null;
    public $lead_status_id = null;

//    public $platform       = null;


    public function dataTable($query)
    {
        $query     = $query->with(['user', 'web']);
        $dataTable = new EloquentDataTable($query);
        $dataTable->editColumn('stats.name', function (Lead $model) {
            if ($model->status_id == 1) {
                return "<span class='label label-info '> " . $model->stats->name ?? '' . "</span>";
            } elseif ($model->status_id == 3) {
                return '<span class="label label-success">' . $model->stats->name ?? '' . '</span>';
            }elseif ($model->status_id == 4) {
                return '<span class=" label label-warning">' . $model->stats->name ?? '' . '</span>';
            }elseif ($model->status_id == 5) {
                return '<span class="label label-primary">' . $model->stats->name ?? '' . '</span>';
            }elseif ($model->status_id == 6) {
                return '<span class="label label-default">' . $model->stats->name ?? '' . '</span>';
            }elseif ($model->status_id == 7) {
                return '<span class="label label-info">' . $model->stats->name ?? '' . '</span>';
            } else {
                return '<span class="label label-danger">' . $model->stats->name ?? '' . '</span>';
            }

        });
        $dataTable->editColumn('web.name', function (Lead $model) {
            return $model->web->name ?? '';

        });
        $dataTable->editColumn('type', function (Lead $model) {
            if ($model->type == 10) {
                return "<span class='label label-info '> Certification</span>";
            } elseif ($model->type == 20) {
                return '<span class="label label-success">Academic Exam</span>';
            }elseif ($model->type == 30) {
                return '<span class=" label label-warning">Academic Class</span>';
            }elseif ($model->type == 40) {
                return '<span class=" label label-danger">Others</span>';
            }else{
                return '<span class=" label label-default">N/A</span>';
            }

        });
        $dataTable->editColumn('user.name', function (Lead $model) {
            return $model->user->name ?? '';
        });
        $dataTable->editColumn('comments', function (Lead $model) {
            return str_limit(strip_tags($model->comments), 20);
        });

        $dataTable->editColumn('phone', function (Lead $model) {
            if ($model->phone) {
//                return '<button class="show-phone-btn" data-phone="' . $model->phone . '">Show Phone</button>';
                return '<button class="label label-info show-phone-btn" data-phone="' . $model->phone . '">Show Phone</button>';
            }
            return '';
        });

        $dataTable->rawColumns(['stats.name', 'action', 'comments','phone','type']);
        return $dataTable->addColumn('action', 'admin.leads.datatables_actions');
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\Lead $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(Lead $model)
    {

        $user = \Auth::user();
        if (\Entrust::hasRole('admin') || \Entrust::hasRole('super-admin')) {
//            dd($this->user_id);
            $model = $model->newQuery();
            if ($this->lead_status_id != null) {
                $model = $model->where('status_id', $this->lead_status_id);
            }
            if ($this->user_id != null && $this->user_id > 0) {
                $model = $model->where('user_id', $this->user_id);
            }
            if ($this->website_id != null && $this->website_id > 0) {

                $model = $model->where('website_id', $this->website_id);
            }
            if ($this->month != null && $this->month > 0) {
                $model = $model->whereMonth('created_at', $this->month);
            }
            if (request()->year != null && request()->year > 0) {
                $model = $model->whereYear('created_at', request()->year);
            }
            if ($this->platform != null) {
                $model = $model->where('lead_status', $this->platform);
            }
            if ($this->team_id != null && $this->team_id > 0) {
                $leads = LeadTeam::where('team_id', $this->team_id)->pluck('lead_id');
                $model = $model->whereIn('id', $leads);
            }
            if (request()->type != null && request()->type > 0) {
                $model = $model->where('type', request()->type);
            }
            return $model->orderBy('id','desc');
        }
        if (\Entrust::hasRole('marketing')) {
//            dd($this->user_id);
            $model = $model->newQuery();
            if ($this->lead_status_id != null) {
                $model = $model->where('status_id', $this->lead_status_id);
            }
            if ($this->user_id != null && $this->user_id > 0) {
                $model = $model->where('user_id', $this->user_id);
            }
            if ($this->website_id != null && $this->website_id > 0) {

                $model = $model->where('website_id', $this->website_id);
            }
            if ($this->month != null && $this->month > 0) {
                $model = $model->whereMonth('created_at', $this->month);
            }
            if (request()->year != null && request()->year > 0) {
                $model = $model->whereYear('created_at', request()->year);
            }
            if ($this->team_id != null && $this->team_id > 0) {
                $leads = LeadTeam::where('team_id', $this->team_id)->pluck('lead_id');
                $model = $model->whereIn('id', $leads);
            }
            if ($this->platform != null) {
                $model = $model->where('lead_status', $this->platform);
            }
            if (request()->type != null && request()->type > 0) {
                $model = $model->where('type', request()->type);
            }
            return $model;
        }
        elseif ($user->details->team_lead == 1) {
            $model = $model->newQuery();
            if ($this->team_id != null && $this->team_id > 0) {
                $websiteIds = Website::where('status', 0)->pluck('id')->toArray();
//                $model = $model->whereIn('team_id', $this->team_id);
                $leads = LeadTeam::where('team_id', $this->team_id)->orWhere('team_id', Team::POOL)->pluck('lead_id');
//                $model = $model->whereIn('id', $leads)->orWhere('team_id', '=', Team::POOL);
//                $model = $model->whereIn('id', $leads);
                $u_leads = Lead::where('user_id', \Auth::id())->pluck('id');
                $leads   = array_merge($leads->toArray(), $u_leads->toArray());

                $model = $model->whereIn('id', $leads)->whereNotIn('website_id', $websiteIds);
            }
            if ($this->lead_status_id != null) {
                $model = $model->where('status_id', $this->lead_status_id);
            }
            if ($this->month != null && $this->month > 0) {
                $model = $model->whereMonth('created_at', $this->month);
            }
            if (request()->year != null && request()->year > 0) {
                $model = $model->whereYear('created_at', request()->year);
            }
            if ($this->user_id != null && $this->user_id > 0) {
                if ($this->team_id == \Auth::user()->details->team_id) {

                    $model = $model->where('user_id', $this->user_id);
                }

            }
            if ($this->website_id != null && $this->website_id > 0) {
                $model = $model->where('website_id', $this->website_id);
            }
            if ($this->platform != null) {
                $model = $model->where('lead_status', $this->platform);
            }
            if (request()->type != null && request()->type > 0) {
                $model = $model->where('type', request()->type);
            }
            return $model;
        }
        else {
            $model = $model->newQuery();

            if ($this->team_id != null && $this->team_id > 0) {
                $websiteIds = Website::where('status', 0)->pluck('id')->toArray();
                $leads      = LeadTeam::where('team_id', $this->team_id)->orWhere('team_id', Team::POOL)->pluck('lead_id');
                $u_leads    = Lead::where('user_id', \Auth::id())->pluck('id');
                $leads      = array_merge($leads->toArray(), $u_leads->toArray());

                $model = $model->whereIn('id', $leads)->whereNotIn('website_id', $websiteIds);
//                $model = $model->whereIn('team_id', $this->team_id);

            }
            if ($this->lead_status_id != null) {
                $model = $model->where('status_id', $this->lead_status_id);
            }
            if ($this->month != null && $this->month > 0) {

                $model = $model->whereMonth('created_at', $this->month);
            }
            if (request()->year != null && request()->year > 0) {
                $model = $model->whereYear('created_at', request()->year);
            }
            if ($this->user_id != null && $this->user_id > 0) {
                if ($this->user_id == \Auth::id()) {
                    $model = $model->where('user_id', $this->user_id);
                }
            }
            if ($this->platform != null) {
                $model = $model->where('lead_status', $this->platform);
            }
            if (request()->type != null && request()->type > 0) {
                $model = $model->where('type', request()->type);
            }

            return $model->orderBy('id','desc');
        }


    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        $buttons = [];
        if (\Entrust::can('leads.create') || \Entrust::hasRole('super-admin') || \Entrust::hasRole('marketing')) {
            $buttons = ['create'];
        } else {
            $buttons = ['create'];
        }
        $buttons = array_merge($buttons, [
//            'export',
            // 'print',

        ], Util::getFilterByUser(), Util::getFilterByMonth(), Util::getFilterByYear(), Util::getFilterByPlatform(),Util::getFilterByType());
        if ($this->lead_status != null) {
            foreach ($this->lead_status as $key => $status) {
                $url                = Util::getUrl(['lead_status_id' => $key]);
                $catButtonsstatus[] = [
                    "name"   => "lead_status_" . $key,
                    "text"   => $status,
                    "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                ];
            }
            $buttons = array_merge($buttons, [
                [
                    "extend"  => "collection",
                    "text"    => "<i class='fa fa-filter'></i> Filter by status",
                    "buttons" => $catButtonsstatus
                ]
            ]);

        }

        if (\Entrust::hasRole('admin') || \Entrust::hasRole('super-admin') || \Entrust::hasRole('marketing')) {

            if ($this->web != null) {

                foreach ($this->web as $key => $wweb) {
                    $url             = Util::getUrl(['website_id' => $key]);
                    $catButtonsweb[] = [
                        "name"   => "website_" . $key,
                        "text"   => $wweb,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-filter'></i> Filter By website",
                        "buttons" => $catButtonsweb
                    ]
                ]);

            }
            if ($this->users != null) {

                foreach ($this->users as $key => $name) {
                    $url              = Util::getUrl(['user_id' => $key]);
                    $catButtonsuser[] = [
                        "name"   => "website_" . $key,
                        "text"   => $name,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-filter'></i> Filter by users",
                        "buttons" => $catButtonsuser
                    ]
                ]);

            }

            if ($this->teams != null) {
                foreach ($this->teams as $key => $name) {
                    $url              = Util::getUrl(['team_id' => $key]);
                    $catButtonsteam[] = [
                        "name"   => "team_id" . $key,
                        "text"   => $name,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-filter'></i> Filter by teams",
                        "buttons" => $catButtonsteam
                    ]
                ]);

            }
//            if ($this->lead_status != null) {
//                foreach ($this->lead_status as $key => $status) {
//                    $url                = Util::getUrl(['lead_status_id' => $key]);
//                    $catButtonsstatus[] = [
//                        "name"   => "lead_status_" . $key,
//                        "text"   => $status,
//                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
//                    ];
//                }
//                $buttons = array_merge($buttons, [
//                    [
//                        "extend"  => "collection",
//                        "text"    => "<i class='fa fa-filter'></i> Filter by status",
//                        "buttons" => $catButtonsstatus
//                    ]
//                ]);
//
//            }

        } elseif (\Auth::user()->details->team_lead == 1) {

            if ($this->users != null) {

                foreach ($this->users as $key => $name) {
                    $url              = Util::getUrl(['user_id' => $key]);
                    $catButtonsuser[] = [
                        "name"   => "website_" . $key,
                        "text"   => $name,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-filter'></i> Filter by users",
                        "buttons" => $catButtonsuser
                    ]
                ]);

            }
            if ($this->web != null) {

                foreach ($this->web as $key => $wweb) {
                    $url             = Util::getUrl(['website_id' => $key]);
                    $catButtonsweb[] = [
                        "name"   => "website_" . $key,
                        "text"   => $wweb,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-filter'></i> Filter By website",
                        "buttons" => $catButtonsweb
                    ]
                ]);

            }
            if ($this->web != null) {

                foreach ($this->web as $key => $wweb) {
                    $url             = Util::getUrl(['website_id' => $key]);
                    $catButtonsweb[] = [
                        "name"   => "website_" . $key,
                        "text"   => $wweb,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-filter'></i> Filter By website",
                        "buttons" => $catButtonsweb
                    ]
                ]);

            }
        }

        return $this->builder()
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->addAction(['width' => '80px', 'printable' => false])
            ->parameters(array_merge(Util::getDataTableParams(), [
                'dom'     => 'Blfrtip',
                'order'   => [[0, 'desc']],
                'buttons' => $buttons,
                'stateSave' => true,
//                'lengthMenu' => [[10, 25, 50, -1], [10, 25, 50, "All"]], // Customize the entries per page dropdown
                'language' => [
                    'paginate' => [
                        'previous' => '&laquo;',
                        'next' => '&raquo;',
                        'first' => '&laquo;&laquo;',
                        'last' => '&raquo;&raquo;',
                    ],
                    'lengthMenu' => 'Per page: _MENU_',
                ],
            ]));
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            'id',
            'name',
            'phone',
            'email',
            'type',
            'comments',
            'lead_status' => ['title' => 'Platform', 'searchable' => false],
            'stats.name'  => ['title' => 'Lead Status', 'searchable' => false],
            'web.name'    => ['title' => 'Web Name', 'searchable' => true],
            'user.name'   => ['title' => 'Lead Owner Name', 'searchable' => true],
            'created_at'
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'leadsdatatable_' . time();
    }
}