<?php

namespace Modules\Role\Repositories;

use Modules\Role\Entities\Role;
use App\Repositories\BaseRepository;
use Modules\Role\Repositories\RoleRepositoryInterface;
use Yajra\DataTables\DataTables;

class RoleRepository extends BaseRepository implements RoleRepositoryInterface
{
    protected $table = 'RoleTable';

    public function __construct(Role $model)
    {
        $this->mainModel = $model;
    }

    public function datatable()
    {
        $data = $this->mainModel->where('id', '!=', 1);

        return DataTables::of($data)
                ->addIndexColumn()
                ->editColumn('id', fn($row) => encryptString($row->id))
                ->addColumn('action', function($row) {
                    return generateActionDropdown([
                        [
                            'class' => 'call-modal',
                            'attributes' => [
                                'data-url' => route('roles.permission', ['id' => encryptString($row->id),]),
                                'data-title' => __('lang.permission_data', ['data' => $row->name,]),
                                'data-table' => $this->table,
                            ],
                            'label' => '<i class="bx bx-lock me-2"></i>' . __('lang.permissions'),
                        ],
                        [
                            'class' => 'call-modal',
                            'attributes' => [
                                'data-url' => route('roles.edit', ['id' => encryptString($row->id),]),
                                'data-title' => __('lang.edit_data', ['data' => __('lang.groups'), 'value' => $row->name,]),
                                'data-table' => $this->table,
                            ],
                            'label' => '<i class="bx bx-pencil me-2"></i>' . __('lang.edit'),
                        ],
                        [
                            'class' => 'delete-action',
                            'attributes' => [
                                'data-url' => route('roles.destroy', encryptString($row->id)),
                                'data-title' => __('lang.delete_data', ['data' => $row->name,]),
                                'data-table' => $this->table,
                            ],
                            'label' => '<i class="bx bx-trash me-2"></i>' . __('lang.delete'),
                        ]
                    ]);
                })
                ->rawColumns(['action'])
                ->make('true');
    }

    public function countUserRole($id)
    {
        $count = $this->mainModel->withCount([
            'user' => fn($query) => $query->where('role_id', $id)
            ])->find($id);

        return $count->user_count;
    }

}
