<?php
/*
 * LaraClassifier - Classified Ads Web Application
 * Copyright (c) BeDigit. All Rights Reserved
 *
 * Website: https://laraclassifier.com
 * Author: Mayeul Akpovi (BeDigit - https://bedigit.com)
 *
 * LICENSE
 * -------
 * This software is provided under a license agreement and may only be used or copied
 * in accordance with its terms, including the inclusion of the above copyright notice.
 * As this software is sold exclusively on CodeCanyon,
 * please review the full license details here: https://codecanyon.net/licenses/standard
 */

namespace App\Http\Middleware;

use App\Http\Controllers\Web\Setup\Update\Traits\CleanUpTrait;
use App\Http\Middleware\Install\CheckInstallation;
use App\Http\Middleware\Install\CheckPurchaseCode;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class Installed
{
	use CheckInstallation, CheckPurchaseCode, CleanUpTrait;
	
	/**
	 * Handle an incoming request.
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param \Closure $next
	 * @param null $guard
	 * @return \Illuminate\Http\RedirectResponse|mixed
	 * @throws \App\Exceptions\Custom\CustomException
	 * @throws \App\Exceptions\Custom\InvalidPurchaseCodeException
	 */
	public function handle(Request $request, Closure $next, $guard = null)
	{
		if (isApiRoute()) {
			return $this->handleApi($request, $next);
		} else {
			return $this->handleWeb($request, $next, $guard);
		}
	}
	
	/**
	 * @param \Illuminate\Http\Request $request
	 * @param \Closure $next
	 * @return \Illuminate\Http\JsonResponse|mixed
	 * @throws \App\Exceptions\Custom\CustomException
	 */
	private function handleApi(Request $request, Closure $next): mixed
	{
		// Since the Admin panel doesn't call the API,
		// skip requests from there to allow admins to log in to into it.
		if (request()->hasHeader('X-WEB-REQUEST-URL')) {
			if (isAdminPanelRoute(request()->header('X-WEB-REQUEST-URL'))) {
				return $next($request);
			}
		}
		
		if ($this->isNotInstalled()) {
			$url = url('install');
			$url = request()->hasHeader('X-WEB-REQUEST-URL')
				? '<a href="' . $url . '">' . $url . '</a>'
				: '"' . $url . '"';
			
			$message = 'The application is not installed. ';
			$message .= 'Please install it by visiting the URL ' . $url . ' from a web browser.';
			
			$data = [
				'success' => false,
				'message' => $message,
				'extra'   => ['error' => ['type' => 'install']],
			];
			
			return apiResponse()->json($data, Response::HTTP_FORBIDDEN);
		}
		
		if (updateIsAvailable()) {
			$url = url('upgrade');
			$url = request()->hasHeader('X-WEB-REQUEST-URL')
				? '<a href="' . $url . '">' . $url . '</a>'
				: '"' . $url . '"';
			
			$message = 'Your application needs to be upgraded. ';
			$message .= 'To achieve this, visit the URL ' . $url . ' in a web browser and follow the steps.';
			
			$data = [
				'success' => false,
				'message' => $message,
				'extra'   => ['error' => ['type' => 'upgrade']],
			];
			
			return apiResponse()->json($data, Response::HTTP_FORBIDDEN);
		}
		
		return $next($request);
	}
	
	/**
	 * @param \Illuminate\Http\Request $request
	 * @param \Closure $next
	 * @param null $guard
	 * @return \Illuminate\Http\RedirectResponse|mixed
	 * @throws \App\Exceptions\Custom\CustomException
	 * @throws \App\Exceptions\Custom\InvalidPurchaseCodeException
	 */
	private function handleWeb(Request $request, Closure $next, $guard = null): mixed
	{
		// Check if an update is available
		if (updateIsAvailable()) {
			if (auth()->check()) {
				$authUser = auth()->guard($guard)->user();
				
				$versionIntroducingAcl = (config('larapen.core.item.slug') == 'jobclass') ? '4.0.0' : '5.2.0';
				if (currentVersionIsGte($versionIntroducingAcl)) {
					if (doesUserHaveStaffPermission($authUser) && !isDemoDomain()) {
						return redirect()->to(getRawBaseUrl() . '/upgrade');
					}
				}
			}
			
			/*
			 * If update is available and the system is unable to load the upgrade page,
			 * perform required actions allowing to avoid
			 * any out-to-date/removed function or variable to cause errors
			 */
			// Flush the default cache store
			$this->flushDefaultCacheStore();
			
			// Manually purge compiled views
			$this->manuallyPurgeCompiledViews(1);
		}
		
		if ($this->isNotInstalled()) {
			return redirect()->to(getRawBaseUrl() . '/install');
		}
		
		$this->checkPurchaseCode();
		
		return $next($request);
	}
}
