<?php

namespace App\DataTables;

use App\Models\GovernorateLang;
use App\Models\Language;
use App\Models\Role;
use App\Models\RoleLang;
use App\Models\Task;
use App\Models\User;
use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\EloquentDataTable;
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;

class UserDataTable extends DataTable
{
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action',function ($data){
                return $this->getActionColumn($data);
            })
            ->addColumn('created_at', function(User $user) {
                return $user->created_at != null ? $user->created_at->format('Y-m-d'):"";
            })
            ->addColumn('role', function(User $user) {
                $role = $user->role_id != null ? $user->role->defaultLang->role_name:"";
                if($user->role_id == Role::ADMIN_ROLE)
                    $html_code = '<span class="badge badge-light-danger me-auto">'.$role.'</span>';
                elseif($user->role_id == Role::EMPLOYEE_ROLE)
                    $html_code = '<span class="badge badge-light-success me-auto">'.$role.'</span>';
                else
                    $html_code = '<span class="badge badge-light-warning me-auto">'.$role.'</span>';

                return view('components.datatable.html-code', compact('html_code'));
            })
            ->editColumn('full_name', function(User $user){
                if($user->full_name != null){
                    // Load the encryption key from the User model
                    $key = Key::loadFromAsciiSafeString(User::ENCRYPTION_KEY);
                    // Decrypt the user's first name and last name
                    return Crypto::decrypt($user->full_name, $key);
                }

            })
            ->editColumn('email', function(User $user){
                if($user->email != null){
                    // Load the encryption key from the User model
                    $key = Key::loadFromAsciiSafeString(User::ENCRYPTION_KEY);
                    // Decrypt the user's first name and last name
                    return Crypto::decrypt($user->email, $key);
                }

            })
            ->editColumn('is_active', function(User $user) {
                if($user->is_active == 1)
                    $html_code = '<span class="badge badge-light-success me-auto">'.__("Active").'</span>';
                else
                    $html_code = '<span class="badge badge-light-danger me-auto">'.__("InActive").'</span>';

                return view('components.datatable.html-code', compact('html_code'));
            })
            ->editColumn('gov_id', function(User $user){
                return $user->gov_id != null ? $user->governorate->defaultLang->name:"";
            })
            ->filterColumn('governorate', function($query, $keyword){
                $query->whereIn('gov_id', function($qu) use($keyword) {
                    $qu->select('gov_id')->from((new GovernorateLang())->getTable())->whereRaw(' governorate_lang.name like ?', ["%$keyword%"]);
                });
            })
            ->filterColumn('role', function($query, $keyword){
                $query->whereIn('role_id', function($qu) use($keyword) {
                    $qu->select('role_id')->from((new RoleLang())->getTable())->whereRaw('role_lang.role_name like ?', ["%$keyword%"]);
                });
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     */
    public function query(User $model): QueryBuilder
    {
        $user = auth()->guard('admin')->user();
        $query = $model->newQuery();
        if($this->request()->gov_id != null)
            $query->where('gov_id', $this->request->gov_id);
        if($this->request()->employee != null)
            $query->whereIn('id', $this->request->employee);
        if($user->role_id == Role::ADMIN_ROLE){
            return $query;
        }elseif($user->role_id == Role::SUPERVISOR_ROLE){
            return $query->where('gov_id', $user->gov_id);
        }
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        return $this->builder()
                    ->setTableId('user-table')
                    ->orderBy('0', 'desc')
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->pageLength(50)
                    ->dom('Bfrtipl')
                    ->orderBy(0, 'asc')
//                    ->setTableHeadClass('fw-bold text-muted fs-4')
                    ->setTableAttribute(['class' => 'table table-row-dashed table-row-gray-300 align-middle gs-0 gy-4'])
                    ->lengthMenu([10, 25, 50, 100, 500, 1000])
                    ->buttons([
                        Button::make('excel'),
                        Button::make('csv'),
                        Button::make('pdf'),
                        Button::make('print')
                    ]);
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id'),
            Column::make('full_name'),
            Column::make('username'),
            Column::make('governorate')->data('gov_id'),
            Column::make('role'),
            Column::make('is_active'),
            Column::make('created_at'),
            Column::computed('action')
                ->exportable(false)
                ->printable(false)
                ->width(60)
                ->title('actions')
                ->addClass('text-center'),
        ];
    }

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

    /**
     * @param $data
     * @return string
     */
    protected function getActionColumn($data): string
    {
        $buttons = [];
        $buttons[] = ["type" => 'link', 'route' => route('users.view', ['user' => $data->id]), 'icon' => 'eye', 'label' => 'view'];
//        if($data->is_active == 1){
//            $buttons[]  = ["type" => 'ajax', 'route' => route('users.activate'), 'icon' => 'flag', 'label' => 'activate', 'id' => $data->id];
//        }elseif($data->result == 'pending'){
//            $buttons[]  = ["type" => 'ajax', 'route' => route('users.deactivate'), 'icon' => 'flag', 'label' => 'deactivate', 'id' => $data->id];
//        }
        $buttons[] = ["type" => 'link', 'route' => route('users.edit', ['user' => $data->id]), 'icon' => 'pencil', 'label' => 'edit', 'id' => $data->id];
        $buttons[] = ["type" => 'ajax', 'route' => route('users.delete', ['user' => $data->id]), 'icon' => 'trash', 'label' => 'delete', 'id' => $data->id];

        return view('components.datatable.action-buttons', compact('buttons'));
    }
}
