<?php
// ─── Hosting Actions API ───────────────────────────────────────────────
require_once __DIR__ . '/../core/whm.php';

function hosting_context($oid) {
    global $conn;
    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_order WHERE id='$oid'"));
    if (!$row) return null;
    $store = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_store WHERE id='{$row['sid']}'")) ?: [];
    $server = whm_resolve_server($row['srv'] ?: 1);
    return ['order' => $row, 'store' => $store, 'server' => $server];
}

function sso() {
    $uid = require_login();
    global $conn;
    $oid = (int)($_GET['oid'] ?? 0);
    $target = in_array($_GET['target'] ?? '', ['cpaneld', 'webmaild', 'whostmgrd']) ? $_GET['target'] : 'cpaneld';
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";

    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id FROM h_order WHERE id='$oid' $uidok"));
    if (!$row) error_response('Service not found', 404);

    $ctx = hosting_context($oid);
    if (!$ctx['server']) error_response('Server not configured for this account.');
    $username = decode($ctx['store']['auser'] ?? '', KEY_ONE);
    if (!$username) error_response('No hosting account username on file.');

    $result = whm_create_user_session($ctx['server'], $username, $target);
    if (!$result['ok']) error_response('SSO failed: ' . $result['message']);

    success_response(['url' => $result['data']['url'] ?? ''], 'SSO session created.');
}

function password() {
    $uid = require_login();
    global $conn;
    $oid = (int)($_POST['oid'] ?? 0);
    $newPass = $_POST['password'] ?? '';
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";

    if (strlen($newPass) < 8 || !preg_match('/[A-Za-z]/', $newPass) || !preg_match('/[0-9]/', $newPass)) {
        error_response('Password must be at least 8 characters and include a letter and a number.');
    }

    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id FROM h_order WHERE id='$oid' $uidok"));
    if (!$row) error_response('Service not found', 404);

    $ctx = hosting_context($oid);
    if (!$ctx['server']) error_response('Server not configured for this account.');
    $username = decode($ctx['store']['auser'] ?? '', KEY_ONE);
    if (!$username) error_response('No hosting account username on file.');

    $result = whm_change_password($ctx['server'], $username, $newPass);
    if (!$result['ok']) error_response('Password change failed: ' . $result['message']);

    $passEnc = encode($newPass, KEY_ONE);
    mysqli_query($conn, "UPDATE h_store SET apass='$passEnc' WHERE id='{$ctx['order']['sid']}'");
    success_response([], 'cPanel password changed.');
}

function suspend() {
    require_admin();
    global $conn;
    $oid = (int)($_GET['oid'] ?? 0);
    $reason = mysqli_real_escape_string($conn, $_GET['reason'] ?? 'Non-payment');

    $ctx = hosting_context($oid);
    if (!$ctx || !$ctx['server']) error_response('Server not configured for this account.');
    $username = decode($ctx['store']['auser'] ?? '', KEY_ONE);
    if (!$username) error_response('No hosting account username on file.');

    $result = whm_suspend($ctx['server'], $username, $reason);
    if (!$result['ok']) error_response('Suspend failed: ' . $result['message']);

    mysqli_query($conn, "UPDATE h_order SET status='2', reson='$reason' WHERE id='$oid'");
    success_response([], 'Account suspended.');
}

function unsuspend() {
    require_admin();
    global $conn;
    $oid = (int)($_GET['oid'] ?? 0);

    $ctx = hosting_context($oid);
    if (!$ctx || !$ctx['server']) error_response('Server not configured for this account.');
    $username = decode($ctx['store']['auser'] ?? '', KEY_ONE);
    if (!$username) error_response('No hosting account username on file.');

    $result = whm_unsuspend($ctx['server'], $username);
    if (!$result['ok']) error_response('Unsuspend failed: ' . $result['message']);

    mysqli_query($conn, "UPDATE h_order SET status='1' WHERE id='$oid'");
    success_response([], 'Account unsuspended.');
}

function info() {
    require_admin();
    $oid = (int)($_GET['oid'] ?? 0);
    $ctx = hosting_context($oid);
    if (!$ctx || !$ctx['server']) error_response('Server not configured for this account.');
    $username = decode($ctx['store']['auser'] ?? '', KEY_ONE);
    if (!$username) error_response('No hosting account username on file.');

    $result = whm_account_summary($ctx['server'], $username);
    if (!$result['ok']) error_response('Could not fetch account info: ' . $result['message']);

    success_response(['info' => $result['data']['acct'][0] ?? []]);
}

/**
 * Creates the real WHM account for an order and records its credentials in
 * h_store. Called directly by admin, and also by payments.php@captureOrder
 * right after a hosting invoice is paid.
 */
function provision_order($oid) {
    global $conn, $now;
    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_order WHERE id='$oid'"));
    if (!$row) return ['ok' => false, 'message' => 'Order not found.'];

    $pid = (int)substr($row['package'], 1);
    $prod = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_product WHERE id='$pid'"));
    if (!$prod) return ['ok' => false, 'message' => 'Product not found for this order.'];

    $domain = explode(',', decode($row['domain'] ?? '', KEY_ONE))[0] ?? '';
    $user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT email FROM h_user WHERE id='{$row['uid']}'"));

    $server = whm_resolve_server($row['srv'] ?: 1);
    if (!$server) return ['ok' => false, 'message' => 'No server configured to provision this account.'];

    $username = substr(preg_replace('/[^a-z0-9]/', '', strtolower(explode('.', $domain)[0] ?? '')), 0, 8) ?: ('u' . $oid);
    $password = bin2hex(random_bytes(6));

    $result = whm_create_account($server, $username, $password, $domain, $prod['pkname'], $user['email'] ?? '');
    if (!$result['ok']) return ['ok' => false, 'message' => $result['message']];

    $userEnc = encode($username, KEY_ONE);
    $passEnc = encode($password, KEY_ONE);
    mysqli_query($conn, "INSERT INTO h_store (uid,package,auser,apass,sdate,date,status) VALUES ('{$row['uid']}','{$row['package']}','$userEnc','$passEnc','$now','$now','Sold')");
    $sid = mysqli_insert_id($conn);

    mysqli_query($conn, "UPDATE h_order SET sid='$sid', status='1' WHERE id='$oid'");
    return ['ok' => true, 'username' => $username];
}

function provision() {
    require_admin();
    $oid = (int)($_POST['oid'] ?? 0);
    $result = provision_order($oid);
    if (!$result['ok']) error_response('Provisioning failed: ' . $result['message']);
    success_response(['username' => $result['username']], 'Account provisioned.');
}

function sendDetails() {
    require_admin();
    global $conn;
    $oid = (int)($_GET['oid'] ?? 0);
    $ctx = hosting_context($oid);
    if (!$ctx) error_response('Order not found', 404);

    $user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name, email FROM h_user WHERE id='{$ctx['order']['uid']}'"));
    if (!$user || empty($ctx['store'])) error_response('No account details to send yet.');

    $domain = explode(',', decode($ctx['order']['domain'] ?? '', KEY_ONE))[0] ?? '';
    $username = decode($ctx['store']['auser'] ?? '', KEY_ONE);
    $password = decode($ctx['store']['apass'] ?? '', KEY_ONE);

    $body = "Dear {$user['name']}<br><br>Your hosting account is ready.<br><br>"
          . "Domain: $domain<br>cPanel Username: $username<br>cPanel Password: $password<br><br>"
          . "Please log in and change your password as soon as possible.<br><br>Host25Cent.com";

    require_once __DIR__ . '/../config/mail.php';
    $mail = make_mailer('info@host25cent.com', 'Host25Cent', 'info@host25cent.com');
    $mail->AddAddress($user['email']);
    $mail->Subject = 'Your Hosting Account Details';
    $mail->MsgHTML($body);
    $mail->IsHTML(true);
    $mail->Send();

    success_response([], 'Details email sent.');
}
