<?php
// ─── WHM API Client ──────────────────────────────────────────────────────────
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
    header('HTTP/1.0 403 Forbidden', true, 403);
    exit;
}

/**
 * Resolve which WHM server an order belongs to. Checks the h_server table
 * first (per-server credentials, same as v1's admin/paidact.php), and falls
 * back to the static per-group constants in config/servers.php when no
 * matching row exists.
 */
function whm_resolve_server($srv) {
    global $conn;
    $srv = (int)$srv;

    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_server WHERE id='$srv' OR FIND_IN_SET('$srv', category_ids) LIMIT 1"));
    if ($row && !empty($row['whm_user']) && !empty($row['token'])) {
        $ns = array_pad(explode(',', $row['nameserver'] ?? ''), 2, '');
        return [
            'host'  => $row['server_url'],
            'user'  => $row['whm_user'],
            'token' => decode($row['token'], KEY_ONE),
            'ns1'   => trim($ns[0]),
            'ns2'   => trim($ns[1]),
        ];
    }

    require_once __DIR__ . '/../config/servers.php';
    $groups = [
        1 => ['host' => WHM_HOST_SSD,  'user' => WHM_USER_SSD,  'token' => WHM_TOKEN_SSD,  'ns1' => $ns1, 'ns2' => $ns2],
        2 => ['host' => WHM_HOST_SSD,  'user' => WHM_USER_SSD,  'token' => WHM_TOKEN_SSD,  'ns1' => $ns11, 'ns2' => $ns12],
        3 => ['host' => WHM_HOST_NVME, 'user' => WHM_USER_NVME, 'token' => WHM_TOKEN_NVME, 'ns1' => $ns3, 'ns2' => $ns4],
        7 => ['host' => WHM_HOST_VPS,  'user' => WHM_USER_VPS,  'token' => WHM_TOKEN_VPS,  'ns1' => $ns7, 'ns2' => $ns8],
    ];
    return $groups[$srv] ?? null;
}

function whm_request($server, $endpoint, $params = []) {
    $params = array_merge(['api.version' => '1'], $params);
    $url = "https://{$server['host']}:2087/json-api/$endpoint?" . http_build_query($params);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false, // WHM :2087 commonly runs a hostname-mismatched cert
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_HTTPHEADER     => ["Authorization: whm {$server['user']}:{$server['token']}"],
    ]);
    $raw = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);

    if ($raw === false) return ['ok' => false, 'message' => "WHM request failed: $err"];

    $data = json_decode($raw, true);
    if (($data['metadata']['result'] ?? 0) != 1) {
        return ['ok' => false, 'message' => $data['metadata']['reason'] ?? 'WHM request failed.', 'raw' => $data];
    }
    return ['ok' => true, 'data' => $data['data'] ?? []];
}

function whm_suspend($server, $username, $reason = '') {
    return whm_request($server, 'suspendacct', ['user' => $username, 'reason' => $reason]);
}

function whm_unsuspend($server, $username) {
    return whm_request($server, 'unsuspendacct', ['user' => $username]);
}

function whm_account_summary($server, $username) {
    return whm_request($server, 'accountsummary', ['user' => $username]);
}

function whm_change_password($server, $username, $password) {
    return whm_request($server, 'passwd', ['user' => $username, 'password' => $password, 'db_cache_clear' => 1]);
}

function whm_create_account($server, $username, $password, $domain, $plan, $email = '') {
    return whm_request($server, 'createacct', [
        'username'     => $username,
        'password'     => $password,
        'domain'       => $domain,
        'plan'         => $plan,
        'contactemail' => $email,
    ]);
}

function whm_create_user_session($server, $username, $service = 'cpaneld') {
    return whm_request($server, 'create_user_session', ['user' => $username, 'service' => $service]);
}
