<?php

namespace App\DataTables\USSD;

use App\UssdResponse;
use App\UssdService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\Services\DataTable;

class UssdResponseReportDatatable extends DataTable
{
    /**
     * Display ajax response.
     *
     * @param $query
     * @return JsonResponse
     */
    public function ajax()
    {
        return datatables()
            ->eloquent($this->query())
            ->addColumn('question_id', function ($row) {
                return $row->ussd_question->question ?? null;
            })->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()
    {
        //find the service
        $service = UssdService::query()->find($this->getServiceId());

        //get all the responses for the service ordered by the question number
        $query = UssdResponse::query()->where('code', $service->code)->orderBy('question_no');

        //if user is filtering by date, filter based on the dates
        if ($this->request()->get('from_date') && $this->request()->get('to_date')) {

            $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();

            if ($from_date->lte($to_date)) {
                $query = $query->where([
                    ['created_at', '>=', $from_date->toDateTimeString()],
                    ['created_at', '<=', $to_date->toDateTimeString()],
                ]);
            }
        }
        return $this->applyScopes($query);
    }


    /**
     * Gets the ussd service id selected by the user
     * @return mixed
     */
    private function getServiceId()
    {
        //get the ussd service from the uri
        $pathInfo = request()->getPathInfo(); //returns ie "/service/4/response/report"
        $pathParts = explode('/', $pathInfo); // places the ussd service id ie 4 at index 2
        //        [ 0 => "",
        //            1 => "service",
        //            2 => "4",
        //            3 => "response",
        //            4 => "report"
        //        ]
        return $pathParts[2];
    }

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

    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            'msisdn',
            'question_no',
            'question_id' => ['title' => 'Question'],
            'response',
            'created_at',
        ];
    }

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