<?php

namespace App\DataTables;

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

class FinancialsRecordsDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->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') : '';
            })
            ->addIndexColumn()
            ->filterColumn('user', function ($query, $keyword) {
                $keywords = trim($keyword);
                $query->whereRaw("CONCAT(users.first_name, ' ',users.last_name) like ?", ["%{$keywords}%"]);
            })
            ->filterColumn('student', function ($query, $keyword) {
                $keywords = trim($keyword);
                $query->whereRaw("CONCAT(students.first_name, ' ',students.last_name) like ?", ["%{$keywords}%"]);
            })
            ->filterColumn('transaction_type', function ($query, $keyword) {
                $keywords = trim($keyword);
                $query->whereRaw("transaction_types.title like ?", ["%{$keywords}%"]);
            });
    }

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

        $allowedDivisions = [];
        $userPermission = Auth::guard('admin')->user()->getUserPermissionByCode('manage-students');
        if ($userPermission) {
            $allowedDivisions = json_decode($userPermission['details'], true)['divisions'];
        }


        $query = $model->select('student_financial_records.*', DB::raw("CONCAT(students.first_name, ' ',students.last_name) AS student"),  DB::raw("CONCAT(users.first_name, ' ',users.last_name) AS user"), 'transaction_types.title as transaction_type',)
            ->join('transaction_types', 'transaction_types.id', '=', 'student_financial_records.transaction_type_id')
            ->join('users', 'users.id', '=', 'student_financial_records.user_id')
            ->join('students', 'students.id', '=', 'student_financial_records.student_id')
            ->orderBy('id', 'desc');

        if (!in_array(-1, $allowedDivisions)) {
            $query = $query->whereIn('students.division_id', $allowedDivisions);
        }

        return $query->orderBy('id', 'desc');
    }

    
    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;
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
            ->setTableId('financialsrecords-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' => [[10, 25, 50, 100], ['10', '25', '50', '100']],
                'language' => $this->lang(),
            ]);
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            Column::computed('DT_RowIndex')->title('#')
                ->addClass('text-center'),
            Column::make('student')->title(trans('general.student_name')),
            Column::make('transaction_date')->title(trans('general.date')),
            Column::make('amount')->title(trans('general.amount')),
            Column::make('transaction_type')->title(trans('general.transaction_type')),
            Column::make('transaction_number')->title(trans('general.transaction_number')),
            Column::make('note')->title(trans('general.notes')),
            Column::make('created_at')->title(trans('general.created-at')),
            Column::make('user')->title(trans('general.user')),
        ];
    }

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