<?php

namespace App\DataTables;

use App\Models\CashManagement;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Illuminate\Support\Facades\Gate;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
use Carbon\Carbon;

class CashManagementDataTable extends DataTable
{
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder $query Results from query() method.
     */

    public function dataTable(QueryBuilder $query)
    {
        return datatables()
            ->eloquent($query)            
            ->addIndexColumn()
            ->editColumn('entry_date', function ($row) {
                return date('d-m-Y', strtotime($row->entry_date)) ?? "";
            })
            ->addColumn('user_name', function ($row) {
                return $row->user ? $row->user->name : "";
            })
            ->editColumn('voucher_number', function ($row) {
                return $row->voucher_number ?? "";
            })
            ->editColumn('payment_way', function ($row) {
                return isset(config('constant.payment_ways')[$row->payment_way])
                    ? config('constant.payment_ways')[$row->payment_way]
                    : '';
            })           
            ->addColumn('action', function ($row) {
                $action = '<div>';         
                
                if (Gate::check('cash_management_access')) {
                    $viewIcon = view('components.svg-icon', ['icon' => 'view'])->render();
                    $action .= '<button data-href="' . route('cash-management.show', $row->uuid) . '"  class="btn btn-icon btn-info view_cashreceipt" title="'.trans('quickadmin.qa_view').'" >' . $viewIcon . '</button>';                        
                }  
              
                if (Gate::check('cash_management_edit')) {
                    $editIcon = view('components.svg-icon', ['icon' => 'edit'])->render();
                    $action .= '<a href="' . route("cash-management.edit", $row->uuid) . '" class="btn btn-icon btn-info edit_product" title="'.trans('quickadmin.qa_update').'" >' . $editIcon . '</a>';
                }
                
                if (Gate::check('cash_management_delete')) {                
                    $deleteIcon = view('components.svg-icon', ['icon' => 'delete'])->render();
                    $action .= '<button title="'.trans('quickadmin.qa_delete').'" class="btn btn-icon btn-info delete_transaction p-1" data-href="'.route('cash-management.destroy', $row->uuid).'">'.$deleteIcon.'</button>';                
                }
                $action .= '</div>'; 
                return $action;
            })           
            ->filterColumn('entry_date', function ($query, $keyword) {
                $query->whereRaw("DATE_FORMAT(cash_management.entry_date,'%d-%m-%Y') like ?", ["%$keyword%"]); //date_format when searching using date
            })
            ->filterColumn('payment_way', function ($query, $keyword) {
                $paymentWays = config('constant.payment_ways');
                $filteredKeys = array_keys(array_filter($paymentWays, function($value) use ($keyword) {
                    return stristr($value, $keyword) !== false;
                }));
            
                if (!empty($filteredKeys)) {
                    $query->whereIn('payment_way', $filteredKeys);
                }
            }) 
            ->filterColumn('user_name', function ($query, $keyword) {
                $query->whereHas('user', function ($q) use ($keyword) {
                    $q->where('users.name', 'like', "%$keyword%");
                });
            })
            ->orderColumn('user_name', function ($query, $order) {
                $query->whereHas('user', function ($q) use ($order) {
                    $q->orderBy('users.name',$order);
                });
            })             
            ->orderColumn('payment_way', function ($query, $order) {
                $paymentWays = config('constant.payment_ways');
                $query->orderByRaw("
                    CASE 
                        WHEN payment_way = 'by_cash' THEN '" . $paymentWays['by_cash'] . "'
                        WHEN payment_way = 'by_check' THEN '" . $paymentWays['by_check'] . "'
                        WHEN payment_way = 'by_account' THEN '" . $paymentWays['by_account'] . "'
                        ELSE payment_way
                    END $order
                ");
            })           

            ->rawColumns(['action','checkbox']);
    }

    /**
     * Get the query source of dataTable.
     */ 

    public function query(CashManagement $model): QueryBuilder
    {
        //return $model->newQuery();
        $query = $model->newQuery()->with('user');
        return $this->applyScopes($query);
    }


    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        return $this->builder()
            ->setTableId('cash-management-table')
            ->parameters([
                'responsive' => false,
                'pageLength' => 50,
            ])
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->dom('frtip')
            ->orderBy(2);
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
       
       return [  
            Column::make('DT_RowIndex')->title(trans('quickadmin.qa_sn'))->orderable(false)->searchable(false),
            Column::make('entry_date')->title(trans('quickadmin.cash-management.fields.date'))->searchable(true),
            Column::make('user_name')->title(trans('quickadmin.cash-management.fields.staff_name'))->searchable(true),
            Column::make('voucher_number')->title(trans('quickadmin.cash-management.fields.estimate_number'))->searchable(true),
            Column::make('payment_way')->title(trans('quickadmin.transaction.fields.payment_mode'))->orderable(true),
            Column::make('amount')->title(trans('quickadmin.cash-management.fields.amount'))->searchable(true),
            Column::computed('action')
                        ->exportable(false)
                        ->printable(false)
                        ->width(60)
                        ->addClass('text-center')->title(trans('quickadmin.qa_action'))
        ];       
    }

    /**
     * Get the filename for export.
     */
    protected function filename(): string
    {
        return 'order' . date('YmdHis');
    }
}
