<?php

require_once __DIR__ . '/../config.php';

requireAdmin();

$db = getDB();

try {
    // Total distribuidores activos
    $stmt = $db->query('SELECT COUNT(*) as total FROM inversionista WHERE estatus_idestatus = 1');
    $totalDistribuidores = (int)($stmt->fetch()['total'] ?? 0);

    // Transacciones del mes
    $mesInicio = date('Y-m-01');
    $mesFin = date('Y-m-t');
    $stmt = $db->prepare('SELECT COUNT(*) as total FROM transacciones WHERE fechat BETWEEN ? AND ?');
    $stmt->execute([$mesInicio, $mesFin]);
    $transaccionesMes = (int)($stmt->fetch()['total'] ?? 0);

    // Ventas del mes (tipo 10 = venta confirmada)
    $stmt = $db->prepare('
        SELECT COALESCE(SUM(d.cantidad), 0) as total 
        FROM transacciones t 
        JOIN depositos d ON t.idtransacciones = d.transacciones_idtransacciones 
        WHERE t.tipostr_idtipostr = 10 AND t.fechat BETWEEN ? AND ?
    ');
    $stmt->execute([$mesInicio, $mesFin]);
    $ventasMes = (float)($stmt->fetch()['total'] ?? 0);

    // Puntos generados este mes
    $stmt = $db->prepare('
        SELECT COALESCE(SUM(d.puntos), 0) as total 
        FROM transacciones t 
        JOIN depositos d ON t.idtransacciones = d.transacciones_idtransacciones 
        WHERE t.fechat BETWEEN ? AND ?
    ');
    $stmt->execute([$mesInicio, $mesFin]);
    $puntosMes = (float)($stmt->fetch()['total'] ?? 0);

    // Ganancias pendientes (regs2 con status = 0)
    $stmt = $db->query('SELECT COALESCE(SUM(apagar), 0) as total FROM regs2 WHERE status = 0');
    $gananciasPendientes = (float)($stmt->fetch()['total'] ?? 0);

    // Ventas últimos 6 meses
    $hace6meses = date('Y-m-01', strtotime('-6 months'));
    $stmt = $db->prepare('
        SELECT DATE_FORMAT(t.fechat, "%Y-%m") as mes, COALESCE(SUM(d.cantidad), 0) as total
        FROM transacciones t
        JOIN depositos d ON t.idtransacciones = d.transacciones_idtransacciones
        WHERE t.tipostr_idtipostr = 10 AND t.fechat >= ?
        GROUP BY DATE_FORMAT(t.fechat, "%Y-%m")
        ORDER BY mes ASC
        LIMIT 6
    ');
    $stmt->execute([$hace6meses]);
    $ventasUltimos6 = $stmt->fetchAll();

    // Distribuidores nuevos por mes (últimos 6 meses)
    $stmt = $db->prepare('
        SELECT DATE_FORMAT(estampa, "%Y-%m") as mes, COUNT(*) as total
        FROM inversionista
        WHERE estampa >= ?
        GROUP BY DATE_FORMAT(estampa, "%Y-%m")
        ORDER BY mes ASC
        LIMIT 6
    ');
    $stmt->execute([$hace6meses]);
    $distNuevos = $stmt->fetchAll();

    // Órdenes pendientes (tipo 7 y 8)
    $stmt = $db->query('SELECT COUNT(*) as total FROM transacciones WHERE tipostr_idtipostr IN (7, 8)');
    $ordenesPendientes = (int)($stmt->fetch()['total'] ?? 0);

    jsonOk([
        'totalDistribuidores' => $totalDistribuidores,
        'transaccionesMes' => $transaccionesMes,
        'ventasMes' => $ventasMes,
        'puntosMes' => $puntosMes,
        'gananciasPendientes' => $gananciasPendientes,
        'ordenesPendientes' => $ordenesPendientes,
        'ventasUltimos6' => $ventasUltimos6,
        'distribuidoresNuevos' => $distNuevos,
    ]);

} catch (Throwable $e) {
    jsonErr(500, 'Error en dashboard: ' . $e->getMessage());
}
