<?php
// ─── Payments API ────────────────────────────────────────────────────────────
require_once __DIR__ . '/../config/payments.php';
require_once __DIR__ . '/hosting.php';        // provision_order()
require_once __DIR__ . '/../core/registrars.php'; // registrar_register_domain_via()

function config() {
    $btcConfigured = BTC_WALLET_ADDRESS !== '' && BTC_WALLET_ADDRESS !== 'PUT_YOUR_BTC_WALLET_ADDRESS_HERE';
    success_response([
        'paypalClientId' => paypal_configured() ? PAYPAL_CLIENT_ID : '',
        'btcAddress'     => $btcConfigured ? BTC_WALLET_ADDRESS : '',
    ]);
}

function invoice_for_payment($iidEnc, $uid) {
    global $conn;
    $iid = (int)decode($iidEnc, KEY_ONE);
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";
    return mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_invoice WHERE id='$iid' $uidok"));
}

function createOrder() {
    $uid = require_login();
    if (!paypal_configured()) error_response('PayPal is not configured yet.');

    $inv = invoice_for_payment($_POST['iid'] ?? '', $uid);
    if (!$inv) error_response('Invoice not found', 404);
    if ((int)$inv['status'] !== 0) error_response('This invoice is not payable.');

    $result = paypal_create_order($inv['price']);
    if (!$result['ok']) error_response('Could not create PayPal order: ' . $result['message']);

    success_response(['orderId' => $result['data']['id']]);
}

function captureOrder() {
    $uid = require_login();
    if (!paypal_configured()) error_response('PayPal is not configured yet.');

    $inv = invoice_for_payment($_POST['iid'] ?? '', $uid);
    if (!$inv) error_response('Invoice not found', 404);
    if ((int)$inv['status'] !== 0) success_response([], 'Invoice already settled.');

    $result = paypal_capture_order($_POST['orderId'] ?? '');
    if (!$result['ok']) error_response('Payment capture failed: ' . $result['message']);

    $captured = $result['data']['purchase_units'][0]['payments']['captures'][0] ?? null;
    if (!$captured || $captured['status'] !== 'COMPLETED') error_response('Payment was not completed.');

    // Never trust the client for the amount — only what PayPal actually captured.
    $capturedAmount = (float)($captured['amount']['value'] ?? 0);
    if (abs($capturedAmount - (float)$inv['price']) > 0.01) {
        error_response('Captured amount does not match the invoice.');
    }

    settle_invoice($inv);
    success_response([], 'Payment received — your service is being activated.');
}

function btcClaim() {
    $uid = require_login();
    global $conn;

    $inv = invoice_for_payment($_POST['iid'] ?? '', $uid);
    if (!$inv) error_response('Invoice not found', 404);

    $user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name, email FROM h_user WHERE id='{$inv['uid']}'"));

    require_once __DIR__ . '/../config/mail.php';
    try {
        $mail = make_mailer('info@host25cent.com', 'Host25Cent', 'info@host25cent.com');
        $mail->AddAddress('info@host25cent.com');
        $mail->Subject = "BTC payment claim - Invoice #{$inv['id']}";
        $mail->MsgHTML("{$user['name']} ({$user['email']}) claims to have paid invoice #{$inv['id']} (\${$inv['price']}) via BTC. "
            . "Please verify on-chain and mark it paid from the admin Invoices page.");
        $mail->IsHTML(true);
        $mail->Send();
    } catch (Exception $e) { /* still acknowledge the claim even if the notification email fails */ }

    success_response([], 'Thanks — we will verify the transaction and activate your service shortly.');
}

/**
 * Flips an invoice/order to Paid and triggers the matching provisioning
 * action — real WHM account creation, plus real domain registration when the
 * customer chose "free domain" or "register a new domain" at checkout.
 * (Domains are never sold standalone on this platform — see domains.php.)
 */
function settle_invoice($inv) {
    global $conn;
    $iid = $inv['id'];
    $oid = $inv['oid'];

    mysqli_query($conn, "UPDATE h_invoice SET status='1' WHERE id='$iid'");
    mysqli_query($conn, "UPDATE h_order SET status='1' WHERE id='$oid'");

    $order = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_order WHERE id='$oid'"));
    if (!$order) return;

    if (empty($order['sid'])) provision_order($oid);

    $domainAction = $order['domain_action'] ?? 'own';
    if (in_array($domainAction, ['free', 'buy'])) {
        register_domain_for_order($order, 1);
    }
}

/**
 * Registers a paid-for domain via the SPECIFIC registrar that was shopped and
 * recorded on the order at checkout time (h_order.registrar_id) — never
 * re-shopped, so the price the customer was quoted is what's honored.
 */
function register_domain_for_order($order, $years) {
    $domain = explode(',', decode($order['domain'] ?? '', KEY_ONE))[0] ?? '';
    if (!$domain || empty($order['registrar_id'])) return;
    require_once __DIR__ . '/../config/servers.php';
    registrar_register_domain_via($order['registrar_id'], $domain, $years, $ns1, $ns2);
}
