<?php

namespace App\Seraph;

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use App\Facades\DBconfig;
use LDAP;

class OAuthPasswordVerifier
{
    /**
     * Verify the credentials for an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|null
     */
    public function verify($request)
    {
        // Check if this is an OAuth request
        if (request()->has('oauth')) {
            return $this->verifyOAuth($request);
        }

        // Regular password verification
        return $this->verifyPassword($request);
    }

    /**
     * Verify OAuth credentials
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|null
     */
    protected function verifyOAuth($request)
    {
        $username = $request->input('username');
        $password = $request->input('password');

        if (!$username || !$password) {
            return null;
        }

        $user = DB::table('users')
            ->where('username', $username)
            ->where('active', 1)
            ->first();

        if (!$user || !Hash::check($password, $user->password)) {
            return null;
        }

        return [
            'id' => $user->id,
            'username' => $user->username,
            'email' => $user->email,
        ];
    }

    /**
     * Verify regular password credentials
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|null
     */
    protected function verifyPassword($request)
    {
        $username = $request->input('username');
        $password = $request->input('password');

        if (!$username || !$password) {
            return null;
        }

        $user = DB::table('users')
            ->where('username', $username)
            ->where('active', 1)
            ->first();

        if (!$user || !Hash::check($password, $user->password)) {
            return null;
        }

        return [
            'id' => $user->id,
            'username' => $user->username,
            'email' => $user->email,
        ];
    }

    public function verifyOld($username, $password)
    {
        $credentials = [
            'username' => $username,
            'password' => $password,
        ];

        if (request()->has('oauth')) {
            $credentials['account_type'] = 'oauth';
        }

        if (Auth::once($credentials)) {
            return Auth::user()->id;
        }

        if (DBconfig::get('ldap.enabled') && LDAP::auth($username, $password)) {
            return Auth::getProvider()->retrieveByCredentials($credentials)->id;
        }

        return false;
    }
}
