<?php

use WHMCS\Database\Capsule;
use WHMCS\Module\Addon\creatia_button\Client\Dispatcher;

if (!defined("WHMCS")) {
    die("This file cannot be accessed directly");
}

/**
 * Define addon module configuration parameters.
 *
 * @return array
 */
function creatia_button_config()
{
    $serverOptions = [];
    try {
        // Query tblservers for ID/name
        $servers = Capsule::table('tblservers')->select('id', 'name')->get();

        foreach ($servers as $server) {
            $serverOptions[$server->id] = $server->name . " (ID " . $server->id . ")";
        }
    } catch (Exception $e) {
        // Log error and fallback
        logActivity("Creatia Button Addon: Failed to load servers for dropdown - " . $e->getMessage());
        // Deliberately empty rather than a '0' sentinel: a saved '0' would pass the
        // "is a server chosen" check in Eligibility and then match every service with no
        // server assigned, making the restriction broader than "Any".
        $serverOptions = [];
    }
    return [
        'name' => 'Creatia Button',
        'description' => 'Addon to provide a Creatia Portal link.',
        'version' => '1.1',
        'author' => 'Jesse and Shaun',
        'fields' => [
            'any_product' => [
                'FriendlyName' => 'Required Product',
                'Type' => 'dropdown',
                'Options' => [ 0 => 'Any', 1 => 'Server' ],
                'Description' => 'Whether the button is visible to anyone with a product, or the person must have a server.',
            ],
            'target_server_id' => [
                'FriendlyName' => 'Target Server',
                'Type' => 'dropdown',
                'Options' => $serverOptions,
                'Description' => 'Choose the server (SynergyCP), clients with a service using this server group will see the Creatia button.',
            ],
            'creatia_identity_key' => [
                'FriendlyName' => 'Identity Key',
                'Type' => 'text',
                'Size' => '30',
                'Default' => 'gsl',
                'Description' => 'This value will be used as the identity key in the Creatia API payload. ( gsl | whmcs_godedicated | whmcs_streamline )',
            ],
            'creatia_subtenant' => [
                'FriendlyName' => 'Subtenant Name',
                'Type' => 'text',
                'Size' => '30',
                'Default' => 'gsl',
                'Description' => 'This value will be sent as the subtenant in the Creatia API payload. ( gsl | go-dedicated | streamline )',
            ],
            'access_level' => [
                'FriendlyName' => 'Access Level',
                'Type' => 'dropdown',
                'Options' => [ 0 => 'Read & Write', 1 => 'Read Only' ],
                'Description' => 'Whether the user will have read only or read and write access.',
            ],
            'creatia_provision_url' => [
                'FriendlyName' => 'Creatia API Base URL',
                'Type' => 'text',
                'Size' => '50',
                'Default' => 'https://api-creatia.securelayer.com',
                'Description' => 'Base URL of the Creatia API, with no path - the module appends /api/... itself. Do NOT point this at /api/whmcs/provision-dedi.',
            ],
            'creata_api_identity' => [
                'FriendlyName' => 'API Identity',
                'Type' => 'text',
                'Size' => '200',
                'Description' => 'Enter the API token used to talk to the Creatia API.',
            ],
            'creatia_api_secret' => [
                'FriendlyName' => 'API Secret',
                'Type' => 'password',
                'Size' => '200',
                'Description' => 'Enter the API secret used to talk to the Creatia API.',
            ],
        ]
    ];
}

/**
 * Activate.
 *
 * @return array Optional success/failure message
 */
function creatia_button_activate()
{
    // Create custom tables and schema required by your module
    try {
        return [
            'status' => 'success',
            'description' => 'Module activation completed.'
        ];
    } catch (\Exception $e) {
        return [
            'status' => "error",
            'description' => 'Unable to activate Creatia Button Addon: ' . $e->getMessage()
        ];
    }
}

/**
 * Deactivate.
 *
 * @return array Optional success/failure message
 */
function creatia_button_deactivate()
{
    try {
        return [
            'status' => 'success',
            'description' => 'Module deactivation completed.'
        ];
    } catch (\Exception $e) {
        return [
            "status" => "error",
            "description" => 'Unable to deactivate Creatia Button Addon: ' . $e->getMessage()
        ];
    }
}

function creatia_button_clientarea($vars)
{
    // $_GET rather than $_REQUEST: the action selects which handler runs and belongs
    // in the URL, not in a form body or a cookie.
    $action = isset($_GET['action']) ? $_GET['action'] : '';
    $dispatcher = new Dispatcher();
    return $dispatcher->dispatch($action, $vars);
}