<?php

namespace App\Services\SM;

use App\Models\SM\Fnction;
use App\Models\SM\FnctionPermission;
use App\Models\SM\Role;
use App\Traits\DataTable;
use Exception;
use stdClass;

class RoleService
{
    use DataTable;
    /**
     * Create a new class instance.
     */
    public function __construct(private Role $model)
    {
        //
    }

    public function dataTable()
    {
        return $this->generate($this->model->query());
    }

    public function create($data)
    {
        $data['app_code'] = config('canteen.app_code');
        $role = $this->model->create($data);
        $role->fncPermissions()->sync($data['permission_id']);
        $fnction_id = Fnction::whereIn('code',$data['fnction_id'])->pluck('id')->toArray();
        $role->fntions()->sync($fnction_id);
        return $role;
    }

    public function detail(string $id)
    {
        $role = $this->model->findOr($id, fn () => throw new Exception("Role not found"));
        $permission_id = $role->fncPermissions->pluck('id')->toArray();
        $fuctions = Fnction::withCount('permissions')->get();
        $arr = [];
        foreach ($permission_id as $p_id) {
            $arr[$p_id] = ['checked' => true];
        }
        foreach($fuctions as $fnt){
            $fnPms = $fnt->permissions->pluck('pivot.id')->toArray();
            $intersect = array_intersect($fnPms,$permission_id);
            $checked = count($intersect) === count($fnPms);
            $partialChecked = count($intersect) > 0 && (count($intersect) !== count($fnPms));
            $arr[$fnt->code] = ['checked' => $checked,'partialChecked' => $partialChecked];
        }
        $role->permission_id = $arr;
        return $role;
    }

    public function update(string $id, array $data)
    {
        $role = $this->model->findOr($id, fn () => throw new Exception("Role not found"));
        $role->update($data);
        $role->fncPermissions()->sync($data['permission_id']);
        $fnction_id = Fnction::whereIn('code',$data['fnction_id'])->pluck('id')->toArray();
        $role->fnctions()->sync($fnction_id);
        return $role;
    }
}
