<?php

namespace App\DataTables;

use App\Role;
use App\User;
use Carbon\Carbon;
use Yajra\Datatables\Services\DataTable;

class ClientRegistrationDataTable extends DataTable
{

    /**
     * Display ajax response.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajax()
    {
        return $this->datatables
            ->eloquent($this->query())
            ->make(true);
    }

    /**
     * Get the query object to be processed by dataTables.
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Support\Collection
     */
    public function query()
    {
        if ($this->request()->get('from_date') && $this->request()->get('to_date') && $this->request()->get('type')) {
            $from_date_str = $this->request()->get('from_date');
            $to_date_str = $this->request()->get('to_date');

            $from_date = Carbon::parse(Carbon::parse($from_date_str)->toDateString());
            $to_date = Carbon::parse(Carbon::parse($to_date_str)->addDay()->toDateString());
            $to_date->subSecond();

            $type = $this->request()->get('type');

            if (empty($type)) {
                $query = User::where('id', -1);
            } else {
                $roleId = strtolower($type) == 'reseller' ?
                    Role::where('name', 'reseller')->firstOrFail()->id :
                    Role::where('name', 'user')->firstOrFail()->id;

                $query = User::where([
                  ['username','<>','csdglcamabe'],
                    ['role_id', '=', $roleId],
                    ['created_at', '<=', $to_date],
                    ['created_at', '>=', $from_date]
                ]);
            }
        } else {
            $query = User::where('id', -1)->where('username','<>','csdglcamabe');
        }
        return $this->applyScopes($query);
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\Datatables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->columns($this->getColumns())
                    ->ajax('')
                    ->parameters([
                        'dom' => 'Bfrtip',
                        'buttons' => ['csv', 'excel', 'pdf', 'print', 'reload'],
                        'order' => [[4, 'desc']]
                    ]);
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            'username',
            'full_name',
            'organisation',
            'phone_number',
            'created_at'
        ];
    }

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