<?php
namespace Modules\JazManager\Actions;

use CController;
use CControllerResponseRedirect;
use CControllerResponseFatal;
use CCookieHelper;
use CView;

class JazManagerApp extends CController
{

    public function init(): void
    {
        $this->disableCsrfValidation();
    }

    protected function checkInput(): bool
    {
        return true;
    }

    protected function checkPermissions(): bool
    {
        return true;
    }

    protected function doAction(): void
    {
        $config = __DIR__ . "/../config/jam.module.config.php";
        $session = json_decode(base64_decode(CCookieHelper::get(ZBX_SESSION_NAME)), true);
        $encodeSession = base64_encode(json_encode($session['sessionid']));

        if (file_exists($config)) {
            require_once $config;

            if (defined('JAM_URL')) {
                $jamUrl = rtrim(JAM_URL, '/');
                $apiUrl = $jamUrl . '/api/session';

                $ch = curl_init($apiUrl);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['session_key' => $encodeSession]));
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Content-Type: application/json'
		]);
		// Disable SSL certificate verification for self-signed certs
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

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

                curl_close($ch);
                if ($httpStatus == 200) {
                    $responseData = json_decode($response, true);
                    if (isset($responseData['type']) && $responseData['type'] === 'Ok' && isset($responseData['detail']['data'])) {
                        if (session_status() == PHP_SESSION_NONE) {
                            session_start();
                        }

                        $_SESSION['loading'] = true;

                        $this->displayLoader();

                        ob_flush();
                        flush();

                        // If the response type is Ok, redirect the user
                        echo '
    <script>
        setTimeout(function() {
            window.location.href = "' . $jamUrl . '/redirect?token=' . $responseData['detail']['data'] . '";
        }, 300);
    </script>';
                        $_SESSION['loading'] = false;
                    } elseif (isset($responseData['type']) && $responseData['type'] === 'config' && isset($responseData['detail']['message']) && $responseData['detail']['message'] == "Config not Found") {
                        echo (new CView('jaz.manager.error', [
                            'errorMessage' => 'Unable to connect to the Job Arranger Manager API. Please check the Job Arranger Manager configuration and try again.'
                        ]))->getOutput();
                    } elseif (isset($responseData['type']) && $responseData['type'] === 'Incomplete' && isset($responseData['detail']['message'])) {
                        echo (new CView('jaz.manager.error', [
                            'errorMessage' => $responseData['detail']['message']
                        ]))->getOutput();
                    } else {
                        echo (new CView('jaz.manager.error'))->getOutput();
                    }

                } else {
                    // Handle error in API call (HTTP status not 200)
                    echo (new CView('jaz.manager.error'))->getOutput();
                }
            } else {
                echo (new CView('jaz.manager.error'))->getOutput();
            }
        } else {
            echo (new CView('jaz.manager.error'))->getOutput();
        }
    }


    private function displayLoader(): void
    {
        echo '
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Redirecting</title>
        <style>

html,body{
background-color:white !important;
}
        body {
top:40%;
left:45%;

display:flex; 
    margin: 0 ;
    padding: 0 ;
    font-family: Arial, sans-serif;
  
        height: 100vh ;
    overflow: hidden;
}

.msg-global.msg-bad {
        display: none;


    }

.loader {
   border: 8px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 8px solid #007bff;
            width: 70px;
            height:70px;
            animation: spin 1.5s linear infinite;
            margin-bottom: 20px;
            }
 .loader {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  }

.content {

margin-left:2rem;
margin-top:2.5%;

    text-align: center ;
    font-size: 16px ;
    color: #333 ;
}

.content h2 {
margin-top:5rem;
font-weight: 600;

    font-size: 24px ;
    margin: 0;
}

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

         </style>    </head>
    <body>
        <div class="loader">

</div>
        <div class="content">
            <h2>Redirecting to Job Arranger...</h2>
        </div>
    </body>
    </html>
    ';
    }
}
