<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\CaptchaService;
use Illuminate\Support\Facades\Session;

class CaptchaController extends Controller
{
    private $captchaService;

    public function __construct()
    {
        if (!Session::has('cdata')) {
            Session::put('cdata', $this->initializeCaptchaData());
        }
    }

    private function generateUniqueId2($minLength = 5, $maxLength = 13)
    {
        $length = rand($minLength, $maxLength);
        $uniqueId = uniqid(bin2hex(random_bytes(2)));
        $uniqueId = preg_replace_callback('/[0-9]/', function ($matches) {
            $letters = range('a', 'z');
            return $letters[$matches[0]];
        }, $uniqueId);
        return substr($uniqueId, 0, $length);
    }

    public function index()
    {
        $cleanUrl = 'secret1';
        $randFunc29 = $this->generateUniqueId2();
        $randFunc27 = $this->generateUniqueId2();

        $captchaHash = hash('sha256', 'captcha' . date("h") . $cleanUrl);

        $src = url("cc/{$captchaHash}.js?action=captcha&onload={$randFunc29}");

        $script = "
            const $randFunc27 = HTMLFormElement.prototype.submit;
            const $randFunc29 = function () {
                if (typeof ccaptchaObj !== 'undefined' && ccaptchaObj !== null) {
                    Object.defineProperty(ccaptchaObj, 'ccaptcha_valid', {
                        get: function () {
                            return this._ccaptcha_valid;
                        },
                        set: function (value) {
                            if (this._ccaptcha_valid === false && value === true) {
                                const captchaForm = document.querySelector(\"#captcha-holder\")?.closest(\"form\");

                                if (captchaForm) {
                                    const buttons = captchaForm.querySelectorAll(\"button[type='submit']\");
                                    if (buttons.length > 0) {
                                        buttons.forEach(function (button) {
                                            button.addEventListener(\"click\", function (event) {
                                                if (event.isTrusted) {
                                                    $randFunc27.call(captchaForm);
                                                }
                                            });
                                        });
                                    } else {
                                        console.error(\"No submit buttons found inside the captcha form.\");
                                    }
                                } else {
                                    console.error(\"No form containing #captcha-holder was found.\");
                                }
                            }
                            this._ccaptcha_valid = value;
                        }
                    });
                } else {
                    alert(\"Captcha Initiation Failed, Please Reload.\");
                }
            };

            const scriptTag = document.createElement(\"script\");
            scriptTag.src = \"$src\";
            document.body.appendChild(scriptTag);
        ";

        return response($script, 200, [
            'Content-Type' => 'application/javascript',
            'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
            'Cache-Control' => 'post-check=0, pre-check=0',
            'Pragma' => 'no-cache',
            'Expires' => '0',
        ]);
    }

    public function action(Request $request)
    {
        $functionData = Session::get('cdata');
        if(!$functionData) {
            abort(404);
        }
        $captcha = new CaptchaService($functionData);

        $action = $request->query('action');

        if ($action === 'captcha') {
            return $captcha->captcha();
        } elseif ($action === 'data') {
            $cdata = $request->query('cdata');
            return $captcha->data($cdata);
        }

        abort(404);
    }

    private function initializeCaptchaData()
    {
        return [
            'selectedIconIndex' => $this->generateUniqueId2(),
            'action'            => $this->generateUniqueId2(),
            'getCaptcha'        => $this->generateUniqueId2(),
            'cverify'           => $this->generateUniqueId2(),
            'options'           => $this->generateUniqueId2(),
            'correctIcon'       => $this->generateUniqueId2(),
            'success'           => $this->generateUniqueId2(),
            'token'             => $this->generateUniqueId2(),
            'validate'          => $this->generateUniqueId2(),
            'ctoken'            => $this->generateUniqueId2(),
            'load'              => $this->generateUniqueId2(),
        ];
    }
}
