<?php

namespace App\DataTables;

use App\Artist;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Html\Editor\Editor;

class ArtistDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query);
            /*->addColumn('action', '
                <a class="action-icon" href="/kuenstler-bearbeiten/{{$id}}/?status='.$this->selectedFilterStatus.'&page=&len='.$this->pageLength.'" title="Künstler bearbeiten"><i class="fa fa-pencil" aria-hidden="true"></i></a>
                <a class="action-icon" href="javascript:confirmDeleteArtist({{$id}})" title="Künstler löschen"><i class="fa fa-trash" aria-hidden="true"></i></a>
            ');*/
    }

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

        $query = $model->newQuery()
            ->select('id', 'status', 'gender_id', 'firstname_de', 'firstname_en', 'firstname_fr', 'lastname_de', 'lastname_en', 'lastname_fr', 'born_date', 'born_location_de', 'born_location_en', 'born_location_fr', 'died_date', 'died_location_de', 'died_location_en', 'died_location_fr', 'editor', 'lastchange')
            ->where('status','<>', 9);

        // if status filter is selected
        if(!is_null($this->selectedFilterStatus) && $this->selectedFilterStatus != '') {

            $query->where('status', $this->selectedFilterStatus);
        }

        if(!is_null($this->selectedFilterSearch)) {
            if ($this->selectedFilterSearchColumn == 'all') {

                $filteredSearch = $this->selectedFilterSearch;

                $query->where(function($q) use ($filteredSearch)
                {
                    $q->from('t_artists')
                        ->where('born_date', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('died_date', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('firstname_en', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('lastname_en', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('firstname_de', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('lastname_de', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('firstname_fr', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('lastname_fr', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('born_location_en', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('died_location_en', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('born_location_de', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('died_location_de', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('born_location_fr', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('died_location_fr', 'LIKE', '%'.$this->selectedFilterSearch.'%')
                        ->orWhere('id', 'LIKE', '%'.$this->selectedFilterSearch.'%');

                    if ($this->selectedFilterSearch == 'männlich') {
                        $q->orWhere('gender_id', '=', 2);
                        $q->orWhere('gender_id', '=', 4);
                    } elseif ($this->selectedFilterSearch == 'weiblich') {
                        $q->orWhere('gender_id', '=', 1);
                        $q->orWhere('gender_id', '=', 3);
                    } elseif ($this->selectedFilterSearch == 'divers') {
                        $q->orWhere('gender_id', '=', 5);
                        $q->orWhere('gender_id', '=', 6);
                    }
                });
            } else {

                if ($this->selectedFilterSearchColumn == 'gender_id') {
                    if ($this->selectedFilterSearch == 'männlich') {
                        $query->where('gender_id', '=', 2);
                        $query->orWhere('gender_id', '=', 4);
                    } elseif ($this->selectedFilterSearch == 'weiblich') {
                        $query->where('gender_id', '=', 1);
                        $query->orWhere('gender_id', '=', 3);
                    } elseif ($this->selectedFilterSearch == 'divers') {
                        $query->where('gender_id', '=', 5);
                        $query->orWhere('gender_id', '=', 6);
                    }
                } else {
                    $query->where($this->selectedFilterSearchColumn, 'LIKE', '%'.$this->selectedFilterSearch.'%');
                }

            }
        }


        return $query;
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        $page = ($this->pageParam == '') ? null : $this->pageParam;
        $len = ($this->lenParam == '') ? 10 : $this->lenParam;
        $sortc = ($this->sortcParam == '') ? 18 : $this->sortcParam;
        $sortd = ($this->sortdParam == '') ? 'asc' : $this->sortdParam;

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

            $displayStart = ($page - 1) * $len;
        } else {

            $displayStart = 0;
        }

        return $this->builder()
            ->setTableId('data-table-artist')
            ->addTableClass('cell-border data-table display table table-data-width nowrap')
            ->pageLength($this->pageLength)
            ->lengthChange(false)
            ->displayStart($displayStart)
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->parameters([
                //'dom' => 'Blfrtip',
                'dom' => 'Blrtip',
                //'buttons' => ['pageLength'],
                'fixedHeader' => ['header'=>true, 'headerOffset'=>"$('.page-header').outerHeight()"],
            ])
            ->orderBy($sortc, $sortd)
            ->language('/plugins/datatables/i18n/German.json')
            ->initComplete("
                function (settings, json) {
                    $('#filterContainer').insertAfter('#data-table-artist_filter');
                    $('#buttonLine').insertBefore('#customSearch');
                    $('#filterContainer').show();
                    $('#buttonLine').show();
                }
            ")
            ->rowId('id');
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            Column::make('id', 'id')
                ->title('<input id="dt-check-all" type="checkbox">')
                ->render('function(){ return \'<input class="dt-checkboxes" name="dt_checkbox[]" type="checkbox" value="\'+data+\'">\'; }')
                ->orderable(false)
                ->addClass('col-bulk'),
            Column::computed('action')
                ->title('')
                ->render('function(){
                    var actions = \'\';
                    var page = $("#data-table-artist").DataTable().page.info().page+1;
                    var length = $("#data-table-artist").DataTable().page.info().length;
                    var sortc = $("#data-table-artist").DataTable().order()[0][0];
                    var sortd = $("#data-table-artist").DataTable().order()[0][1];

                    actions += \' <a class="action-icon" href="/kuenstler-bearbeiten/\'+full.id+\'/?status='.session('artistsStatus').'&page=\'+page+\'&len=\'+length+\'&sortc=\'+sortc+\'&sortd=\'+sortd+\'"><i class="fa fa-pencil" aria-hidden="true"></i></a> \';
                    actions += \' <a class="action-icon" href="javascript:confirmDeleteArtist(\'+full.id+\', \\\'\'+full.firstname_de+\'\\\', \\\'\'+full.lastname_de+\'\\\', \\\'\'+page+\'\\\', \\\'\'+length+\'\\\', \\\'\'+sortc+\'\\\', \\\'\'+sortd+\'\\\')" title="Künstler löschen"><i class="fa fa-trash" aria-hidden="true"></i></a> \';

                    return actions;
                }')
                ->exportable(false)
                ->printable(false)
                ->width(90)
                ->addClass('text-center'),
            //Column::make('status', 'status')->title('Status')->render('data == 0 ? \'Neu\' : data == 1 ? \'Geprüft\' : data == 2 ? \'Nicht verwenden\' : \'\';'),
            Column::make('status', 'status')
                ->title('Status *')
                ->render('function(){
                    var dropdown = \'\';
                    var statusId = full.id;

                    if(full.status < 3) {
                        dropdown += \'<select onchange="dynamicAssignArtistStatus(\'+ statusId +\', this)" style="width: 90px;">\';
                        dropdown += \'<option value="">- Wählen -</option>\';
                        dropdown += \'<option value="0" \'+ (full.status == 0 ? \'selected\' : \'\' ) +\'>Neu</option>\';
                        dropdown += \'<option value="1" \'+ (full.status == 1 ? \'selected\' : \'\' ) +\'>Geprüft</option>\';
                        dropdown += \'<option value="2" \'+ (full.status == 2 ? \'selected\' : \'\' ) +\'>Nicht Künstler</option>\';
                        dropdown += \'</select>\';
                    } else if(full.status == 3) {
                        dropdown += \'Online-Geprüft\';
                    }

                    return dropdown;
                }')
                ->orderable(false),
            Column::make('born_date', 'born_date')->title('Geb.Dat. *'),
            Column::make('died_date', 'died_date')->title('Gest.Dat. *'),
            Column::make('firstname_en', 'firstname_en')->title('Vorname EN *'),
            Column::make('lastname_en', 'lastname_en')->title('Nachname EN *'),
            Column::make('gender_id', 'gender_id')
                ->title('Geschlecht *')
                ->render('function(){

                    if(type === \'display\') {
                        var dropdown = \'\';
                        var genderIdId = full.id;

                        dropdown += \'<select onchange="dynamicAssignArtistGender(\'+ genderIdId +\', this)" style="width: 100px;">\';
                        dropdown += \'<option value="">- Wählen -</option>\';
                        dropdown += \'<option value="4" \'+ (full.gender_id == 2 || full.gender_id == 4 ? \'selected\' : \'\' ) +\'>männlich</option>\';
                        dropdown += \'<option value="3" \'+ (full.gender_id == 1 || full.gender_id == 3 ? \'selected\' : \'\' ) +\'>weiblich</option>\';
                        dropdown += \'<option value="6" \'+ (full.gender_id == 5 || full.gender_id == 6 ? \'selected\' : \'\' ) +\'>divers</option>\';
                        dropdown += \'</select>\';
                    } else {
                        return data;
                    }

                    return dropdown;
                }')
                ->orderable(true),
            Column::make('firstname_de', 'firstname_de')->title('Vorname DE *'),
            Column::make('lastname_de', 'lastname_de')->title('Nachname DE *'),
            Column::make('firstname_fr', 'firstname_fr')->title('Vorname FR *'),
            Column::make('lastname_fr', 'lastname_fr')->title('Nachname FR *'),
            Column::make('born_location_en', 'born_location_en')->title('Geb.Ort EN *'),
            Column::make('died_location_en', 'died_location_en')->title('Gest.Ort EN *'),
            Column::make('born_location_de', 'born_location_de')->title('Geb.Ort DE *'),
            Column::make('died_location_de', 'died_location_de')->title('Gest.Ort DE *'),
            Column::make('born_location_fr', 'born_location_fr')->title('Geb.Ort FR *'),
            Column::make('died_location_fr', 'died_location_fr')->title('Gest.Ort FR *'),
            Column::make('id', 'id')->title('ID'),
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'Artist_' . date('YmdHis');
    }
}
