<?php
// ─── Services API ────────────────────────────────────────────────────────────

function serviceList() {
    $uid = require_login();
    global $conn;
    
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";
    [$start, $perpage] = get_pagination_params();
    $status = isset($_GET['status']) ? (int)$_GET['status'] : null;
    $search = $_GET['search'] ?? '';
    
    $where = "WHERE status!='4' $uidok";
    if ($status !== null) $where .= " AND status='$status'";
    if ($search) {
        $srch = encode(strtolower($search), KEY_ONE);
        $where .= " AND (domain LIKE '%$srch%' OR id='" . (int)$search . "')";
    }
    
    $count = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM h_order $where"))['total'];
    $rss = mysqli_query($conn, "SELECT * FROM h_order $where ORDER BY id DESC LIMIT $start,$perpage");
    
    $services = [];
    while ($row = mysqli_fetch_assoc($rss)) {
        $dom = explode(',', decode($row['domain'] ?? '', KEY_ONE));
        $services[] = [
            'id'     => $row['id'],
            'uid'    => $row['uid'],
            'package' => $row['package'],
            'domain'  => $dom[0] ?? '',
            'status'  => (int)$row['status'],
            'date'    => $row['date'],
            'sid'     => $row['sid'],
            'iid'     => $row['iid'],
            'srv'     => $row['srv']
        ];
    }
    
    success_response([
        'items' => $services,
        'total' => $count,
        'start' => $start,
        'perpage' => $perpage
    ]);
}

function detail() {
    $uid = require_login();
    global $conn;
    
    $oid = (int)($_GET['oid'] ?? 0);
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";
    
    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_order WHERE id='$oid' $uidok"));
    if (!$row) error_response('Service not found', 404);
    
    $dom = explode(',', decode($row['domain'] ?? '', KEY_ONE));
    
    // Get invoice
    $inv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_invoice WHERE id='{$row['iid']}' $uidok")) ?: [];
    
    // Get store credentials
    $store = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_store WHERE id='{$row['sid']}'")) ?: [];
    
    // Get user
    $user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name, email, phone FROM h_user WHERE id='{$row['uid']}'"));

    // Plan pricing — fmonth is the plan's own minimum billing cycle length in
    // months (not always 1), used to label the real renewal/upgrade options.
    $pid = (int)substr($row['package'] ?? '', 1);
    $prod = mysqli_fetch_assoc(mysqli_query($conn, "SELECT pkname, fprice, fmonth, yprice FROM h_product WHERE id='$pid'")) ?: [];

    success_response([
        'id'          => $row['id'],
        'uid'         => $row['uid'],
        'package'     => $row['package'],
        'domain'      => $dom[0] ?? '',
        'date'        => $row['date'],
        'status'      => (int)$row['status'],
        'sid'         => $row['sid'],
        'iid'         => $row['iid'],
        'srv'         => $row['srv'],
        'reson'       => $row['reson'] ?? '',
        'username'    => $store ? decode($store['auser'] ?? '', KEY_ONE) : '',
        'password'    => $store ? decode($store['apass'] ?? '', KEY_ONE) : '',
        'cpanel'      => $user['name'] ?? '',
        'email'       => $user['email'] ?? '',
        'phone'       => $user['phone'] ?? '',
        'inv_date'    => $inv['date'] ?? '',
        'inv_exdate'  => $inv['exdate'] ?? '',
        'inv_status'  => (int)($inv['status'] ?? 0),
        'inv_price'   => $inv['price'] ?? '0',
        'inv_domp'    => $inv['domp'] ?? '0',
        'plan_name'   => $prod['pkname'] ?? '',
        'fprice'      => isset($prod['fprice']) ? (float)$prod['fprice'] : null,
        'fmonth'      => isset($prod['fmonth']) ? (int)$prod['fmonth'] : null,
        'yprice'      => isset($prod['yprice']) ? (float)$prod['yprice'] : null
    ]);
}

function featured() {
    global $conn;
    $stmt = $conn->prepare("SELECT * FROM h_product WHERE ((id<=3) OR (id>=7 AND id<=9) OR (id>=17 AND id<=19) OR (id>=20 AND id<=22)) AND status='0' ORDER BY id ASC LIMIT 12");
    $stmt->execute();
    $products = [];
    foreach ($stmt->get_result() as $row) {
        $save1 = $row['price'] * 12;
        $save = ($save1 > 0) ? number_format((1 - $row['yprice'] / $save1) * 100, 0) : 0;
        $hhost = ($row['id'] <= 6) ? 'host' : 'rhost';
        $products[] = [
            'id' => $row['id'],
            'name' => $row['pkname'],
            'space' => $row['space'],
            'band' => $row['band'],
            'htype' => $row['htype'],
            'price' => $row['price'],
            'fprice' => $row['fprice'],
            'yprice' => $row['yprice'],
            'fmonth' => $row['fmonth'],
            'cpanel' => $row['cpanel'],
            'save' => $save . '%',
            'is_nvme' => ($row['id'] >= 17)
        ];
    }
    success_response($products);
}

function packages() {
    global $conn;
    $htype = $_GET['type'] ?? 'Hosting';
    $hid   = isset($_GET['hid']) ? (int)$_GET['hid'] : 0;
    
    $where = $hid ? "id='$hid'" : "htype='" . mysqli_real_escape_string($conn, $htype) . "' AND status='0'";
    $stmt = $conn->prepare("SELECT * FROM h_product WHERE $where ORDER BY price ASC LIMIT 12");
    $stmt->execute();
    
    $products = [];
    foreach ($stmt->get_result() as $row) {
        $save1 = $row['price'] * 12;
        $save = ($save1 > 0) ? number_format((1 - $row['yprice'] / $save1) * 100, 0) : 0;
        $products[] = [
            'id' => $row['id'],
            'name' => $row['pkname'],
            'space' => $row['space'],
            'band' => $row['band'],
            'htype' => $row['htype'],
            'price' => $row['price'],
            'fprice' => $row['fprice'],
            'yprice' => $row['yprice'],
            'fmonth' => $row['fmonth'],
            'cpanel' => $row['cpanel'],
            'whm' => $row['whm'],
            'save' => $save . '%',
            'is_nvme' => ($row['id'] >= 17)
        ];
    }
    success_response($products);
}

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

    $oid = (int)($_POST['oid'] ?? $_GET['oid'] ?? 0);
    $opk = $_POST['opk'] ?? $_GET['opk'] ?? '';
    $newPk = $_POST['ph'] ?? $_GET['ph'] ?? '';

    if (!$oid || !$newPk) error_response('Missing parameters.');

    $curPid = (int)substr($opk, 1);
    $newPid = (int)substr($newPk, 1);
    $curBt = substr($opk, 0, 1);
    $newBt = substr($newPk, 0, 1);

    $cur = mysqli_fetch_assoc(mysqli_query($conn, "SELECT fprice,yprice,fmonth FROM h_product WHERE id='$curPid'"));
    $new = mysqli_fetch_assoc(mysqli_query($conn, "SELECT fprice,yprice,fmonth FROM h_product WHERE id='$newPid'"));
    if (!$cur || !$new) error_response('Product not found.');

    $curPrice = ($curBt === 'm') ? $cur['fprice'] : $cur['yprice'];
    $newPrice = ($newBt === 'm') ? $new['fprice'] : $new['yprice'];
    $upgCost = number_format(max(0, $newPrice - $curPrice), 2);
    
    $last = mysqli_fetch_assoc(mysqli_query($conn, "SELECT exdate FROM h_invoice WHERE oid='$oid' ORDER BY id DESC LIMIT 1"));
    $exDate = $last['exdate'] ?? date('Y-m-d');
    
    mysqli_query($conn, "INSERT INTO h_invoice (uid,oid,item,price,date,exdate,status) 
        VALUES ('$uid','$oid','$newPk','$upgCost','$now','$exDate','0')");
    $iid = mysqli_insert_id($conn);
    
    success_response(['iid' => encode($iid, KEY_ONE)], 'Upgrade invoice created.');
}

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

    // services/detail hands the frontend a raw (unencoded) order id, and this is
    // called both as a GET (query string) and POST (form body) action elsewhere,
    // so accept oid/pk from either.
    $oid = (int)($_POST['oid'] ?? $_GET['oid'] ?? 0);
    $pk  = $_POST['pk'] ?? $_GET['pk'] ?? '';

    if (!$oid || !$pk) error_response('Missing parameters.');

    $bt = substr($pk, 0, 1);
    $pid = (int)substr($pk, 1);
    $prod = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_product WHERE id='$pid'"));
    if (!$prod) error_response('Product not found.');

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

    $last = mysqli_fetch_assoc(mysqli_query($conn, "SELECT exdate FROM h_invoice WHERE oid='$oid' ORDER BY id DESC LIMIT 1"));
    $baseDate = $last['exdate'] ?? date('Y-m-d');
    $newExDate = date('Y-m-d', strtotime("$baseDate +$months months"));

    mysqli_query($conn, "INSERT INTO h_invoice (uid,oid,item,price,date,exdate,status)
        VALUES ('$uid','$oid','$pk','$price','$now','$newExDate','0')");
    $iid = mysqli_insert_id($conn);

    success_response(['iid' => encode($iid, KEY_ONE)], 'Renewal invoice created.');
}

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

    $oid = (int)($_POST['oid'] ?? $_GET['oid'] ?? 0);
    $iid = (int)($_POST['iid'] ?? $_GET['iid'] ?? 0);
    $status = (($_POST['sta'] ?? $_GET['sta'] ?? '') == '4') ? 0 : 4;

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

    success_response([], ($status == 0) ? 'Service restored.' : 'Service deleted.');
}

function updateDomain() {
    $uid = require_login();
    global $conn;
    
    $domain = mysqli_real_escape_string($conn, $_POST['domain'] ?? '');
    $domainok = encode($domain, KEY_ONE);
    $pakpak = mysqli_real_escape_string($conn, $_POST['pakpak'] ?? '');
    $oid = (int)$_POST['oid'];
    
    mysqli_query($conn, "UPDATE h_order SET domain='$domainok', package='$pakpak' WHERE id=$oid");
    success_response([], 'Domain updated.');
}