<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use LucaDegasperi\OAuth2Server\Facades\Authorizer;
use App\Models\User;

class OAuthController extends Controller
{
    /**
     * Issue access token
     */
    public function accessToken()
    {
        return Response::json(Authorizer::issueAccessToken());
    }

    /**
     * Show authorization form
     */
    public function authorizeGet()
    {
        $authParams = Authorizer::getAuthCodeRequestParams();

        $formParams = array_except($authParams, 'client');

        $formParams['client_id'] = $authParams['client']->getId();

        $formParams['scope'] = implode(config('oauth2.scope_delimiter'), array_map(function ($scope) {
            return $scope->getId();
        }, $authParams['scopes']));

        return View::make('oauth.authorization-form', ['params' => $formParams, 'client' => $authParams['client']]);
    }

    /**
     * Handle authorization post
     */
    public function authorizePost()
    {
        $params = Authorizer::getAuthCodeRequestParams();
        $params['user_id'] = Auth::user()->id;
        $redirectUri = '/';

        // If the user has allowed the client to access its data, redirect back to the client with an auth code.
        if (Request::has('approve')) {
            $redirectUri = Authorizer::issueAuthCode('user', $params['user_id'], $params);
        }

        // If the user has denied the client to access its data, redirect back to the client with an error message.
        if (Request::has('deny')) {
            $redirectUri = Authorizer::authCodeRequestDeniedRedirectUri();
        }

        return Redirect::to($redirectUri);
    }

    /**
     * Get OAuth user info
     */
    public function me()
    {
        $user = User::findOrFail(Authorizer::getResourceOwnerId());
        if ($user->account_type == 'oauth') {
            $user->load('oauth');
        }

        return $user;
    }
} 