<?php

namespace App\Services\SM;

use App\Models\SM\Fnction;
use App\Models\SM\Permission;
use App\Traits\DataTable;
use Exception;

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

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

    public function create($data)
    {
        $data['app_code'] = config('canteen.app_code');
        $fnction = $this->model->create($data);
        $permission_id = [];
        foreach ($data['permission_id'] as $permission_id) {
            $pms = Permission::findOr($permission_id, fn () => throw new Exception("Permission does not exist"));
            $keyCode = $fnction->code . '.' . $pms->name;
            $permission_id[$permission_id] = ['key_code' => $keyCode];
        }
        $fnction->permissions()->sync($permission_id);
    }

    public function detail(string $id)
    {
        $data = $this->model->findOr($id, fn () => throw new Exception("Function not found"));
        $data->permission_id = $data->permissions()->pluck('permission_id')->toArray();
        return $data;
    }

    public function update($id, $data)
    {
        $data['app_code'] = config('canteen.app_code');
        $fnction = $this->model->findOr($id, fn () => throw new Exception("Function Not found"));
        $fnction->update($data);
        $permission_id = [];
        foreach ($data['permission_id'] as $per_id) {
            $pms = Permission::findOr($per_id, fn () => throw new Exception("Permission does not exist"));
            $keyCode = $fnction->code . '.' . $pms->name;
            $permission_id[$per_id]['key_code'] = $keyCode;
        }
        $fnction->permissions()->sync($permission_id);
    }
}
