<?php
/**
 * cpanel_lib.php
 * Thin client for cPanel's UAPI, used to automatically create an Addon
 * Domain when a merchant's white-label domain passes DNS verification -
 * no manual cPanel work needed after that.
 *
 * cPanel UAPI docs: https://api.docs.cpanel.net/openapi/cpanel/operation/addaddondomain/
 */

function cpanel_settings($conn) {
    $res = mysqli_query($conn, "SELECT cpanel_host, cpanel_port, cpanel_username, cpanel_api_token, cpanel_docroot FROM site_settings LIMIT 1");
    return $res ? mysqli_fetch_assoc($res) : [];
}

function cpanel_configured($conn) {
    $s = cpanel_settings($conn);
    return !empty($s['cpanel_host']) && !empty($s['cpanel_username']) && !empty($s['cpanel_api_token']) && !empty($s['cpanel_docroot']);
}

/**
 * Low-level UAPI call. $module e.g. 'AddonDomain', $function e.g. 'addaddondomain'.
 * Returns ['ok' => bool, 'data' => array|null, 'message' => string]
 */
function cpanel_uapi_call($conn, $module, $function, $params = []) {
    $s = cpanel_settings($conn);
    if (empty($s['cpanel_host']) || empty($s['cpanel_username']) || empty($s['cpanel_api_token'])) {
        return ['ok' => false, 'data' => null, 'message' => 'cPanel API abhi configure nahi hai (Website Manage me set karein).'];
    }

    $port = (int)($s['cpanel_port'] ?: 2083);
    $url = "https://{$s['cpanel_host']}:{$port}/execute/{$module}/{$function}";
    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 25,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_HTTPHEADER => [
            'Authorization: cpanel ' . $s['cpanel_username'] . ':' . $s['cpanel_api_token'],
        ],
        // Some cPanel installs (esp. on shared/DNS-only boxes) present a
        // cert that doesn't match the API hostname - keep this off only if
        // your host genuinely needs it; safest default is verification ON.
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        return ['ok' => false, 'data' => null, 'message' => "cPanel se connect nahi ho paaya: {$curlError}"];
    }

    $decoded = json_decode($response, true);
    if (!is_array($decoded)) {
        return ['ok' => false, 'data' => null, 'message' => "cPanel se unexpected response mila (HTTP {$httpCode})."];
    }

    $status = $decoded['status'] ?? ($decoded['metadata']['result'] ?? 0);
    if ((int)$status === 1) {
        return ['ok' => true, 'data' => $decoded['data'] ?? $decoded, 'message' => 'OK'];
    }

    $errors = $decoded['errors'] ?? ($decoded['metadata']['reason'] ?? null);
    $errMsg = is_array($errors) ? implode(' ', $errors) : ($errors ?: 'Unknown cPanel error');
    return ['ok' => false, 'data' => $decoded, 'message' => $errMsg];
}

/**
 * Older-style JSON-API (API2) call - fallback for hosts where the UAPI
 * AddonDomain module Perl file isn't installed/available, but the
 * legacy API2 module might still work.
 */
function cpanel_api2_call($conn, $module, $function, $params = []) {
    $s = cpanel_settings($conn);
    if (empty($s['cpanel_host']) || empty($s['cpanel_username']) || empty($s['cpanel_api_token'])) {
        return ['ok' => false, 'data' => null, 'message' => 'cPanel API abhi configure nahi hai.'];
    }

    $port = (int)($s['cpanel_port'] ?: 2083);
    $query = array_merge([
        'cpanel_jsonapi_apiversion' => 2,
        'cpanel_jsonapi_module'     => $module,
        'cpanel_jsonapi_func'       => $function,
    ], $params);
    $url = "https://{$s['cpanel_host']}:{$port}/json-api/cpanel?" . http_build_query($query);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 25,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_HTTPHEADER => [
            'Authorization: cpanel ' . $s['cpanel_username'] . ':' . $s['cpanel_api_token'],
        ],
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
    ]);

    $response = curl_exec($ch);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        return ['ok' => false, 'data' => null, 'message' => "cPanel (API2) se connect nahi ho paaya: {$curlError}"];
    }

    $decoded = json_decode($response, true);
    $result = $decoded['cpanelresult']['data'][0] ?? null;
    $eventStatus = $decoded['cpanelresult']['event']['result'] ?? null;

    if ($eventStatus === 1 || (is_array($result) && empty($result['reason']))) {
        return ['ok' => true, 'data' => $result, 'message' => 'OK'];
    }

    $errMsg = $result['reason'] ?? ($result['statusmsg'] ?? 'Unknown cPanel (API2) error');
    return ['ok' => false, 'data' => $decoded, 'message' => $errMsg];
}

/**
 * Nudges cPanel's AutoSSL to run right away for this domain instead of
 * waiting for its normal periodic check - best-effort only, since some
 * hosts restrict this too. Failure here is silently ignored by the
 * caller; it's a bonus speed-up, not something to block on.
 */
function cpanel_request_autossl($conn) {
    return cpanel_uapi_call($conn, 'SSL', 'start_autossl_check', []);
}

/**
 * Creates the Addon Domain, pointing it at the SAME folder the main
 * NeoPay site already lives in - so the exact same files serve under the
 * new domain immediately, no separate deployment needed.
 */
function cpanel_add_addon_domain($conn, $domain) {
    $s = cpanel_settings($conn);
    if (empty($s['cpanel_docroot'])) {
        return ['ok' => false, 'message' => 'cPanel Document Root Website Manage me set karein (jaise: neopay.mgamer.online).'];
    }

    // cPanel needs a short "subdomain" label internally for every addon
    // domain - derive one from the domain itself (letters/numbers only).
    $subLabel = preg_replace('/[^a-z0-9]/', '', strtolower(explode('.', $domain)[0]));
    if ($subLabel === '') $subLabel = 'wl' . substr(md5($domain), 0, 6);

    // Try the modern UAPI first.
    $result = cpanel_uapi_call($conn, 'AddonDomain', 'addaddondomain', [
        'domain'    => $domain,
        'dir'       => $s['cpanel_docroot'],
        'subdomain' => $subLabel,
    ]);
    if ($result['ok']) return $result;

    // Some hosts don't have the UAPI module's Perl file installed, but the
    // older API2 module works fine on the same account - try that next
    // rather than giving up.
    if (stripos($result['message'], "can't locate") !== false || stripos($result['message'], 'failed to load module') !== false) {
        $fallback = cpanel_api2_call($conn, 'AddonDomain', 'addaddondomain', [
            'newdomain' => $domain,
            'dir'       => $s['cpanel_docroot'],
            'subdomain' => $subLabel,
        ]);
        if ($fallback['ok']) return $fallback;
        return ['ok' => false, 'message' => $result['message'] . ' | API2 fallback bhi fail hua: ' . $fallback['message']];
    }

    return $result;
}
