<?php

namespace App\Http\Controllers;

use App\Models\Domain;
use App\Models\DomainAuthorization;
use Illuminate\Http\Request;

class DomainAuthorizationController extends Controller
{
    private $prefix = "admin/domains/";
    private $resources = [];
    private $checkPermissionAndRolesController;
    private $userController;

    public function __construct(
        CheckPermissionsAndRolesController $checkPermissionAndRolesController,
        UserController $userController
    ) {
        $this->resources['prefix'] = $this->prefix;
        $this->checkPermissionAndRolesController = $checkPermissionAndRolesController;
        $this->userController = $userController;
    }
    public function index(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'View Domain']);
        $this->resources['data'] = Domain::with('authorization.authorized_user')->where('id', $request->id)->first();
        $this->resources['users'] = $this->userController->getAll();
        return view('admin.domains.domain_authorization')->with($this->resources);
    }

    public function autherization(Request $request)
    {

        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Authorize Domain']);
        try {
            $credentials = $request->validate([
                'user_id' => ['required', 'numeric'],
                'domain_id' => ['required', 'numeric'],
                'authorization' => ['required', 'numeric'],
            ]);
            DomainAuthorization::updateOrCreate(['user_id' => $credentials['user_id'], 'domain_id' => $credentials['domain_id']],$credentials);
            $this->resources['messages'] = array("type" => "success", "description" => "Domain authorized success");
            return redirect()->back()->with('messages', $this->resources);
        } catch (\Throwable $th) {
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }
}
