<?php
use Illuminate\Database\Capsule\Manager as Capsule;

// Script executed on every pageload

/**
 * Check if there's a variable gogetssl_username set. When it's set, save it to the DB.
 */
if (isset($_POST['gogetssl_username'])
    && isset($_SESSION['adminid'])
    && strpos($_SERVER['SCRIPT_NAME'], 'configproducts.php') != false
    && isset($_GET['action'])
    && $_GET['action'] == 'save') {
    global $whmcs, $client;

    foreach ($_POST as $item => $value) {
        if (substr($item, 0, 8) != 'gogetssl') {
            continue;
        }

        if ($item == 'gogetssl_tech') {
            $value = json_encode($value);
        }

        if ($item == 'gogetssl_test') {
            $value = $value == 'on' ? 1 : 0;
        }

        $whmcs->set_config($item, $value);
    }
}

/**
 * Check if we're on configuressl, so let's write to Awaiitng Configuration to fool WHMCS
 */
if (strpos($_SERVER['SCRIPT_NAME'], 'configuressl') != false
    && isset($_SESSION['gogetsslcert']['reissue'])) {
    $order = Capsule::table('tblsslorders')
        ->where('id', $_SESSION['gogetsslcert']['reissue'])
        ->first();

    if ($_GET['cert'] == md5($_SESSION['gogetsslcert']['reissue'])) {
        Capsule::table('tblsslorders')
            ->where('id', $order->id)
            ->update([
                'status' => 'Awaiting Configuration'
            ]);

        register_shutdown_function(function () use ($order) {
            Capsule::table('tblsslorders')
                ->where('id', $order->id)
                ->update([
                    'status' => $order->status
                ]);
        });
    }
}
