<?php

namespace App\Http\Controllers;

use Illuminate\Support\Arr;
use App\Services\AccreditationService;
use App\Repositories\FilterItemsAssociation;
use App\Http\Requests\Learning\AccreditationStore;

class AccreditationController extends Controller
{

    private $accreditationService;

    public function __construct(AccreditationService $accreditationService)
    {
        $this->accreditationService = $accreditationService;
        $this->middleware('auth:sanctum');
    }

    public function index()
    {
        $accreditations = $this->accreditationService->getAll();

        return response()->json($accreditations, 201);
    }

    public function store(AccreditationStore $request)
    {
        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isOperator = auth()->user()->hasRole('operator');

        if (!$isSuperAdmin && !$isAdmin && !$isOperator) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        if ($request['filter_items']) {
            $filter_items = Arr::collapse($request['filter_items']);
            $filter_items = Arr::flatten($filter_items);
        }

        $data = Arr::except($request->validated(), ['filter_items']);

        $accreditation = $this->accreditationService->save($data);

        if (isset($filter_items) && $filter_items) {

            $accreditation->filters()->delete();

            foreach ($filter_items as $filter_item_id) {
                $filter_association = new FilterItemsAssociation();
                $filter_association->filter_item_id = $filter_item_id;
                $accreditation->filters()->save($filter_association);
            }
        }

        // return $request;
        return response()->json($accreditation->load('filters'), 201);
    }

    public function show($id)
    {
        $accreditation = $this->accreditationService->get($id);

        return response()->json($accreditation);
    }

    public function destroy($id)
    {
        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isOperator = auth()->user()->hasRole('operator');

        if (!$isSuperAdmin && !$isAdmin && !$isOperator) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $this->accreditationService->delete($id);
        return response()->json(null, 204);
    }
}
