<?php

namespace App\Http\Controllers\GUI;

use App\Exceptions\HTTPException;
use App\Http\Controllers\Controller;
use App\Http\Resources\oAuth\AccessToken;
use App\Jobs\Mails\ValidateMailAddressJob;
use App\Models\App;
use App\Models\AppAccess;
use App\Models\AppCode;
use App\Models\Invite;
use App\Models\Mail;
use App\Models\RefreshToken;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AccessController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function listAccess() {
        if(!Auth::check()) {
            abort(401);
        }

        $access = AppAccess::query()->where("user_id", "=", Auth::user()->id)->get();
        $visibleAccess = [];
        foreach($access as $a) {
            if(!$a->getApp()->hidden_in_app_list) {
                $visibleAccess[] = $a;
            }
        }


        return view("access/list", ["access" => $visibleAccess]);
    }

    public function removeAccess(Request $request) {
        if(!Auth::check()) {
            abort(401);
        }

        $access = AppAccess::query()->where("id", "=", $request->id)->firstOrFail();
        if($access->user_id != Auth::user()->id) {
            abort(401);
        }

        if($access->getApp()->user_cant_remove_app) {
            abort(400, "App access cant remove for this app");
        }

        RefreshToken::query()->where("access_id", "=", $access->id)->delete();
        \App\Models\AccessToken::query()->where("access_id", "=", $access->id)->delete();
        AppCode::query()->where("access_id", "=", $access->id)->delete();
        $access->delete();


        return redirect("/gui/access");
    }
}