<?php
/**
 * compra-pendientes.php
 * GET ?id_inv=X
 * Devuelve cantidad de regalías pendientes (regs2 status=0) y
 * cantidad + monto total de vouchers pendientes (voucher status=0)
 * para el distribuidor con id_inver = X
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

require_once __DIR__ . '/../../config.php';
$db = getDB();

// ── Validar token ─────────────────────────────────────────────────────────────
$headers    = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
if (!preg_match('/Bearer\s+(.+)/i', $authHeader, $m)) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Token requerido']);
    exit;
}
$token = trim($m[1]);
$stmtTok = $db->prepare("SELECT idusuarios_sist FROM admin_sessions WHERE token = ? AND expira > NOW()");
$stmtTok->execute([$token]);
if (!$stmtTok->fetch()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Sesion invalida o expirada']);
    exit;
}

$id_inv = (int)($_GET['id_inv'] ?? 0);
if (!$id_inv) {
    echo json_encode(['ok' => false, 'error' => 'id_inv requerido']);
    exit;
}

try {
    // ── Regalías pendientes (regs2 status=0) ──────────────────────────────────
    $stmtR = $db->prepare("
        SELECT COUNT(*) as cantidad, COALESCE(SUM(apagar), 0) as monto
        FROM regs2
        WHERE id_inver = ? AND status = 0
    ");
    $stmtR->execute([$id_inv]);
    $regs = $stmtR->fetch(PDO::FETCH_ASSOC);

    // ── Vouchers pendientes (voucher status=0) ─────────────────────────────────
    $stmtV = $db->prepare("
        SELECT COUNT(*) as cantidad, COALESCE(SUM(restante), 0) as monto
        FROM voucher
        WHERE id_inv = ? AND status = 0
    ");
    $stmtV->execute([$id_inv]);
    $vouchers = $stmtV->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        'ok'      => true,
        'regalias' => [
            'cantidad' => (int)$regs['cantidad'],
            'monto'    => (float)$regs['monto'],
        ],
        'vouchers' => [
            'cantidad' => (int)$vouchers['cantidad'],
            'monto'    => (float)$vouchers['monto'],
        ],
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
