<?php
/**
 * ARCHIVO: api_logic/ventas.php
 * DESCRIPCIÓN: Motor central definitivo (Ventas, KPIs, Reportes, Kardex y Vencimientos).
 * VERSIÓN: Blindada con corrección de variable para evitar "undefined días".
 */

// =========================================================================
// 0. AUTO-MANTENIMIENTO DE BASE DE DATOS
// =========================================================================
$conn->query("CREATE TABLE IF NOT EXISTS `detalle_venta` (
  `id_detalle` int(11) NOT NULL AUTO_INCREMENT,
  `id_venta` int(11) NOT NULL,
  `id_producto` int(11) NOT NULL,
  `cantidad` decimal(12,2) NOT NULL,
  `precio_unitario` decimal(10,2) NOT NULL,
  `subtotal` decimal(10,2) NOT NULL,
  PRIMARY KEY (`id_detalle`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

$conn->query("ALTER TABLE ventas ADD COLUMN IF NOT EXISTS monto_pago DECIMAL(10,2) DEFAULT 0.00");
$conn->query("ALTER TABLE ventas ADD COLUMN IF NOT EXISTS vuelto DECIMAL(10,2) DEFAULT 0.00");
$conn->query("ALTER TABLE ventas ADD COLUMN IF NOT EXISTS id_caja INT(11) NULL");
$conn->query("ALTER TABLE ventas ADD COLUMN IF NOT EXISTS serie VARCHAR(20) NULL");
$conn->query("ALTER TABLE ventas ADD COLUMN IF NOT EXISTS correlativo INT(11) NULL");

$conn->query("ALTER TABLE egresos ADD COLUMN IF NOT EXISTS id_usuario INT(11) NOT NULL");
$conn->query("ALTER TABLE egresos ADD COLUMN IF NOT EXISTS id_caja INT(11) NULL");

$conn->query("CREATE TABLE IF NOT EXISTS `kardex` (
  `id_kardex` int(11) NOT NULL AUTO_INCREMENT,
  `id_producto` int(11) NOT NULL,
  `id_usuario` int(11) NOT NULL,
  `tipo` enum('ENTRADA','SALIDA') NOT NULL,
  `cantidad` decimal(12,2) NOT NULL,
  `motivo` varchar(255) DEFAULT NULL,
  `fecha` datetime DEFAULT current_timestamp(),
  PRIMARY KEY (`id_kardex`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

// =========================================================================
// 1. REPORTE FILTRADO DE VENTAS
// =========================================================================
if ($task == 'filtered_report') {
    $ini = !empty($_GET['ini']) ? $_GET['ini'] : date('Y-m-d');
    $fin = !empty($_GET['fin']) ? $_GET['fin'] : date('Y-m-d');
    
    $sql = "SELECT 
                v.id_venta AS id, 
                v.fecha_venta AS fecha, 
                v.monto_total AS total, 
                v.tipo_pago AS pago, 
                v.estado_venta AS estado,
                COALESCE(c.nombre, 'Público General') AS cliente,
                COALESCE((SELECT GROUP_CONCAT(p.nombre SEPARATOR ', ') 
                 FROM detalle_venta dv 
                 INNER JOIN productos p ON dv.id_producto = p.id_producto 
                 WHERE dv.id_venta = v.id_venta), 'Sin detalle') AS productos,
                COALESCE((SELECT SUM(dv.cantidad) 
                 FROM detalle_venta dv 
                 WHERE dv.id_venta = v.id_venta), 0) AS unidades
            FROM ventas v
            LEFT JOIN clientes c ON v.id_cliente = c.id_cliente
            WHERE DATE(v.fecha_venta) >= '$ini' AND DATE(v.fecha_venta) <= '$fin'
            ORDER BY v.id_venta DESC";
            
    $res = $conn->query($sql);
    
    if (!$res) {
        echo json_encode(['success' => false, 'error' => "Fallo SQL: " . $conn->error]);
        exit;
    }

    $rows = [];
    $suma_total = 0;

    while($r = $res->fetch_assoc()) {
        if($r['estado'] !== 'ANULADA') {
            $suma_total += (float)$r['total'];
        }
        $r['id'] = (int)$r['id'];
        $r['total'] = (float)$r['total'];
        $r['unidades'] = (float)$r['unidades'];
        $rows[] = $r;
    }
    
    echo json_encode([
        'success' => true, 
        'data_rows' => $rows, 
        'monto_global' => (float)$suma_total
    ]);
    exit;
}

// =========================================================================
// 2. KARDEX / AUDITORÍA
// =========================================================================
if ($task == 'get_kardex') {
    $ini = !empty($_GET['ini']) ? $_GET['ini'] : date('Y-m-d');
    $fin = !empty($_GET['fin']) ? $_GET['fin'] : date('Y-m-d');
    
    $sql = "SELECT k.*, p.nombre as producto, COALESCE(e.nombre, 'Sistema') as responsable 
            FROM kardex k
            INNER JOIN productos p ON k.id_producto = p.id_producto
            LEFT JOIN empleados e ON k.id_usuario = e.id_empleado
            WHERE DATE(k.fecha) >= '$ini' AND DATE(k.fecha) <= '$fin'
            ORDER BY k.id_kardex DESC";
            
    $res = $conn->query($sql);
    
    if (!$res) {
        echo json_encode(['error' => "Fallo SQL en Kardex: " . $conn->error]);
        exit;
    }

    $rows = [];
    while($r = $res->fetch_assoc()) { 
        $rows[] = $r;
    }
    
    echo json_encode($rows);
    exit;
}

// =========================================================================
// 3. DASHBOARD KPIs
// =========================================================================
if ($task == 'dashboard_kpis') {
    $conn->query("UPDATE productos p SET p.fecha_caducidad = (SELECT MIN(l.fecha_vencimiento) FROM lotes l WHERE l.id_producto = p.id_producto AND l.stock_actual > 0 AND l.estado = 1) WHERE EXISTS (SELECT 1 FROM lotes l WHERE l.id_producto = p.id_producto)");

    $vta = $conn->query("SELECT COALESCE(SUM(monto_total),0) as total, COUNT(*) as cant FROM ventas WHERE DATE(fecha_venta) = CURDATE() AND estado_venta != 'ANULADA'")->fetch_assoc();
    $gst = $conn->query("SELECT COALESCE(SUM(monto),0) as total, COUNT(*) as cant FROM egresos WHERE DATE(fecha) = CURDATE()")->fetch_assoc();
    $stk = $conn->query("SELECT COUNT(*) as cant FROM productos WHERE stock <= 5 AND stock > 0")->fetch_assoc();
    
    $ticket = ($vta['cant'] > 0) ? ($vta['total'] / $vta['cant']) : 0;

    echo json_encode([
        'ventas_hoy' => ['total' => (float)$vta['total'], 'cantidad' => (int)$vta['cant']],
        'gastos_hoy' => ['total' => (float)$gst['total'], 'cantidad' => (int)$gst['cant']],
        'stock_bajo' => (int)$stk['cant'],
        'ticket_promedio' => (float)$ticket
    ]);
    exit;
}

// =========================================================================
// 4. VENTA ATÓMICA Y DESCUENTO DE LOTES
// =========================================================================
if ($task == 'sync_sale') {
    $data = json_decode($_POST['venta'], true);
    if (!$data || empty($data['items'])) { 
        echo json_encode(['success'=>false, 'error'=>'Carrito vacío.']); 
        exit; 
    }

    $conn->begin_transaction();
    try {
        $qc = $conn->query("SELECT id_caja FROM cajas WHERE id_empleado = $uid AND estado = 'ABIERTA' LIMIT 1");
        $id_caja = ($qc && $qc->num_rows > 0) ? (int)$qc->fetch_assoc()['id_caja'] : 0;

        $id_cli = (int)$data['id_cliente'];
        $total  = (float)$data['total'];
        $pago   = (float)$data['monto_pago'];
        $vuelto = $pago - $total;

        $stmtV = $conn->prepare("INSERT INTO ventas (id_empleado, id_cliente, monto_total, monto_pago, vuelto, tipo_pago, tipo_comprobante, estado_venta, id_caja) VALUES (?, ?, ?, ?, ?, ?, ?, 'COMPLETADA', ?)");
        $stmtV->bind_param("iidddssi", $uid, $id_cli, $total, $pago, $vuelto, $data['metodo_pago'], $data['tipo_doc'], $id_caja);
        $stmtV->execute();
        $id_venta = $conn->insert_id;

        foreach ($data['items'] as $item) {
            $pid = (int)$item['id']; 
            $cant = (float)$item['cant']; 
            $prec = (float)$item['p'];
            $subt = $cant * $prec;

            $conn->query("INSERT INTO detalle_venta (id_venta, id_producto, cantidad, precio_unitario, subtotal) VALUES ($id_venta, $pid, $cant, $prec, $subt)");
            $conn->query("UPDATE productos SET stock = stock - $cant WHERE id_producto = $pid");
            
            $resL = $conn->query("SELECT id_lote, stock_actual FROM lotes WHERE id_producto = $pid AND stock_actual > 0 AND estado = 1 ORDER BY fecha_vencimiento ASC");
            if($resL) {
                $pen = $cant;
                while($l = $resL->fetch_assoc()){
                    if($pen <= 0) break;
                    $desc = min($pen, $l['stock_actual']);
                    $conn->query("UPDATE lotes SET stock_actual = stock_actual - $desc WHERE id_lote = {$l['id_lote']}");
                    $pen -= $desc;
                }
            }
            
            $conn->query("INSERT INTO kardex (id_producto, id_usuario, tipo, cantidad, motivo) VALUES ($pid, $uid, 'SALIDA', $cant, 'Venta #$id_venta')");
        }
        
        $conn->commit(); 
        echo json_encode(['success'=>true, 'id_venta'=>$id_venta]); 
        exit;
        
    } catch (Exception $e) { 
        $conn->rollback(); 
        echo json_encode(['success'=>false, 'error'=>$e->getMessage()]); 
        exit; 
    }
}

// =========================================================================
// 5. UTILITARIOS
// =========================================================================
if ($task == 'get_utility_report') {
    $ini = !empty($_GET['ini']) ? $_GET['ini'] : date('Y-m-01');
    $fin = !empty($_GET['fin']) ? $_GET['fin'] : date('Y-m-d');

    $sqlV = "SELECT SUM(dv.subtotal) as v, SUM(dv.cantidad * p.precio_costo) as c FROM detalle_venta dv INNER JOIN ventas v ON dv.id_venta = v.id_venta INNER JOIN productos p ON dv.id_producto = p.id_producto WHERE DATE(v.fecha_venta) >= '$ini' AND DATE(v.fecha_venta) <= '$fin' AND v.estado_venta != 'ANULADA'";
    $resV = $conn->query($sqlV)->fetch_assoc();
    
    $sqlG = "SELECT SUM(monto) as g FROM egresos WHERE DATE(fecha) >= '$ini' AND DATE(fecha) <= '$fin'";
    $resG = $conn->query($sqlG)->fetch_assoc();

    $v = (float)($resV['v'] ?? 0);
    $c = (float)($resV['c'] ?? 0);
    $g = (float)($resG['g'] ?? 0);

    echo json_encode([
        'ventas' => $v,
        'margen_bruto' => $v - $c,
        'gastos' => $g,
        'utilidad_neta' => ($v - $c) - $g
    ]);
    exit;
}

if ($task == 'get_notifications') {
    $res = $conn->query("SELECT nombre, fecha_caducidad, DATEDIFF(fecha_caducidad, CURDATE()) as dias FROM productos WHERE fecha_caducidad IS NOT NULL AND stock > 0 AND fecha_caducidad <= DATE_ADD(CURDATE(), INTERVAL 60 DAY) ORDER BY fecha_caducidad ASC LIMIT 10");
    $rows = [];
    if($res) { while($r = $res->fetch_assoc()) { $rows[] = $r; } }
    echo json_encode($rows);
    exit;
}

if ($task == 'get_popular_products') {
    $res = $conn->query("SELECT p.id_producto, p.nombre, p.precio_venta, p.stock, COALESCE(SUM(dv.cantidad), 0) as vendidos FROM productos p LEFT JOIN detalle_venta dv ON p.id_producto = dv.id_producto WHERE p.stock > 0 GROUP BY p.id_producto ORDER BY vendidos DESC LIMIT 5");
    $rows = [];
    if($res) { while($r = $res->fetch_assoc()) { $rows[] = $r; } }
    echo json_encode($rows);
    exit;
}

if ($task == 'save_cliente_pos') {
    $stmt = $conn->prepare("INSERT INTO clientes (nombre, documento, telefono, estado) VALUES (?, ?, ?, 1)");
    $stmt->bind_param("sss", $_POST['nombre'], $_POST['documento'], $_POST['telefono']);
    if($stmt->execute()) {
        echo json_encode(['success'=>true, 'id'=>$conn->insert_id, 'nombre'=>$_POST['nombre'], 'doc'=>$_POST['documento']]);
    } else {
        echo json_encode(['success'=>false, 'error'=>"Error al guardar cliente."]);
    }
    exit;
}

// =========================================================================
// 6. MÓDULO DE VENCIMIENTOS - CORRECCIÓN DEFINITIVA DE VARIABLES
// =========================================================================
if ($task == 'full_vencimientos') {
    $meses = isset($_GET['meses']) ? (int)$_GET['meses'] : 6;
    
    $sql = "SELECT 
                id_producto, 
                nombre, 
                stock, 
                fecha_caducidad, 
                DATEDIFF(fecha_caducidad, CURDATE()) as dias 
            FROM productos 
            WHERE stock > 0 
            AND fecha_caducidad IS NOT NULL 
            AND fecha_caducidad <= DATE_ADD(CURDATE(), INTERVAL $meses MONTH) 
            ORDER BY fecha_caducidad ASC";
            
    $res = $conn->query($sql);
    $rows = [];
    
    if ($res) {
        while ($r = $res->fetch_assoc()) {
            // Enviamos ambos nombres para asegurar compatibilidad con el JS
            $r['dias_para_vencer'] = $r['dias']; 
            
            if ($r['dias'] <= 0) {
                $r['estado'] = 'VENCIDO';
            } elseif ($r['dias'] <= 30) {
                $r['estado'] = 'CRÍTICO';
            } else {
                $r['estado'] = 'PRÓXIMO';
            }
            $rows[] = $r;
        }
    }
    
    echo json_encode($rows);
    exit;
}