<?php
// ─── Invoices API ──────────────────────────────────────────────────────────

function invoiceList() {
    $uid = require_login();
    global $conn, $now;
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";
    
    $rss = mysqli_query($conn, "SELECT * FROM h_invoice WHERE status!='4' $uidok ORDER BY id DESC LIMIT 50");
    $items = [];
    while ($row = mysqli_fetch_assoc($rss)) {
        $items[] = [
            'id' => $row['id'],
            'iid_enc' => encode($row['id'], KEY_ONE),
            'oid' => $row['oid'],
            'uid' => $row['uid'],
            'price' => $row['price'],
            'date' => $row['date'],
            'exdate' => $row['exdate'],
            'status' => (int)$row['status']
        ];
    }
    success_response(['items' => $items]);
}

function detail() {
    $uid = require_login();
    global $conn;
    $iid = (int)decode($_GET['iid'] ?? '', KEY_ONE);
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";

    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_invoice WHERE id='$iid' $uidok"));
    if (!$row) error_response('Invoice not found', 404);

    $order = mysqli_fetch_assoc(mysqli_query($conn, "SELECT domain FROM h_order WHERE iid='$iid'"));
    $domain = $order ? (explode(',', decode($order['domain'] ?? '', KEY_ONE))[0] ?? '') : '';

    success_response([
        'id'      => $row['id'],
        'iid_enc' => encode($row['id'], KEY_ONE),
        'oid'     => $row['oid'],
        'oid_enc' => encode($row['oid'], KEY_ONE),
        'item'    => $row['item'],
        'domain'  => $domain,
        'price'   => $row['price'],
        'date'    => $row['date'],
        'exdate'  => $row['exdate'],
        'status'  => (int)$row['status']
    ]);
}

