<?php
// ─── Orders / Checkout API ───────────────────────────────────────────────────
// v1 never had a working checkout (buy.php/cart.php/checkout.php were all
// missing from that codebase) — this is designed fresh. Coupons are fully
// database-driven (core/coupons.php, h_coupon/h_coupon_usage) and domain
// pricing/availability comes from shopping every active registrar for the
// cheapest option (core/registrars.php@shop_domain) — nothing hardcoded.

function cart() {
    global $conn;
    $pid  = (int)($_GET['pid'] ?? 0);

    $prod = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_product WHERE id='$pid' AND status='0'"));
    if (!$prod) error_response('Product not found', 404);

    // Every plan has exactly two real billing options: its own minimum cycle
    // (fmonth months for fprice) and annual (12 months for yprice) — fmonth is
    // NOT always 1, e.g. a plan can be billed every 3 or 6 months at minimum.
    success_response([
        'pid' => $pid, 'name' => $prod['pkname'], 'htype' => $prod['htype'],
        'fprice' => (float)$prod['fprice'], 'fmonth' => (int)$prod['fmonth'], 'yprice' => (float)$prod['yprice']
    ]);
}

function coupon() {
    $uid = require_login();
    global $conn;
    $code = trim($_GET['code'] ?? '');
    $pid  = (int)($_GET['pid'] ?? 0);
    $term = ($_GET['term'] ?? 'm') === 'y' ? 'y' : 'm';

    $prod = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_product WHERE id='$pid' AND status='0'"));
    if (!$prod) error_response('Product not found', 404);
    $price = ($term === 'm') ? $prod['fprice'] : $prod['yprice'];

    require_once __DIR__ . '/../core/coupons.php';
    $result = validate_coupon($code, $pid, $price, $uid);
    if (!$result['ok']) error_response($result['message']);

    success_response(['discounted_price' => $result['discounted_price']], $result['message']);
}

function checkout() {
    $uid = require_login();
    global $conn, $now;

    $pid    = (int)($_POST['pid'] ?? 0);
    $term   = ($_POST['term'] ?? 'm') === 'y' ? 'y' : 'm';
    $coupon = trim($_POST['coupon'] ?? '');
    $domainAction = in_array($_POST['domain_action'] ?? '', ['own', 'free', 'buy']) ? $_POST['domain_action'] : 'own';

    if (!$pid) error_response('Please choose a plan.');

    $prod = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_product WHERE id='$pid' AND status='0'"));
    if (!$prod) error_response('Product not found', 404);

    $price  = ($term === 'm') ? $prod['fprice'] : $prod['yprice'];
    $months = ($term === 'm') ? $prod['fmonth'] : 12;

    $couponId = null;
    if ($coupon !== '') {
        require_once __DIR__ . '/../core/coupons.php';
        $result = validate_coupon($coupon, $pid, $price, $uid);
        if (!$result['ok']) error_response($result['message']);
        $price = $result['discounted_price'];
        $couponId = $result['coupon_id'];
    }

    $domainPrice = 0;
    $registrarId = null;
    require_once __DIR__ . '/../core/registrars.php';
    require_once __DIR__ . '/../config/domains.php'; // free_domain_threshold()/tld_is_free()

    if ($domainAction === 'own') {
        // Customer already owns this domain elsewhere — no registration, no availability check.
        $domain = strtolower(trim($_POST['domain'] ?? ''));
        if ($domain === '' || !preg_match('/^[a-z0-9.-]+\.[a-z]{2,}$/', $domain)) {
            error_response('Please enter a valid domain name.');
        }
    } elseif ($domainAction === 'buy') {
        // Any TLD is allowed — shop every active registrar and use the cheapest available.
        $domain = strtolower(trim($_POST['domain'] ?? ''));
        if ($domain === '' || !preg_match('/^[a-z0-9.-]+\.[a-z]{2,}$/', $domain)) {
            error_response('Please enter a valid domain name.');
        }
        $shop = shop_domain($domain);
        if (!$shop['ok']) error_response($shop['message']);
        if (empty($shop['available'])) error_response('That domain is no longer available — please choose another.');

        $domainPrice = $shop['price'];
        $registrarId = $shop['registrar_id']; // recorded now, used at registration time — never re-shopped
    } else {
        // 'free' — name+TLD chosen from the admin-curated allow-list (js/hosting.js's
        // Checkout populates the TLD <select> from domains/tlds). Still shopped for a
        // real price, which must fall at/under the threshold to actually be free.
        $name  = strtolower(trim($_POST['domain_name'] ?? ''));
        $tldId = (int)($_POST['tld_id'] ?? 0);
        if ($name === '' || !preg_match('/^[a-z0-9-]+$/', $name)) error_response('Please enter a valid domain name.');

        $tldRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_tld WHERE id='$tldId' AND status='1'"));
        if (!$tldRow) error_response('Please choose a valid domain extension.');

        $domain = $name . '.' . $tldRow['tld'];
        $shop = shop_domain($domain);
        if (!$shop['ok']) error_response($shop['message']);
        if (empty($shop['available'])) error_response('That domain is no longer available — please choose another.');
        if (!tld_is_free($shop['price'])) {
            error_response('That domain doesn\'t qualify as a free domain right now (' . number_format($shop['price'], 2) . ') — choose another, or select "Register a new domain" instead.');
        }

        $domainPrice = 0;
        $registrarId = $shop['registrar_id'];
    }

    // Domain add-on: 'buy' adds the shopped registration price to the invoice; 'free' is
    // included at no extra charge; 'own' means no registration happens at all.
    $totalPrice = round($price + $domainPrice, 2);

    $domainEnc = encode($domain, KEY_ONE);
    $package   = $term . $pid;
    $exDate    = date('Y-m-d', strtotime("+$months months"));
    $domainActionSafe = mysqli_real_escape_string($conn, $domainAction);
    $registrarIdSql = $registrarId !== null ? (int)$registrarId : 'NULL';

    // Order first (status 0 = pending/unpaid), then its invoice, then link them —
    // mirrors the two-step insert already used in services.php@renew/@upgrade.
    // domain_action + registrar_id are read back by payments.php@settle_invoice()
    // once this invoice is paid, to register the domain via the SAME registrar
    // that was shopped here (never re-shopped, so the price quoted stays honored).
    mysqli_query($conn, "INSERT INTO h_order (uid,package,domain,status,date,domain_action,registrar_id)
        VALUES ('$uid','$package','$domainEnc','0','$now','$domainActionSafe',$registrarIdSql)");
    $oid = mysqli_insert_id($conn);

    mysqli_query($conn, "INSERT INTO h_invoice (uid,oid,item,price,domp,date,exdate,status) VALUES ('$uid','$oid','$package','$totalPrice','$domainPrice','$now','$exDate','0')");
    $iid = mysqli_insert_id($conn);

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

    if ($couponId) {
        require_once __DIR__ . '/../core/coupons.php';
        record_coupon_usage($couponId, $uid, $oid);
    }

    success_response([
        'oid' => encode($oid, KEY_ONE),
        'iid' => encode($iid, KEY_ONE)
    ], 'Order created. Please complete payment to activate your service.');
}
