<?php

namespace App\Services;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Artisan;

// use App\Services\SecurityCheckService;

class SecurityCheckService
{

    private function getBaseUrl()
    {

        if (strpos(request()->fullUrl(), 'index.php') === true) {
            $url    = explode("/index.php", url()->current())[0];
            $parent = explode("/", $url);

            array_pop($parent);

            return implode("/", $parent) . "/$srm_url";
        } else {
            $url    = explode("/dashboard", url()->current())[0];
            $parent = explode("/", $url);

            return implode("/", $parent);
        }

    }

    private function checkAccessibilityCurl($url)
    {
        try {
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_NOBODY, true);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // Connection timeout in seconds
            curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Request timeout in seconds

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            curl_close($ch);

            if ($response === false) {
                // throw new Exception("cURL error: " . curl_error($ch));
                return false;
            }

            if ($httpCode == 200) {
                return true;
            }

            return false;
        } catch (\Exception $e) {
            return true;
            // return $e->getMessage();
        }

    }

    public static function checkSiteAccessability($files)
    {
        $base_url = (new self)->getBaseUrl();

        foreach ($files as $file) {

            if ((new self)->checkAccessibilityCurl("$base_url/$file")) {
                return true;
            }

        }

        return false;
    }

    public static function securityCheckMessage()
    {
        $message = Config::get("srm_config.security_message");

        return $message;
    }

    public static function securityCheck()
    {

        (new self)->clearConfigCache();

        $send_curl_requests = Config::get("srm_config.send_curl_requests");

        $curl_checks = [
            "composer.json",
            ".htaccess",
            "config",
            "storage",
            "storage/framework/sessions",
            "storage/logs/laravel.log"
        ];

        if ($send_curl_requests) {
            return SecurityCheckService::checkSiteAccessability($curl_checks) ? true : false;
        }

    }

    public static function securityCheckExecute($user)
    {

        if ($user->isAdminOrOwner() && SecurityCheckService::securityCheck()) {
            return redirect()->route('home')->with(
                'security_errors',
                [
                    "security_check_error" => SecurityCheckService::securityCheckMessage()
                ]
            );
        } else {
            return redirect()->route('home');
        }

    }

    public static function checkSrmInstallExist()
    {

        if (!file_exists(public_path('srm_install'))) {
            return false;
        }

        return true;
    }

    public static function checkInstallScriptExist()
    {

        if (!file_exists(base_path("../../install.sh")) && !file_exists(base_path("../../install.ps1"))) {
            return false;
        }

        return true;
    }

    public static function checkUserSecurityQuestionExist()
    {

        if (
            !is_null(auth()->user()->Security_question_index)
            && !is_null(auth()->user()->Security_answer)
        ) {
            return false;
        }

        return true;
    }

    public function clearConfigCache()
    {
        Artisan::call('config:clear');
    }

}
