<?php

namespace App\DataTables;

use App\Models\SemesterExam;
use App\Models\Student;
use App\Models\StudentExamGrades;
use Carbon\Carbon;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Services\DataTable;

class ExamGradesDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->rawColumns([
                'grade'
            ])
            ->setRowId(function ($record) {
                return 'row_' . $record->id;
            })
            ->editColumn('created_at', function ($record) {
                return $record->created_at ? with(new Carbon($record->created_at))->format('Y-m-d H:i') : '';
            })
               ->filterColumn('father_name', function ($query, $keyword) {
                $keywords = trim($keyword);
                $query->whereRaw("father.first_name  like ?", ["%{$keywords}%"]);
             })
            
   
               ->filterColumn('grade', function ($query, $keyword) {
                $keywords = trim($keyword);
                $query->whereRaw("student_exam_grades.grade  like ?", ["%{$keywords}%"]);
             })
            
            
            
            ->editColumn('grade', function ($record) {
                return '<input type="text" value="' . (old('students_grades[' . $record->student_id . ']') ? old('students_grades[' . $record->student_id . ']') : $record->grade) . '" style="max-width: fit-content;" class="form-control" name="students_grades[' . $record->student_id . ']" id="students_grades">';
            })
            ->addIndexColumn();
    }


    public function lang()
    {
        $langJson = [
            "sEmptyTable"     =>  trans('general.datatable.sEmptyTable'),
            "sInfo"           =>  trans('general.datatable.sInfo'),
            "sInfoEmpty"      =>  trans('general.datatable.sInfoEmpty'),
            "sInfoFiltered"   =>  trans('general.datatable.sInfoFiltered'),
            "sInfoPostFix"    =>  trans('general.datatable.sInfoPostFix'),
            "sInfoThousands"  =>  trans('general.datatable.sInfoThousands'),
            "sLengthMenu"     =>  trans('general.datatable.sLengthMenu'),
            "sLoadingRecords" =>  trans('general.datatable.sLoadingRecords'),
            "sProcessing"     =>  trans('general.datatable.sProcessing'),
            "sSearch"         =>  trans('general.datatable.sSearch'),
            "sZeroRecords"    =>  trans('general.datatable.sZeroRecords'),
            "sFirst"          =>  trans('general.datatable.sFirst'),
            "sLast"           =>  trans('general.datatable.sLast'),
            "sNext"           =>  trans('general.datatable.sNext'),
            "sPrevious"       =>  trans('general.datatable.sPrevious'),
            "sSortAscending"  =>  trans('general.datatable.sSortAscending'),
            "sSortDescending" =>  trans('general.datatable.sSortDescending'),
            "paginate" => [
                "first" => trans('general.datatable.sFirst'),
                "previous" => trans('general.datatable.sPrevious'),
                "next" => trans('general.datatable.sNext'),
                "last" => trans('general.datatable.sLast')
            ],
        ];
        return $langJson;
    }



    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\Student $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(Student $model)
    {
        return $model->select('student_exam_grades.grade','student_exam_grades.semester_exam_id','student_exam_grades.id',
            'students.id as student_id', 'students.first_name','students.last_name', 'father.first_name as father_name')
            ->leftJoin('student_exam_grades',function($join){
                $join->on('students.id', '=', 'student_exam_grades.student_id');
                $join->on('student_exam_grades.semester_exam_id', DB::raw($this->exam->id));
            })
            ->Join('semester_exams' , function($join){
                $join->on('semester_exams.id',DB::raw($this->exam->id) )
                ;})
            ->Join('parents as father', 'students.father_id', '=', 'father.id')
            ->where('students.division_id', $this->exam->division_id)
            ->orderBy('id', 'desc');
           
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
            ->setTableId('examgrades-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->dom('<"d-flex justify-content-between align-items-center mx-0 row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>t<"d-flex justify-content-between mx-0 row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>')
            ->orderBy(0)
            ->buttons(
                Button::make('reset')->text(' <i class="fas fa-redo"></i> ' . trans('app.datatable.reset')),
                Button::make('reload')->text(' <i class="fas fa-sync-alt"></i> ' . trans('app.datatable.reload')),
            )->parameters([
                'responsive' => true,
                'autoWidth' => false,
                'lengthMenu' => [[50, 100, 200], ['50', '100', '200']],
                'language' => $this->lang(),
            ]);
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            Column::computed('DT_RowIndex')->title('#')
                ->addClass('text-center'),
            Column::make('first_name')->title(trans('general.First Name')),
            Column::make('last_name')->title(trans('general.Last Name')),
            Column::make('father_name')->title(trans('general.father')),
            Column::make('grade')->title(trans('general.grade')),
        ];
    }

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