<?php

namespace App\DataTables\Admin;

use App\Helper\Util;
use App\Models\Order;
use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\EloquentDataTable;

/**
 * Class OrderDataTable
 * @package App\DataTables\Admin
 */
class OrderDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */

    public $production_user_id = null; // production_user_id for production user_id
    public $sales_person_id    = null; // $sales_person_id for sales user_id
    public $month              = null; // month for all
    public $production_users   = null; //for production user filter
    public $sales_users        = null; // for sales user filter
    public $status_id          = null; // status id
    public $status             = null; // for status
    public $production_team    = null; // for production team filter
    public $sales_team         = null; // for sales team filter
    public $sales_team_id      = null;
    public $production_team_id = null;

    public function dataTable($query)
    {
        $dataTable = new EloquentDataTable($query);
        $dataTable->editColumn('user.name', function (Order $model) {
            return $model->user->name ?? "N/A";
        });
        $dataTable->editColumn('production_team.name', function (Order $model) {
            return $model->production_team->name ?? "N/A";
        });
        $dataTable->editColumn('lead_id', function (Order $model) {
            return '<a href="' . url('/admin/leads/' . $model->lead_id ?? '') . '" style="font-weight:bold">' . $model->lead_id ?? '' . '</a>';
        });
        $dataTable->editColumn('production_user.name', function (Order $model) {
            return $model->production_user->name ?? "N/A";
        });
        $dataTable->editColumn('portal', function (Order $model) {
            return str_limit($model->portal, 25) ?? "N/A";
        });
        $dataTable->editColumn('status', function (Order $model) {
            if ($model->status_id == Order::PENDING) {
                return "<span class='label label-info '>Pending</span>";
            } elseif ($model->status_id == Order::PROCESS) {
                return "<span class='label label-info '>Process</span>";
            } elseif ($model->status_id == Order::ONHOLD) {
                return "<span class='label label-primary '>OnHold</span>";
            } elseif ($model->status_id == Order::ASSIGNED) {
                return "<span class='label label-warning '>Assigned</span>";
            } elseif ($model->status_id == Order::CANCELLED) {
                return "<span class='label label-danger'>Assigned</span>";
            } else {
                return '<span class="label label-success">Completed</span>';
            }

        });
        $dataTable->rawColumns(['user.name', 'lead_id', 'production_team.name', 'status', 'production_user.name', 'action']);
        return $dataTable->addColumn('action', 'admin.orders.datatables_actions');
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\Order $model
     * @return \Illuminate\Database\Eloquent\Builder
     */

    public function query(Order $model)
    {

        if (\Entrust::hasRole('admin') || \Entrust::hasRole('super-admin')) {
            $model = $model->newQuery();
            if ($this->parent_order_id != null) {
                $model = $model->where('parent_order_id', $this->parent_order_id);
            }
            if ($this->month != null) {
                $model = $model->whereMonth('created_at', $this->month);
            }
            if ($this->production_team_id != null) {
                $model = $model->where('production_team_id', $this->production_team_id);
            }
            if ($this->sales_team_id != null) {
                $model = $model->where('sales_team_id', $this->sales_team_id);
            }
            if ($this->production_user_id != null) {
                $model = $model->where('production_user_id', $this->production_user_id);
            }
            if ($this->sales_person_id != null) {
                $model = $model->where('sales_person_id', $this->sales_person_id);
            }
            if ($this->status_id != null) {
                $model = $model->where('status_id', $this->status_id);
            }
        } else if (\Auth::user()->details->is_production_team_lead == 1 && \Auth::user()->details->is_production == 1) {
            $model = $model->newQuery();
            if ($this->parent_order_id != null) {
                $model = $model->where('parent_order_id', $this->parent_order_id);
            }
            $model = $model->where('production_team_id', \Auth::user()->details->production_team_id);

            if ($this->month != null) {
                $model = $model->whereMonth('created_at', $this->month);
            }
            if ($this->status_id != null) {
                $model = $model->where('status_id', $this->status_id);
            }
            if ($this->production_user_id != null) {
                $model = $model->where('production_user_id', $this->production_user_id);
            }


        } else if (\Auth::user()->details->is_production_team_lead == 1 && \Auth::user()->details->is_production == 0) {
            $model = $model->newQuery();
            if ($this->parent_order_id != null) {
                $model = $model->where('parent_order_id', $this->parent_order_id);
            }
            $model = $model->where('sales_team_id', \Auth::user()->details->team_id);
            if ($this->month != null) {
                $model = $model->whereMonth('created_at', $this->month);
            }
            if ($this->status_id != null) {
                $model = $model->where('status_id', $this->status_id);
            }
            if ($this->sales_person_id != null) {
                $model = $model->where('sales_person_id', $this->sales_person_id);
            }
        } else if (\Auth::user()->details->is_production == 0) {
            $model = $model->newQuery();
            if ($this->parent_order_id != null) {
                $model = $model->where('parent_order_id', $this->parent_order_id);
            }
            $model = $model->where('sales_person_id', \Auth::user()->details->user_id);
        } else {
            $model = $model->newQuery();
            if ($this->parent_order_id != null) {
                $model = $model->where('parent_order_id', $this->parent_order_id);
            }
            $model = $model->where('production_user_id', \Auth::user()->details->user_id);
        }
        return $model;
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */

    public function html()
    {
        $buttons = [];
        if (\Entrust::can('orders.create') || \Entrust::hasRole('super-admin')) {
            $buttons = ['create'];
        } elseif (\Auth::user()->details->is_production_team_lead == 1

            || \Auth::user()->details->is_production_team_lead != 1) {
            $buttons = [];
        }
        $buttons = array_merge($buttons, [

        ], Util::getFilterByMonth());
        if (\Entrust::hasRole('admin') || \Entrust::hasRole('super-admin')) {

            // production user Filter start
            if ($this->production_users != null) {
                foreach ($this->production_users as $key => $user) {
                    $url            = Util::getUrl(['production_user_id' => $key]);
                    $catButtonsss[] = [
                        "name"   => "production_user_" . $key,
                        "text"   => $user,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-users'></i> Production users",
                        "buttons" => $catButtonsss
                    ]
                ]);;
            }
            // sales user Filter start
            if ($this->sales_users != null) {
                foreach ($this->sales_users as $key => $user) {
                    $url            = Util::getUrl(['sales_person_id' => $key]);
                    $catButtonsss[] = [
                        "name"   => "sales_person_" . $key,
                        "text"   => $user,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-users'></i> Sales users",
                        "buttons" => $catButtonsss
                    ]
                ]);;
            }
            // team Filter close


            // status Filter start
            if ($this->status != null) {

                foreach ($this->status as $key => $status_names) {

                    $url          = Util::getUrl(['status_id' => $key]);
                    $status_btn[] = [
                        "name"   => "status_" . $key,
                        "text"   => $status_names,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-users'></i> Status",
                        "buttons" => $status_btn
                    ]
                ]);;
            }
            if ($this->production_team != null) {

                foreach ($this->production_team as $key => $pro_team_name) {

                    $url            = Util::getUrl(['production_team_id' => $key]);
                    $pro_team_btn[] = [
                        "name"   => "production_team_" . $key,
                        "text"   => $pro_team_name,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-users'></i> Production Team",
                        "buttons" => $pro_team_btn
                    ]
                ]);;
            }
            if ($this->sales_team != null) {

                foreach ($this->sales_team as $key => $sale_team_name) {

                    $url             = Util::getUrl(['sales_team_id' => $key]);
                    $sale_team_btn[] = [
                        "name"   => "sales_team_" . $key,
                        "text"   => $sale_team_name,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-users'></i> Sales Team",
                        "buttons" => $sale_team_btn
                    ]
                ]);;
            }
            // status Filter close
        } else if (\Auth::user()->details->is_production == 1 && \Auth::user()->details->is_production_team_lead == 1) {
            //production user that belongs to his team
            if ($this->production_users != null) {
                foreach ($this->production_users as $key => $user) {
                    $url            = Util::getUrl(['production_user_id' => $key]);
                    $catButtonsss[] = [
                        "name"   => "production_user_" . $key,
                        "text"   => $user,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-users'></i> Production users",
                        "buttons" => $catButtonsss
                    ]
                ]);;
            }
            if ($this->status != null) {

                foreach ($this->status as $key => $status_names) {

                    $url          = Util::getUrl(['status_id' => $key]);
                    $status_btn[] = [
                        "name"   => "status_" . $key,
                        "text"   => $status_names,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-users'></i> Status",
                        "buttons" => $status_btn
                    ]
                ]);;
            }

        } else if (\Auth::user()->details->is_production_team_lead == 1 && \Auth::user()->details->is_production == 0) {
            if ($this->sales_users != null) {
                foreach ($this->sales_users as $key => $user) {
                    $url            = Util::getUrl(['sales_person_id' => $key]);
                    $catButtonsss[] = [
                        "name"   => "sales_person_" . $key,
                        "text"   => $user,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-users'></i> Sales users",
                        "buttons" => $catButtonsss
                    ]
                ]);;
            }
            if ($this->status != null) {

                foreach ($this->status as $key => $status_names) {

                    $url          = Util::getUrl(['status_id' => $key]);
                    $status_btn[] = [
                        "name"   => "status_" . $key,
                        "text"   => $status_names,
                        "action" => "function(e, dt, button, config) { window.location.href='" . $url . "' }"
                    ];
                }
                $buttons = array_merge($buttons, [
                    [
                        "extend"  => "collection",
                        "text"    => "<i class='fa fa-users'></i> Status",
                        "buttons" => $status_btn
                    ]
                ]);;
            }
        }
        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,
            ]));
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        if (\Auth::user()->details->is_production == 1) {

            return [
                'id'                   => ['title' => 'Order Id'],
//                'lead_id',
                'production_user.name' => ['title' => 'Production User Name'],
                'production_team.name' => ['title' => 'Production Team Name'],
                'portal'               => ['title' => 'Subject'],
//                'created_at',
                'user.name'            => ['title' => 'Sale User Name'],
//            'link',
//                'deadline',

                'status' => ['title' => 'Status', 'searchable' => false],
            ];
        } else {

            return [
                'id'                   => ['title' => 'Order Id'],
                'lead_id',
//                'production_user.name' => ['title' => 'Production User Name'],
                'production_team.name' => ['title' => 'Production Team Name'],
                'portal'               => ['title' => 'Subject'],
                'created_at',
                'user.name'            => ['title' => 'Sale User Name'],
//            'link',
                'deadline',

                'status' => ['title' => 'Status', 'searchable' => false],
            ];
        }

//        elseif (\Entrust::hasRole('admin') || \Entrust::hasRole('super-admin')) {
//            return [
//                'id',
//                'lead_id',
//                'user.name'            => ['title' => 'Sale User Name'],
//                'production_team.name' => ['title' => 'Production Team Name'],
//                'link',
//                'user_name',
//                'deadline',
////                'status'
//            ];
//        } else {
//            return [
//                // 'production_user_id',
//                'lead_id',
//                'user.name'            => ['title' => 'Sale User Name'],
//                'production_team.name' => ['title' => 'Production Team Name'],
//                'link',
//                'user_name',
//
//                'deadline',
////                'status'
//            ];
//        }
    }

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