<?php

namespace App\DataTables\Admin;

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

/**
 * Class PaymentDataTable
 * @package App\DataTables\Admin
 */
class PaymentDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public $user_id      = null;
    public $is_team_lead = null;
    public $team_id      = null;
    public $web          = null;
    public $website_id   = null;


    public function dataTable($query)
    {


        $query     = $query->with(['user','team']);
        $dataTable = new EloquentDataTable($query);
        // $dataTable->editColumn('comments', function (Payment $model) {

        //     return strip_tags($model->comments);

        // });
//        $dataTable->editColumn('image', function (Payment $model) {
//            if ($model->image) {
//                return '<img  style="width: 90px !important; height: 200px !important "   src="' . $model->image_url . '">';
//            }
//
//        });

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

        });
        $dataTable->editColumn('comments', function (Payment $model) {
            return str_limit(strip_tags($model->comments), 60);
        });
        $dataTable->editColumn('status', function (Payment $model) {
            if ($model->status == 1) {
                return "<span class='label label-success'>Paid</span>";
            } else {
                return '<span class="label label-info">Unpaid</span>';
            }

        });
        $dataTable->editColumn('type', function (Payment $model) {
            if ($model->type == 4) {
                return "<span class='label label-success'>Fresh</span>";
            } elseif ($model->type == 5) {
                return '<span class="label label-info">UpSell</span>';
            } elseif ($model->type == 6) {
                return '<span class="label label-warning">Existing</span>';
            } else {
                return '<span class="label label-default">N/A</span>';
            }

        });
        $dataTable->editColumn('platform', function (Payment $model) {
            if ($model->platform == 'Social Media') {
                return "<span class='label label-success'>Social Media</span>";
            } elseif ($model->platform == 'Ppc') {
                return '<span class="label label-info">PPC</span>';
            } else {
                return '<span class="label label-default">N/A</span>';
            }

        });
        $dataTable->editColumn('team.name', function (Payment $model) {
            // return '<a href="' . url('/admin/users/' . $model->user_id ?? "") . '" style="font-weight:bold">' . $model->user->name . '</a>';

            return isset($model->team) && ($model->team->name) ? '<a href="' . url('/admin/teams/' . $model->team_id) . '" style="font-weight:bold">' . $model->team->name . '</a> ' : 'N/A';
        });
        $dataTable->editColumn('price', function (Payment $model) {
            return $model->price . '(' . $model->currency . ')';
        });
        $dataTable->editColumn('user.name', function (Payment $model) {
            // return '<a href="' . url('/admin/users/' . $model->user_id ?? "") . '" style="font-weight:bold">' . $model->user->name . '</a>';

            return isset($model->user) && ($model->user->name) ? '<a href="' . url('/admin/users/' . $model->user_id) . '" style="font-weight:bold">' . $model->user->name . '</a> ' : 'N/A';
        });
        $dataTable->rawColumns(['status', 'image', 'action', 'user.name','type','platform','team.name','lead_type']);
        return $dataTable->addColumn('action', 'admin.payments.datatables_actions');
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\Payment $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(Payment $model)
    {
        if (\Entrust::hasRole('admin') || \Entrust::hasRole('super-admin') || \Entrust::hasRole('marketing')) {
            $model->newQuery();
            if ($this->month != null && $this->month > 0) {
                $model = $model->whereMonth('created_at', $this->month);
            }
            if ($this->user_id != null && $this->user_id > 0) {
                $model = $model->where('user_id', $this->user_id);
            }
            if (request()->year != null && request()->year > 0) {
                $model = $model->whereYear('created_at', request()->year);
            }
            if ($this->website_id != null && $this->website_id > 0) {

                $model = $model->where('website_id', $this->website_id);
            }  if (request()->team_id != null && request()->team_id > 0) {

                $model = $model->where('team_id', request()->team_id);
            }
            if (request()->type != null && request()->type > 0) {
                $model = $model->where('lead_type', request()->type);
            }
            if (request()->pay_type != null && request()->pay_type > 0) {
                $model = $model->where('type', request()->pay_type);
            }
            return $model;
        }
        $model = $model->newQuery();
//        if ($this->is_team_lead != null && $this->is_team_lead >= 0)
        if (\Entrust::hasRole('Team-Lead') && \Auth::user()->details->is_production == 0 && \Auth::user()->details->team_lead == 1 )
        {
//   dd('i am here');
//            $model = $model->where('team_id', $this->team_id)->orwhere('team_id', NULL);
            if ($this->month != null && $this->month > 0) {
                $model = $model->whereMonth('created_at', $this->month);
            }
            if ($this->user_id != null && $this->user_id > 0) {
                $model = $model->where('user_id', $this->user_id);
            }
            if (request()->year != null && request()->year > 0) {
                $model = $model->whereYear('created_at', request()->year);
            }
            if ($this->website_id != null && $this->website_id > 0) {

                $model = $model->where('website_id', $this->website_id);
            }
//dd(\Auth::user()->details->team_id);
            if (request()->type != null && request()->type > 0) {
                $model = $model->where('lead_type', request()->type);
            }
            if (request()->pay_type != null && request()->pay_type > 0) {
                $model = $model->where('type', request()->pay_type);
            }
            return $model->where('team_id',\Auth::user()->details->team_id)->orderBy('id','desc');
        }
        else {
            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->website_id != null && $this->website_id > 0) {

                $model = $model->where('website_id', $this->website_id);
            }
            if (request()->type != null && request()->type > 0) {
                $model = $model->where('lead_type', request()->type);
            }
            if (request()->pay_type != null && request()->pay_type > 0) {
                $model = $model->where('type', request()->pay_type);
            }
            return $model->where('user_id',\Auth::user()->id);
        }


    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        $buttons = [];
        if (\Entrust::can('payments.create') || \Entrust::hasRole('super-admin')) {
            $buttons = ['create'];
        }
        $buttons = array_merge($buttons, [
            // 'export',
            // 'print',
            'reset',
            'reload',
        ], Util::getFilterByMonth(), Util::getFilterByYear(),Util::getFilterByType(),Util::getFilterByPaymentType());
        if (\Entrust::hasRole('admin') || \Entrust::hasRole('super-admin') || \Entrust::hasRole('marketing') || \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
                ]
            ]);

        }

        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()
    {
        return [
            'id',
            'lead_id',
            'team.name',
            'lead_type',
            'user.name',
            'comments',
            'price',
            'status',
            'type',
            'platform',
            'created_at'
        ];
    }

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