<?php

namespace App\Http\Middleware;

use App\Models\CompanyDefaultPermissions;
use App\Models\DetailMembershipPayment;
use App\Models\DetailUserCompany;
use App\Models\Permissions;
use App\Models\PermissionsUser;
use App\Traits\HasResponse;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class PermissionsUserMiddleware
{
    use HasResponse;

    public function handle(Request $request, Closure $next)
    {
        # Superadministrador hace uso de todo
        $detailUser = DetailUserCompany::find($request->iddetail_user);
        if (optional($detailUser)->iduser_type == 1) return $next($request);

        $route = $request->route();
        $user = Auth::user();
        $excludedGroups = ['v1/auth', 'v1/transbank'];

        /* --------------- VERIFICAR EL PAGO DE MEMBRESÍA ACTIVO ------------- */
        # En caso sea el administrador solo se le deja hacer uso de las apis de AUTH y las de TRANSBANK para el tema de pago, si es otro tipo de usuario no se le permite nada

        $detailMembershipPayment = DetailMembershipPayment::where('idcompany', $request->idcompany)
            ->where('status_page', 1)->active()->first();

        if (!$detailMembershipPayment) {
            if (in_array($route->action['prefix'], $excludedGroups)) {
                return $next($request);
            } else {
                return $this->errorResponse('La membresía de su empresa no esta activa, por favor comuníquese con su administrador.', 401);
            }
        }

        /* ------------------------ ANOTACIONES ------------------------
            PP = Permisos personalizados -> tabla tbl_permissions_user
            Acciones = Lectura, Escritura, Edición, Eliminado
        */

        # Rutas permitidas por defecto
        if (in_array($route->action['prefix'], $excludedGroups))  return $next($request);

        $permissionsUser = PermissionsUser::where('iduser', $user->id)
            ->whereHas('user', function ($q) use ($request) {
                $q->where('idcompany', $request->idcompany);
            })->active()->get();

        if ($permissionsUser->isEmpty()) {

            $permissionsCompany = CompanyDefaultPermissions::where('idcompany', $request->idcompany)
                ->where('iduser_type',  $detailUser->iduser_type)->first();

            $data = $this->structureData(2, $permissionsCompany);
        } else {
            $data = $this->structureData(1, $permissionsUser);
        }

        $access = collect($data['permissions'])->contains(str_replace("v1/", "", $route->action['prefix']));
        $actionValue = array_intersect([$request->method()], $data['actions']);
        $actionValue = count($actionValue) > 0;

        if (!$access || !$actionValue) return $this->errorResponse('No cuenta con permisos para realizar dicha acción.', 400);

        return $next($request);
    }

    private function structureData($type, $permissionsUser)
    {
        $actionList = ['GET', 'POST', 'PATCH', 'DELETE'];

        $permissions = ($type == 1) ? $permissionsUser[0]->permissions : $permissionsUser->permissions;
        $permissionsData = Permissions::whereIn('id', $permissions)->get();

        $dataPermissions = $permissionsData->flatMap(function ($permission) {
            return $permission->route_group;
        })->all();

        $dataActions = ($type == 1) ? collect($permissionsUser[0]->actions)->map(function ($action) use ($actionList) {
            return $actionList[$action - 1];
        })->all() : $actionList;

        return [
            'permissions' => $dataPermissions,
            'actions' => $dataActions,
        ];
    }
}
