<?php
/**
 * WHMCS SSO Handler for WHP Module
 * Generates SSO login URLs for clients
 */

// Include WHMCS configuration
$whmcsdir = dirname(__FILE__) . '/../../../';
require_once $whmcsdir . 'init.php';

// Include the database capsule
use WHMCS\Database\Capsule;

// Security check
if (!defined('WHMCS')) {
    die('Access denied');
}

header('Content-Type: application/json');

try {
    // Verify request method
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }
    
    // Get parameters
    $serviceid = intval($_POST['serviceid'] ?? 0);
    $username = $_POST['username'] ?? '';
    
    if (!$serviceid || !$username) {
        throw new Exception('Missing required parameters');
    }
    
    // Get service details
    $service = Capsule::table('tblhosting')
        ->where('id', $serviceid)
        ->where('username', $username)
        ->first();
    
    if (!$service) {
        throw new Exception('Service not found or access denied');
    }
    
    // Get server details
    $server = Capsule::table('tblservers')
        ->where('id', $service->server)
        ->first();
    
    if (!$server) {
        throw new Exception('Server configuration not found');
    }
    
    // Include the WHP module functions
    require_once dirname(__FILE__) . '/whp.php';
    
    // WHMCS stores username in plaintext but encrypts the password
    $apiKey = $server->username;
    $apiSecret = decrypt($server->password);
    
    // Prepare parameters for SSO function
    $params = array(
        'serverdata' => array(
            'hostname' => $server->hostname,
            'port' => $server->port,
            'secure' => $server->secure == 'on',
            'username' => $apiKey,  // API Key (plaintext in DB)
            'password' => $apiSecret   // API Secret (encrypted in DB, now decrypted)
        ),
        'username' => $service->username,
        'serviceid' => $serviceid
    );
    
    // Generate SSO login
    $result = whp_ServiceSingleSignOn($params);
    
    if ($result['success']) {
        echo json_encode(array(
            'success' => true,
            'url' => $result['redirectTo']
        ));
    } else {
        echo json_encode(array(
            'success' => false,
            'message' => $result['errorMsg']
        ));
    }
    
} catch (Exception $e) {
    echo json_encode(array(
        'success' => false,
        'message' => $e->getMessage()
    ));
}
?>