<?php
 
namespace App\Http\Middleware;

use App\Helpers\Security;
use Illuminate\Support\Facades\Notification;
use App\Notifications\SlackNotification;
use App\Models\SecurityEvent;

use Closure;

class Whmcs
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $role
     * @return mixed
     */

    public function handle($_request, Closure $_next)
    {

        // Get whether or not the requesting client is allowed to hit this point.
        if(array_search(Security::real_ip(), config('creatia.whitelist.whmcs')) !== false) {

            // Check whether the message is legitimate.
            $integrity_check_payload = $_request->input();

            if(isset($integrity_check_payload['organisation']) && $integrity_check_payload['organisation'] == null) {
                $integrity_check_payload['organisation']='';
            }

            if(isset($integrity_check_payload['organisation']['name']) && $integrity_check_payload['organisation']['name'] == null) {
                $integrity_check_payload['organisation']['name']='';
            }

            // Try both varieties of sorting if necessary to provide the most robust integrity check...
            ksort($integrity_check_payload, SORT_DESC);
            $has_integrity = $_request->header('X-Signature') == hash_hmac('sha256', http_build_query($integrity_check_payload), config('creatia.whmcs.secret'));

            if($has_integrity) {
                SecurityEvent::create([
                    'user_id'       => 1,
                    'ip'            => Security::real_ip(),
                    'user_agent'    => $_request->userAgent(),
                    'route'         => $_request->path(),
                    'payload'       => json_encode($_request->input()),
                    'description'   => 'WHMCS Request Success',
                ]);
    
                return $_next($_request);
            }

            SecurityEvent::create([
                'user_id'       => 1,
                'ip'            => Security::real_ip(),
                'user_agent'    => $_request->userAgent(),
                'route'         => $_request->path(),
                'payload'       => json_encode($_request->input()),
                'description'   => 'WHMCS Request Failed - Integrity',
            ]);

            Notification::route('slack', config('creatia.webhook.standard'))->notify(new SlackNotification("WHMCS Security Middleware: Could not confirm integrity of message from WHMCS."));

            return response('', 400);
        }

        SecurityEvent::create([
            'user_id'       => 1,
            'ip'            => Security::real_ip(),
            'user_agent'    => $_request->userAgent(),
            'route'         => $_request->path(),
            'payload'       => json_encode($_request->input()),
            'description'   => 'WHMCS Request Failed - Authenticity',
        ]);

        Notification::route('slack', config('creatia.webhook.standard'))->notify(new SlackNotification('WHMCS Security Middleware: WHMCS address not whitelisted' . Security::real_ip() . ' failed to access ' . $_request->path() . ' using ' . $_request->header('user-agent')));

        return response('', 400);
    }
 
}