<?php
// pages/descuentos.php

// Verificar permisos
if (!isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], ['admin', 'editor'])) {
    echo '<div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg">
            <p class="text-red-700">No tienes permisos para acceder a esta sección.</p>
          </div>';
    return;
}

// Función para determinar si es una petición AJAX
function isAjaxRequest() {
    return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

// Crear tabla de descuentos si no existe
try {
    $checkTable = $pdo->query("SHOW TABLES LIKE 'descuentos'");
    if ($checkTable->rowCount() == 0) {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS descuentos (
                id INT AUTO_INCREMENT PRIMARY KEY,
                tipo_descuento ENUM('general', 'categoria', 'referencia', 'referencia_ubicacion', 'tienda_ubicacion', 'referencia_stock') NOT NULL,
                categoria_id INT NULL,
                referencia VARCHAR(100) NULL,
                tienda VARCHAR(50) NULL,
                bodega VARCHAR(50) NULL,
                ubicacion_interna VARCHAR(50) NULL,
                stock_minimo INT NULL,
                porcentaje_descuento DECIMAL(5,2) NOT NULL,
                fecha_inicio DATE NULL,
                fecha_fin DATE NULL,
                descripcion TEXT NULL,
                activo TINYINT(1) DEFAULT 1,
                prioridad INT DEFAULT 0,
                created_by VARCHAR(100),
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_tipo (tipo_descuento),
                INDEX idx_referencia (referencia),
                INDEX idx_categoria (categoria_id),
                INDEX idx_tienda (tienda),
                INDEX idx_ubicacion_interna (ubicacion_interna),
                INDEX idx_stock_minimo (stock_minimo),
                INDEX idx_activo (activo),
                INDEX idx_fechas (fecha_inicio, fecha_fin)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
        ");
    }
} catch (PDOException $e) {
    if (!isAjaxRequest()) {
        echo '<div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg">
                <p class="text-red-700">Error al crear la tabla: ' . htmlspecialchars($e->getMessage()) . '</p>
              </div>';
        return;
    }
}

// Procesar acciones POST (AJAX)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // Si es petición AJAX, preparar respuesta JSON
    if (isAjaxRequest()) {
        // Limpiar cualquier salida previa
        if (ob_get_level()) {
            ob_clean();
        }
        header('Content-Type: application/json; charset=utf-8');
    }
    
    $response = ['success' => false, 'message' => ''];
    
    try {
        $action = $_POST['action'];
        
        switch ($action) {
            case 'add':
            case 'update':
                // Validar datos según el tipo
                $tipo = $_POST['tipo_descuento'] ?? '';
                if (empty($tipo)) {
                    throw new Exception('Tipo de descuento requerido');
                }
                
                $categoria_id = null;
                $referencia = null;
                $tienda = null;
                $bodega = null;
                $ubicacion_interna = null;
                $stock_minimo = null;
                
                // Procesar campos según el tipo
                switch ($tipo) {
                    case 'categoria':
                        $categoria_id = !empty($_POST['categoria_id']) ? $_POST['categoria_id'] : null;
                        if (!$categoria_id) {
                            throw new Exception('Debe seleccionar una categoría');
                        }
                        break;
                        
                    case 'referencia':
                        $referencia = $_POST['referencia'] ?? '';
                        if (empty($referencia)) {
                            throw new Exception('Debe especificar una referencia');
                        }
                        break;
                        
                    case 'referencia_ubicacion':
                        $referencia = $_POST['referencia'] ?? '';
                        if (empty($referencia)) {
                            throw new Exception('Debe especificar una referencia');
                        }
                        $tienda = !empty($_POST['tienda']) ? $_POST['tienda'] : null;
                        $bodega = !empty($_POST['bodega']) ? $_POST['bodega'] : null;
                        break;
                        
                    case 'tienda_ubicacion':
                        $tienda = !empty($_POST['tienda_ubicacion']) ? $_POST['tienda_ubicacion'] : null;
                        // Si es ubicación personalizada, usar ese valor
                        if (isset($_POST['ubicacion_interna']) && $_POST['ubicacion_interna'] === 'CUSTOM' && !empty($_POST['ubicacion_personalizada'])) {
                            $ubicacion_interna = $_POST['ubicacion_personalizada'];
                        } else {
                            $ubicacion_interna = !empty($_POST['ubicacion_interna']) ? $_POST['ubicacion_interna'] : null;
                        }
                        break;
                        
                    case 'referencia_stock':
                        $referencia = $_POST['referencia_stock'] ?? '';
                        if (empty($referencia)) {
                            throw new Exception('Debe especificar una referencia');
                        }
                        $stock_minimo = !empty($_POST['stock_minimo']) ? intval($_POST['stock_minimo']) : null;
                        if (!$stock_minimo || $stock_minimo < 1) {
                            throw new Exception('El stock mínimo debe ser mayor a 0');
                        }
                        $tienda = !empty($_POST['tienda_stock']) ? $_POST['tienda_stock'] : null;
                        // Si es ubicación personalizada para stock
                        if (isset($_POST['ubicacion_stock']) && $_POST['ubicacion_stock'] === 'CUSTOM' && !empty($_POST['ubicacion_personalizada_stock'])) {
                            $bodega = $_POST['ubicacion_personalizada_stock'];
                        } else {
                            $bodega = !empty($_POST['ubicacion_stock']) ? $_POST['ubicacion_stock'] : null;
                        }
                        break;
                }
                
                // Validar porcentaje
                $porcentaje_descuento = floatval($_POST['porcentaje_descuento'] ?? 0);
                if ($porcentaje_descuento <= 0 || $porcentaje_descuento > 100) {
                    throw new Exception('El porcentaje debe estar entre 0 y 100');
                }
                
                if ($action === 'add') {
                    $stmt = $pdo->prepare("
                        INSERT INTO descuentos 
                        (tipo_descuento, categoria_id, referencia, tienda, bodega, 
                         ubicacion_interna, stock_minimo, porcentaje_descuento, fecha_inicio, 
                         fecha_fin, descripcion, prioridad, created_by)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    
                    $result = $stmt->execute([
                        $tipo,
                        $categoria_id,
                        $referencia,
                        $tienda,
                        $bodega,
                        $ubicacion_interna,
                        $stock_minimo,
                        $porcentaje_descuento,
                        !empty($_POST['fecha_inicio']) ? $_POST['fecha_inicio'] : null,
                        !empty($_POST['fecha_fin']) ? $_POST['fecha_fin'] : null,
                        !empty($_POST['descripcion']) ? $_POST['descripcion'] : null,
                        intval($_POST['prioridad'] ?? 0),
                        $_SESSION['user_email'] ?? 'unknown'
                    ]);
                    
                    if (!$result) {
                        throw new Exception('Error al insertar el descuento');
                    }
                    
                    $response['success'] = true;
                    $response['message'] = 'Descuento agregado correctamente';
                    
                } else { // update
                    if (empty($_POST['id'])) {
                        throw new Exception('ID de descuento no especificado');
                    }
                    
                    $stmt = $pdo->prepare("
                        UPDATE descuentos 
                        SET tipo_descuento = ?, categoria_id = ?, referencia = ?, 
                            tienda = ?, bodega = ?, ubicacion_interna = ?, stock_minimo = ?,
                            porcentaje_descuento = ?, fecha_inicio = ?, fecha_fin = ?, 
                            descripcion = ?, prioridad = ?, activo = ?
                        WHERE id = ?
                    ");
                    
                    $result = $stmt->execute([
                        $tipo,
                        $categoria_id,
                        $referencia,
                        $tienda,
                        $bodega,
                        $ubicacion_interna,
                        $stock_minimo,
                        $porcentaje_descuento,
                        !empty($_POST['fecha_inicio']) ? $_POST['fecha_inicio'] : null,
                        !empty($_POST['fecha_fin']) ? $_POST['fecha_fin'] : null,
                        !empty($_POST['descripcion']) ? $_POST['descripcion'] : null,
                        intval($_POST['prioridad'] ?? 0),
                        isset($_POST['activo']) ? 1 : 0,
                        intval($_POST['id'])
                    ]);
                    
                    if (!$result) {
                        throw new Exception('Error al actualizar el descuento');
                    }
                    
                    $response['success'] = true;
                    $response['message'] = 'Descuento actualizado correctamente';
                }
                
                // Intentar consolidar stock (opcional)
                try {
                    $pdo->exec("CALL consolidar_stock_crusardi()");
                    $response['message'] .= '. Stock consolidado.';
                } catch (Exception $e) {
                    // Solo log, no fallar
                    error_log("Error consolidando stock: " . $e->getMessage());
                }
                
                break;
                
            case 'delete':
                if (empty($_POST['id'])) {
                    throw new Exception('ID no especificado');
                }
                
                $stmt = $pdo->prepare("DELETE FROM descuentos WHERE id = ?");
                $result = $stmt->execute([intval($_POST['id'])]);
                
                if (!$result) {
                    throw new Exception('Error al eliminar el descuento');
                }
                
                $response['success'] = true;
                $response['message'] = 'Descuento eliminado correctamente';
                
                // Intentar consolidar stock
                try {
                    $pdo->exec("CALL consolidar_stock_crusardi()");
                } catch (Exception $e) {
                    error_log("Error consolidando stock: " . $e->getMessage());
                }
                break;
                
            case 'toggle':
                if (empty($_POST['id'])) {
                    throw new Exception('ID no especificado');
                }
                
                $stmt = $pdo->prepare("UPDATE descuentos SET activo = NOT activo WHERE id = ?");
                $result = $stmt->execute([intval($_POST['id'])]);
                
                if (!$result) {
                    throw new Exception('Error al cambiar el estado');
                }
                
                $response['success'] = true;
                $response['message'] = 'Estado actualizado correctamente';
                
                // Intentar consolidar stock
                try {
                    $pdo->exec("CALL consolidar_stock_crusardi()");
                } catch (Exception $e) {
                    error_log("Error consolidando stock: " . $e->getMessage());
                }
                break;
                
            default:
                throw new Exception('Acción no válida');
        }
        
    } catch (Exception $e) {
        $response['success'] = false;
        $response['message'] = $e->getMessage();
        error_log("Error en descuentos.php: " . $e->getMessage());
    }
    
    // Enviar respuesta según el tipo de petición
    if (isAjaxRequest()) {
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit;
    } else {
        // Si no es AJAX, redirigir con mensaje
        $_SESSION['message'] = $response['message'];
        $_SESSION['message_type'] = $response['success'] ? 'success' : 'error';
        header('Location: ?page=descuentos');
        exit;
    }
}

// RESTO DEL CÓDIGO PARA MOSTRAR LA PÁGINA (solo se ejecuta si no es POST)

// Obtener categorías para el selector
$categorias = [];
try {
    $stmt = $pdo->query("
        SELECT c1.id, c1.nombre as categoria1, c2.id as cat2_id, c2.nombre as categoria2 
        FROM categorias_nivel1 c1
        LEFT JOIN categorias_nivel2 c2 ON c1.id = c2.categoria1_id
        WHERE c1.activo = 1
        ORDER BY c1.orden, c1.nombre, c2.orden, c2.nombre
    ");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        if (!isset($categorias[$row['id']])) {
            $categorias[$row['id']] = [
                'nombre' => $row['categoria1'],
                'subcategorias' => []
            ];
        }
        if ($row['cat2_id']) {
            $categorias[$row['id']]['subcategorias'][] = [
                'id' => $row['cat2_id'],
                'nombre' => $row['categoria2']
            ];
        }
    }
} catch (PDOException $e) {
    error_log("Error obteniendo categorías: " . $e->getMessage());
}

// Obtener tiendas y bodegas únicas
$tiendas = [];
$bodegas = [];
try {
    $stmt = $pdo->query("SELECT DISTINCT bodega FROM stock_data WHERE bodega IS NOT NULL ORDER BY bodega");
    $tiendas = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    $stmt = $pdo->query("SELECT DISTINCT almacen FROM stock_data WHERE almacen IS NOT NULL ORDER BY almacen");
    $bodegas = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    error_log("Error obteniendo tiendas/bodegas: " . $e->getMessage());
}

// Obtener filtros
$filtro_tipo = $_GET['tipo'] ?? 'todos';
$filtro_busqueda = $_GET['busqueda'] ?? '';
$filtro_activo = $_GET['activo'] ?? 'activos';

// Construir consulta con filtros
$query = "
    SELECT d.*, 
           c1.nombre as categoria_nombre,
           c2.nombre as subcategoria_nombre,
           r.nombre as referencia_nombre
    FROM descuentos d
    LEFT JOIN categorias_nivel1 c1 ON d.categoria_id = c1.id AND d.tipo_descuento = 'categoria'
    LEFT JOIN categorias_nivel2 c2 ON d.categoria_id = c2.id AND d.tipo_descuento = 'categoria'
    LEFT JOIN references_data r ON d.referencia = r.referencia
    WHERE 1=1
";
$params = [];

if ($filtro_tipo !== 'todos') {
    $query .= " AND d.tipo_descuento = ?";
    $params[] = $filtro_tipo;
}

if (!empty($filtro_busqueda)) {
    $query .= " AND (d.referencia LIKE ? OR d.descripcion LIKE ? OR r.nombre LIKE ?)";
    $busqueda_param = "%$filtro_busqueda%";
    $params = array_merge($params, [$busqueda_param, $busqueda_param, $busqueda_param]);
}

if ($filtro_activo === 'activos') {
    $query .= " AND d.activo = 1";
} elseif ($filtro_activo === 'inactivos') {
    $query .= " AND d.activo = 0";
}

$query .= " ORDER BY d.tipo_descuento, d.prioridad DESC, d.created_at DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$descuentos = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Obtener estadísticas
$stats = [
    'total' => count($descuentos),
    'activos' => 0,
    'general' => 0,
    'categoria' => 0,
    'referencia' => 0,
    'ubicacion' => 0,
    'tienda_ubicacion' => 0,
    'referencia_stock' => 0
];

foreach ($descuentos as $desc) {
    if ($desc['activo']) $stats['activos']++;
    switch ($desc['tipo_descuento']) {
        case 'general': $stats['general']++; break;
        case 'categoria': $stats['categoria']++; break;
        case 'referencia': $stats['referencia']++; break;
        case 'referencia_ubicacion': $stats['ubicacion']++; break;
        case 'tienda_ubicacion': $stats['tienda_ubicacion']++; break;
        case 'referencia_stock': $stats['referencia_stock']++; break;
    }
}

// Mostrar mensajes de sesión si existen
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    $type = $_SESSION['message_type'] ?? 'info';
    unset($_SESSION['message'], $_SESSION['message_type']);
    
    $alertClass = $type === 'success' ? 'bg-green-50 border-green-500 text-green-700' : 'bg-red-50 border-red-500 text-red-700';
    echo "<div class='$alertClass border-l-4 p-4 mb-4'>$message</div>";
}
?>

<div class="space-y-6">
    <!-- Header -->
    <div class="bg-white rounded-lg shadow-sm p-6">
        <div class="flex justify-between items-center">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">Gestión de Descuentos</h1>
                <p class="mt-1 text-sm text-gray-600">
                    Configura descuentos generales, por categoría, referencia o ubicación específica
                </p>
            </div>
            <button onclick="openModal('add')" 
                    class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
                <i class="fas fa-plus mr-2"></i>Nuevo Descuento
            </button>
        </div>
    </div>

    <!-- Estadísticas -->
    <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-4">
        <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex items-center">
                <div class="p-2 bg-blue-100 rounded-lg">
                    <i class="fas fa-percent text-blue-600"></i>
                </div>
                <div class="ml-3">
                    <p class="text-xs text-gray-600">Total</p>
                    <p class="text-xl font-bold text-gray-900"><?= $stats['total'] ?></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex items-center">
                <div class="p-2 bg-green-100 rounded-lg">
                    <i class="fas fa-check-circle text-green-600"></i>
                </div>
                <div class="ml-3">
                    <p class="text-xs text-gray-600">Activos</p>
                    <p class="text-xl font-bold text-gray-900"><?= $stats['activos'] ?></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex items-center">
                <div class="p-2 bg-purple-100 rounded-lg">
                    <i class="fas fa-globe text-purple-600"></i>
                </div>
                <div class="ml-3">
                    <p class="text-xs text-gray-600">Generales</p>
                    <p class="text-xl font-bold text-gray-900"><?= $stats['general'] ?></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex items-center">
                <div class="p-2 bg-orange-100 rounded-lg">
                    <i class="fas fa-folder text-orange-600"></i>
                </div>
                <div class="ml-3">
                    <p class="text-xs text-gray-600">Categoría</p>
                    <p class="text-xl font-bold text-gray-900"><?= $stats['categoria'] ?></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex items-center">
                <div class="p-2 bg-indigo-100 rounded-lg">
                    <i class="fas fa-tag text-indigo-600"></i>
                </div>
                <div class="ml-3">
                    <p class="text-xs text-gray-600">Referencia</p>
                    <p class="text-xl font-bold text-gray-900"><?= $stats['referencia'] ?></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex items-center">
                <div class="p-2 bg-red-100 rounded-lg">
                    <i class="fas fa-map-marker-alt text-red-600"></i>
                </div>
                <div class="ml-3">
                    <p class="text-xs text-gray-600">Ubicación</p>
                    <p class="text-xl font-bold text-gray-900"><?= $stats['ubicacion'] ?></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex items-center">
                <div class="p-2 bg-yellow-100 rounded-lg">
                    <i class="fas fa-store text-yellow-600"></i>
                </div>
                <div class="ml-3">
                    <p class="text-xs text-gray-600">Tienda + Ubicación</p>
                    <p class="text-xl font-bold text-gray-900"><?= $stats['tienda_ubicacion'] ?></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex items-center">
                <div class="p-2 bg-pink-100 rounded-lg">
                    <i class="fas fa-boxes text-pink-600"></i>
                </div>
                <div class="ml-3">
                    <p class="text-xs text-gray-600">Ref + Stock</p>
                    <p class="text-xl font-bold text-gray-900"><?= $stats['referencia_stock'] ?></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtros -->
    <div class="bg-white rounded-lg shadow-sm p-6">
        <form method="GET" class="flex flex-wrap gap-4">
            <input type="hidden" name="page" value="descuentos">
            
            <div class="flex-1 min-w-[250px]">
                <label class="block text-sm font-medium text-gray-700 mb-2">Buscar</label>
                <input type="text" 
                       name="busqueda" 
                       value="<?= htmlspecialchars($filtro_busqueda) ?>"
                       placeholder="Referencia, descripción..."
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
            </div>
            
            <div class="w-48">
                <label class="block text-sm font-medium text-gray-700 mb-2">Tipo</label>
                <select name="tipo" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                    <option value="todos">Todos</option>
                    <option value="general" <?= $filtro_tipo === 'general' ? 'selected' : '' ?>>General</option>
                    <option value="categoria" <?= $filtro_tipo === 'categoria' ? 'selected' : '' ?>>Por Categoría</option>
                    <option value="referencia" <?= $filtro_tipo === 'referencia' ? 'selected' : '' ?>>Por Referencia</option>
                    <option value="referencia_ubicacion" <?= $filtro_tipo === 'referencia_ubicacion' ? 'selected' : '' ?>>Por Ubicación</option>
                    <option value="tienda_ubicacion" <?= $filtro_tipo === 'tienda_ubicacion' ? 'selected' : '' ?>>Por Tienda + Ubicación</option>
                    <option value="referencia_stock" <?= $filtro_tipo === 'referencia_stock' ? 'selected' : '' ?>>Por Referencia + Stock</option>
                </select>
            </div>
            
            <div class="w-40">
                <label class="block text-sm font-medium text-gray-700 mb-2">Estado</label>
                <select name="activo" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                    <option value="todos">Todos</option>
                    <option value="activos" <?= $filtro_activo === 'activos' ? 'selected' : '' ?>>Activos</option>
                    <option value="inactivos" <?= $filtro_activo === 'inactivos' ? 'selected' : '' ?>>Inactivos</option>
                </select>
            </div>
            
            <div class="flex items-end gap-2">
                <button type="submit" 
                        class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
                    <i class="fas fa-search mr-2"></i>Filtrar
                </button>
                <a href="?page=descuentos" 
                   class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                    <i class="fas fa-redo mr-2"></i>Limpiar
                </a>
            </div>
        </form>
    </div>

    <!-- Tabla de descuentos -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Tipo
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Aplicado a
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Descuento
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Vigencia
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Prioridad
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Estado
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Acciones
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($descuentos)): ?>
                        <tr>
                            <td colspan="7" class="px-6 py-4 text-center text-gray-500">
                                No se encontraron descuentos
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($descuentos as $desc): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php
                                    $tipo_badge = [
                                        'general' => ['bg-purple-100 text-purple-800', 'fa-globe', 'General'],
                                        'categoria' => ['bg-orange-100 text-orange-800', 'fa-folder', 'Categoría'],
                                        'referencia' => ['bg-indigo-100 text-indigo-800', 'fa-tag', 'Referencia'],
                                        'referencia_ubicacion' => ['bg-red-100 text-red-800', 'fa-map-marker-alt', 'Ubicación'],
                                        'tienda_ubicacion' => ['bg-yellow-100 text-yellow-800', 'fa-store', 'Tienda + Ubicación'],
                                        'referencia_stock' => ['bg-pink-100 text-pink-800', 'fa-boxes', 'Referencia + Stock']
                                    ];
                                    $badge = $tipo_badge[$desc['tipo_descuento']];
                                    ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?= $badge[0] ?>">
                                        <i class="fas <?= $badge[1] ?> mr-1"></i><?= $badge[2] ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm">
                                        <?php switch ($desc['tipo_descuento']):
                                            case 'general': ?>
                                                <div class="text-gray-900 font-medium">Todos los productos</div>
                                            <?php break;
                                            case 'categoria': ?>
                                                <div class="text-gray-900 font-medium">
                                                    <?= htmlspecialchars($desc['categoria_nombre'] ?? $desc['subcategoria_nombre'] ?? 'Categoría #' . $desc['categoria_id']) ?>
                                                </div>
                                            <?php break;
                                            case 'referencia': ?>
                                                <div class="text-gray-900 font-medium"><?= htmlspecialchars($desc['referencia']) ?></div>
                                                <?php if ($desc['referencia_nombre']): ?>
                                                    <div class="text-gray-500 text-xs"><?= htmlspecialchars($desc['referencia_nombre']) ?></div>
                                                <?php endif; ?>
                                            <?php break;
                                            case 'referencia_ubicacion': ?>
                                                <div class="text-gray-900 font-medium"><?= htmlspecialchars($desc['referencia']) ?></div>
                                                <div class="text-gray-500 text-xs">
                                                    <?= $desc['tienda'] ? 'Tienda: ' . htmlspecialchars($desc['tienda']) : 'Todas las tiendas' ?>
                                                    <?= $desc['bodega'] ? ' | Bodega: ' . htmlspecialchars($desc['bodega']) : '' ?>
                                                </div>
                                            <?php break;
                                            case 'tienda_ubicacion': ?>
                                                <div class="text-gray-900 font-medium">Tienda + Ubicación</div>
                                                <div class="text-gray-500 text-xs">
                                                    <?= $desc['tienda'] ? 'Tienda: ' . htmlspecialchars($desc['tienda']) : 'Todas las tiendas' ?>
                                                    <?= $desc['ubicacion_interna'] ? ' | Ubicación: ' . htmlspecialchars($desc['ubicacion_interna']) : '' ?>
                                                </div>
                                            <?php break;
                                            case 'referencia_stock': ?>
                                                <div class="text-gray-900 font-medium"><?= htmlspecialchars($desc['referencia']) ?></div>
                                                <div class="text-gray-500 text-xs">
                                                    Stock mínimo: <?= $desc['stock_minimo'] ?: 'N/A' ?>
                                                    <?= $desc['tienda'] ? ' | Tienda: ' . htmlspecialchars($desc['tienda']) : '' ?>
                                                    <?= $desc['bodega'] ? ' | Ubicación: ' . htmlspecialchars($desc['bodega']) : '' ?>
                                                </div>
                                            <?php break;
                                        endswitch; ?>
                                        <?php if ($desc['descripcion']): ?>
                                            <div class="text-gray-500 text-xs mt-1"><?= htmlspecialchars($desc['descripcion']) ?></div>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="text-lg font-semibold text-green-600">
                                        <?= number_format($desc['porcentaje_descuento'], 0) ?>%
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm">
                                    <?php
                                    $hoy = date('Y-m-d');
                                    $vigente = true;
                                    
                                    if ($desc['fecha_inicio'] && $desc['fecha_inicio'] > $hoy) {
                                        $vigente = false;
                                        echo '<span class="text-yellow-600"><i class="fas fa-clock mr-1"></i>Desde ' . date('d/m/Y', strtotime($desc['fecha_inicio'])) . '</span>';
                                    } elseif ($desc['fecha_fin'] && $desc['fecha_fin'] < $hoy) {
                                        $vigente = false;
                                        echo '<span class="text-red-600"><i class="fas fa-times-circle mr-1"></i>Expiró ' . date('d/m/Y', strtotime($desc['fecha_fin'])) . '</span>';
                                    } else {
                                        if ($desc['fecha_inicio'] || $desc['fecha_fin']) {
                                            echo '<div class="text-green-600"><i class="fas fa-check-circle mr-1"></i>Vigente</div>';
                                            echo '<div class="text-xs text-gray-500">';
                                            if ($desc['fecha_inicio']) echo 'Desde: ' . date('d/m/Y', strtotime($desc['fecha_inicio'])) . '<br>';
                                            if ($desc['fecha_fin']) echo 'Hasta: ' . date('d/m/Y', strtotime($desc['fecha_fin']));
                                            echo '</div>';
                                        } else {
                                            echo '<span class="text-gray-500">Sin restricción</span>';
                                        }
                                    }
                                    ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-center">
                                    <span class="text-sm font-medium text-gray-700"><?= $desc['prioridad'] ?></span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <button onclick="toggleStatus(<?= $desc['id'] ?>)" 
                                            class="relative inline-flex items-center h-6 rounded-full w-11 transition-colors
                                            <?= $desc['activo'] ? 'bg-green-500' : 'bg-gray-200' ?>">
                                        <span class="inline-block w-4 h-4 transform transition-transform bg-white rounded-full shadow
                                            <?= $desc['activo'] ? 'translate-x-6' : 'translate-x-1' ?>">
                                        </span>
                                    </button>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                    <button onclick='openModal("edit", <?= json_encode($desc, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)' 
                                            class="text-indigo-600 hover:text-indigo-900 mr-3">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button onclick="deleteDiscount(<?= $desc['id'] ?>)" 
                                            class="text-red-600 hover:text-red-900">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Información sobre prioridades -->
    <div class="bg-blue-50 border-l-4 border-blue-400 p-4">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-info-circle text-blue-400"></i>
            </div>
            <div class="ml-3">
                <h3 class="text-sm font-medium text-blue-800">Sistema de Prioridades</h3>
                <div class="mt-2 text-sm text-blue-700">
                    <p>Los descuentos se aplican según el siguiente orden de prioridad:</p>
                    <ol class="list-decimal list-inside mt-1">
                        <li><strong>Referencia + Ubicación específica</strong> (mayor prioridad)</li>
                        <li><strong>Referencia específica</strong></li>
                        <li><strong>Categoría</strong></li>
                        <li><strong>Descuento general</strong> (menor prioridad)</li>
                    </ol>
                    <p class="mt-2">Cuando hay múltiples descuentos aplicables, se usa el de mayor prioridad. Entre descuentos del mismo tipo, se usa el valor de prioridad más alto.</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal para agregar/editar -->
<div id="discountModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <form id="discountForm" class="p-6">
                <input type="hidden" name="action" id="modalAction">
                <input type="hidden" name="id" id="discountId">
                
                <h2 class="text-xl font-bold text-gray-900 mb-4" id="modalTitle">Nuevo Descuento</h2>
                
                <div class="space-y-4">
                    <!-- Tipo de descuento -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Tipo de Descuento <span class="text-red-500">*</span>
                        </label>
                        <select name="tipo_descuento" 
                                id="tipo_descuento"
                                onchange="toggleFieldsByType()"
                                required
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                            <option value="">Seleccionar tipo...</option>
                            <option value="general">Descuento General</option>
                            <option value="categoria">Por Categoría</option>
                            <option value="referencia">Por Referencia</option>
                            <option value="referencia_ubicacion">Por Referencia y Ubicación</option>
                            <option value="tienda_ubicacion">Por Tienda y Ubicación Interna</option>
                            <option value="referencia_stock">Por Referencia y Stock Mínimo</option>
                        </select>
                    </div>
                    
                    <!-- Campo de categoría -->
                    <div id="categoria_field" style="display: none;">
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Categoría <span class="text-red-500">*</span>
                        </label>
                        <select name="categoria_id" 
                                id="categoria_id"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                            <option value="">Seleccionar categoría...</option>
                            <?php foreach ($categorias as $cat1_id => $cat1): ?>
                                <optgroup label="<?= htmlspecialchars($cat1['nombre']) ?>">
                                    <option value="<?= $cat1_id ?>"><?= htmlspecialchars($cat1['nombre']) ?> (Toda la categoría)</option>
                                    <?php foreach ($cat1['subcategorias'] as $cat2): ?>
                                        <option value="<?= $cat2['id'] ?>">— <?= htmlspecialchars($cat2['nombre']) ?></option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Campo de referencia -->
                    <div id="referencia_field" style="display: none;">
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Referencia <span class="text-red-500">*</span>
                        </label>
                        <input type="text" 
                               name="referencia" 
                               id="referencia"
                               placeholder="Código de referencia"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                    </div>
                    
                    <!-- Campos de ubicación -->
                    <div id="ubicacion_fields" style="display: none;">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Tienda/Bodega (Opcional)
                                </label>
                                <select name="tienda" 
                                        id="tienda"
                                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                                    <option value="">Todas las tiendas</option>
                                    <?php foreach ($tiendas as $tienda): ?>
                                        <option value="<?= htmlspecialchars($tienda) ?>"><?= htmlspecialchars($tienda) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Almacén (Opcional)
                                </label>
                                <select name="bodega" 
                                        id="bodega"
                                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                                    <option value="">Todos los almacenes</option>
                                    <?php foreach ($bodegas as $bodega): ?>
                                        <option value="<?= htmlspecialchars($bodega) ?>"><?= htmlspecialchars($bodega) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Campo de ubicación interna -->
                    <div id="ubicacion_interna_field" style="display: none;">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Tienda <span class="text-red-500">*</span>
                                </label>
                                <select name="tienda_ubicacion" 
                                        id="tienda_ubicacion"
                                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                                    <option value="">Seleccionar tienda...</option>
                                    <?php foreach ($tiendas as $tienda): ?>
                                        <option value="<?= htmlspecialchars($tienda) ?>"><?= htmlspecialchars($tienda) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Ubicación Interna <span class="text-red-500">*</span>
                                </label>
                                <select name="ubicacion_interna" 
                                        id="ubicacion_interna"
                                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                                    <option value="">Seleccionar ubicación...</option>
                                    <optgroup label="Ubicaciones del Sistema">
                                        <?php foreach ($bodegas as $bodega): ?>
                                            <option value="<?= htmlspecialchars($bodega) ?>"><?= htmlspecialchars($bodega) ?></option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <optgroup label="Ubicación Personalizada">
                                        <option value="CUSTOM">Personalizada...</option>
                                    </optgroup>
                                </select>
                                <p class="text-xs text-gray-500 mt-1">Selecciona una ubicación del sistema o ingresa una personalizada</p>
                                
                                <!-- Campo para ubicación personalizada (oculto por defecto) -->
                                <input type="text" 
                                       name="ubicacion_personalizada" 
                                       id="ubicacion_personalizada"
                                       placeholder="Ingresa ubicación personalizada"
                                       style="display: none;"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500 mt-2">
                            </div>
                        </div>
                    </div>
                    
                    <!-- Campo de stock mínimo -->
                    <div id="stock_minimo_field" style="display: none;">
                        <div class="space-y-4">
                            <!-- Referencia -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Referencia <span class="text-red-500">*</span>
                                </label>
                                <input type="text" 
                                       name="referencia_stock" 
                                       id="referencia_stock"
                                       placeholder="Código de referencia"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                            </div>
                            
                            <!-- Tienda y Ubicación (Opcional) -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Tienda y Ubicación (Opcional)
                                </label>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <select name="tienda_stock" 
                                                id="tienda_stock"
                                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                                            <option value="">Todas las tiendas</option>
                                            <?php foreach ($tiendas as $tienda): ?>
                                                <option value="<?= htmlspecialchars($tienda) ?>"><?= htmlspecialchars($tienda) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div>
                                        <select name="ubicacion_stock" 
                                                id="ubicacion_stock"
                                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                                            <option value="">Todas las ubicaciones</option>
                                            <optgroup label="Ubicaciones del Sistema">
                                                <?php foreach ($bodegas as $bodega): ?>
                                                    <option value="<?= htmlspecialchars($bodega) ?>"><?= htmlspecialchars($bodega) ?></option>
                                                <?php endforeach; ?>
                                            </optgroup>
                                            <optgroup label="Ubicación Personalizada">
                                                <option value="CUSTOM">Personalizada...</option>
                                            </optgroup>
                                        </select>
                                        
                                        <!-- Campo para ubicación personalizada de stock (oculto por defecto) -->
                                        <input type="text" 
                                               name="ubicacion_personalizada_stock" 
                                               id="ubicacion_personalizada_stock"
                                               placeholder="Ingresa ubicación personalizada"
                                               style="display: none;"
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500 mt-2">
                                    </div>
                                </div>
                                <p class="text-xs text-gray-500 mt-1">Si no se especifica, el descuento se aplica a todas las tiendas y ubicaciones</p>
                            </div>
                            
                            <!-- Stock mínimo -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Stock Mínimo <span class="text-red-500">*</span>
                                </label>
                                <input type="number" 
                                       name="stock_minimo" 
                                       id="stock_minimo"
                                       min="1"
                                       placeholder="Ej: 5"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                                <p class="text-xs text-gray-500 mt-1">El descuento se aplica solo si hay más unidades que este número</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Porcentaje de descuento -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Porcentaje de Descuento <span class="text-red-500">*</span>
                        </label>
                        <div class="relative">
                            <input type="number" 
                                   name="porcentaje_descuento" 
                                   id="porcentaje_descuento"
                                   min="0"
                                   max="100"
                                   step="0.01"
                                   required
                                   class="w-full px-3 py-2 pr-8 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                            <span class="absolute right-3 top-2 text-gray-500">%</span>
                        </div>
                    </div>
                    
                    <!-- Fechas de vigencia -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                Fecha de Inicio (Opcional)
                            </label>
                            <input type="date" 
                                   name="fecha_inicio" 
                                   id="fecha_inicio"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                Fecha de Fin (Opcional)
                            </label>
                            <input type="date" 
                                   name="fecha_fin" 
                                   id="fecha_fin"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                    </div>
                    
                    <!-- Prioridad y descripción -->
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                Prioridad
                            </label>
                            <input type="number" 
                                   name="prioridad" 
                                   id="prioridad"
                                   min="0"
                                   value="0"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                        
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                Descripción (Opcional)
                            </label>
                            <input type="text" 
                                   name="descripcion" 
                                   id="descripcion"
                                   placeholder="Descripción del descuento"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                    </div>
                    
                    <!-- Estado activo -->
                    <div class="flex items-center" id="activoContainer" style="display: none;">
                        <input type="checkbox" 
                               name="activo" 
                               id="activo"
                               checked
                               class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded">
                        <label for="activo" class="ml-2 block text-sm text-gray-700">
                            Descuento activo
                        </label>
                    </div>
                </div>
                
                <div class="mt-6 flex justify-end space-x-3">
                    <button type="button" 
                            onclick="closeModal()"
                            class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                        Cancelar
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
                        <i class="fas fa-save mr-2"></i>Guardar
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Hacer disponibles las listas de bodegas globalmente (para edición)
window.bodegas = <?= json_encode($bodegas ?? []) ?>;

// Función para mostrar/ocultar campos según el tipo
function toggleFieldsByType() {
    const tipo = document.getElementById('tipo_descuento').value;
    
    // Ocultar todos los campos específicos
    document.getElementById('categoria_field').style.display = 'none';
    document.getElementById('referencia_field').style.display = 'none';
    document.getElementById('ubicacion_fields').style.display = 'none';
    document.getElementById('ubicacion_interna_field').style.display = 'none';
    document.getElementById('stock_minimo_field').style.display = 'none';
    
    // Limpiar required
    document.getElementById('categoria_id').removeAttribute('required');
    document.getElementById('referencia').removeAttribute('required');
    document.getElementById('tienda_ubicacion').removeAttribute('required');
    document.getElementById('ubicacion_interna').removeAttribute('required');
    document.getElementById('referencia_stock').removeAttribute('required');
    document.getElementById('stock_minimo').removeAttribute('required');
    
    // Mostrar campos según el tipo
    switch (tipo) {
        case 'categoria':
            document.getElementById('categoria_field').style.display = 'block';
            document.getElementById('categoria_id').setAttribute('required', 'required');
            break;
        case 'referencia':
            document.getElementById('referencia_field').style.display = 'block';
            document.getElementById('referencia').setAttribute('required', 'required');
            break;
        case 'referencia_ubicacion':
            document.getElementById('referencia_field').style.display = 'block';
            document.getElementById('ubicacion_fields').style.display = 'block';
            document.getElementById('referencia').setAttribute('required', 'required');
            break;
        case 'tienda_ubicacion':
            document.getElementById('ubicacion_interna_field').style.display = 'block';
            document.getElementById('tienda_ubicacion').setAttribute('required', 'required');
            document.getElementById('ubicacion_interna').setAttribute('required', 'required');
            break;
        case 'referencia_stock':
            document.getElementById('stock_minimo_field').style.display = 'block';
            document.getElementById('referencia_stock').setAttribute('required', 'required');
            document.getElementById('stock_minimo').setAttribute('required', 'required');
            break;
    }
}

// Función para manejar ubicación personalizada
function handleUbicacionPersonalizada() {
    const ubicacionSelect = document.getElementById('ubicacion_interna');
    const ubicacionPersonalizada = document.getElementById('ubicacion_personalizada');
    
    if (ubicacionSelect && ubicacionSelect.value === 'CUSTOM') {
        ubicacionPersonalizada.style.display = 'block';
        ubicacionPersonalizada.setAttribute('required', 'required');
        ubicacionPersonalizada.focus();
    } else if (ubicacionPersonalizada) {
        ubicacionPersonalizada.style.display = 'none';
        ubicacionPersonalizada.removeAttribute('required');
        ubicacionPersonalizada.value = '';
    }
}

// Función para manejar ubicación personalizada de stock
function handleUbicacionPersonalizadaStock() {
    const ubicacionSelect = document.getElementById('ubicacion_stock');
    const ubicacionPersonalizada = document.getElementById('ubicacion_personalizada_stock');
    
    if (ubicacionSelect && ubicacionSelect.value === 'CUSTOM') {
        ubicacionPersonalizada.style.display = 'block';
        ubicacionPersonalizada.focus();
    } else if (ubicacionPersonalizada) {
        ubicacionPersonalizada.style.display = 'none';
        ubicacionPersonalizada.value = '';
    }
}

// Funciones del modal
function openModal(action, data = null) {
    const modal = document.getElementById('discountModal');
    const form = document.getElementById('discountForm');
    const title = document.getElementById('modalTitle');
    const actionInput = document.getElementById('modalAction');
    const activoContainer = document.getElementById('activoContainer');
    
    // Resetear formulario
    form.reset();
    
    // Configurar según la acción
    if (action === 'add') {
        title.textContent = 'Nuevo Descuento';
        actionInput.value = 'add';
        activoContainer.style.display = 'none';
        document.getElementById('activo').checked = true;
    } else if (action === 'edit' && data) {
        title.textContent = 'Editar Descuento';
        actionInput.value = 'update';
        activoContainer.style.display = 'flex';
        
        // Llenar campos básicos
        document.getElementById('discountId').value = data.id;
        document.getElementById('tipo_descuento').value = data.tipo_descuento;
        toggleFieldsByType();
        
        // Llenar campos específicos según el tipo
        if (data.categoria_id) {
            document.getElementById('categoria_id').value = data.categoria_id;
        }
        
        if (data.referencia) {
            const refField = document.getElementById('referencia');
            if (refField) refField.value = data.referencia;
            
            if (data.tipo_descuento === 'referencia_stock') {
                const refStockField = document.getElementById('referencia_stock');
                if (refStockField) refStockField.value = data.referencia;
            }
        }
        
        if (data.tienda) {
            if (data.tipo_descuento === 'tienda_ubicacion') {
                const tiendaUbField = document.getElementById('tienda_ubicacion');
                if (tiendaUbField) tiendaUbField.value = data.tienda;
            } else if (data.tipo_descuento === 'referencia_stock') {
                const tiendaStockField = document.getElementById('tienda_stock');
                if (tiendaStockField) tiendaStockField.value = data.tienda;
            } else {
                const tiendaField = document.getElementById('tienda');
                if (tiendaField) tiendaField.value = data.tienda;
            }
        }
        
        if (data.bodega) {
            if (data.tipo_descuento === 'referencia_stock') {
                const ubicacionStock = document.getElementById('ubicacion_stock');
                const ubicacionPersonalizadaStock = document.getElementById('ubicacion_personalizada_stock');
                
                if (window.bodegas.includes(data.bodega)) {
                    if (ubicacionStock) ubicacionStock.value = data.bodega;
                } else {
                    if (ubicacionStock) ubicacionStock.value = 'CUSTOM';
                    if (ubicacionPersonalizadaStock) {
                        ubicacionPersonalizadaStock.style.display = 'block';
                        ubicacionPersonalizadaStock.value = data.bodega;
                    }
                }
            } else {
                const bodegaField = document.getElementById('bodega');
                if (bodegaField) bodegaField.value = data.bodega;
            }
        }
        
        if (data.ubicacion_interna) {
            const ubicacionInterna = document.getElementById('ubicacion_interna');
            const ubicacionPersonalizada = document.getElementById('ubicacion_personalizada');
            
            if (window.bodegas.includes(data.ubicacion_interna)) {
                if (ubicacionInterna) ubicacionInterna.value = data.ubicacion_interna;
            } else {
                if (ubicacionInterna) ubicacionInterna.value = 'CUSTOM';
                if (ubicacionPersonalizada) {
                    ubicacionPersonalizada.style.display = 'block';
                    ubicacionPersonalizada.value = data.ubicacion_interna;
                    ubicacionPersonalizada.setAttribute('required', 'required');
                }
            }
        }
        
        if (data.stock_minimo) {
            const stockField = document.getElementById('stock_minimo');
            if (stockField) stockField.value = data.stock_minimo;
        }
        
        // Campos generales
        document.getElementById('porcentaje_descuento').value = data.porcentaje_descuento || '';
        document.getElementById('fecha_inicio').value = data.fecha_inicio || '';
        document.getElementById('fecha_fin').value = data.fecha_fin || '';
        document.getElementById('prioridad').value = data.prioridad || 0;
        document.getElementById('descripcion').value = data.descripcion || '';
        document.getElementById('activo').checked = data.activo == 1;
    }
    
    modal.classList.remove('hidden');
}

function closeModal() {
    const modal = document.getElementById('discountModal');
    if (modal) modal.classList.add('hidden');
}

// Función mejorada para enviar formularios AJAX
function sendAjaxRequest(formData, successMessage) {
    return fetch('?page=descuentos', {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        // Verificar el estado HTTP
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        // Obtener el texto de respuesta
        return response.text();
    })
    .then(text => {
        // Intentar parsear como JSON
        try {
            const data = JSON.parse(text);
            
            if (data.success) {
                // Si hay mensaje personalizado, usarlo
                if (successMessage) {
                    console.log(successMessage);
                }
                // Recargar la página para ver los cambios
                setTimeout(() => {
                    location.reload();
                }, 100);
            } else {
                // Mostrar error del servidor
                throw new Error(data.message || 'Error al procesar la solicitud');
            }
            
            return data;
        } catch (e) {
            // Si no es JSON válido, registrar el error
            console.error('Respuesta no válida del servidor:', text);
            // Pero si el texto está vacío, asumir éxito
            if (text.trim() === '' || text.includes('<!DOCTYPE')) {
                // Probablemente la operación fue exitosa pero no devolvió JSON
                console.log('Operación completada (sin respuesta JSON)');
                setTimeout(() => {
                    location.reload();
                }, 100);
            } else {
                throw new Error('La respuesta del servidor no es válida');
            }
        }
    })
    .catch(error => {
        console.error('Error en la petición:', error);
        alert(error.message || 'Error al procesar la solicitud');
        throw error;
    });
}

// Inicialización cuando el DOM esté listo
document.addEventListener('DOMContentLoaded', function() {
    console.log('Inicializando módulo de descuentos...');
    
    // Event listeners para ubicaciones personalizadas
    const ubicacionInterna = document.getElementById('ubicacion_interna');
    if (ubicacionInterna) {
        ubicacionInterna.addEventListener('change', handleUbicacionPersonalizada);
    }
    
    const ubicacionStock = document.getElementById('ubicacion_stock');
    if (ubicacionStock) {
        ubicacionStock.addEventListener('change', handleUbicacionPersonalizadaStock);
    }
    
    // Manejar envío del formulario
    const discountForm = document.getElementById('discountForm');
    if (discountForm) {
        discountForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            
            // Mostrar estado de carga
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Guardando...';
            submitBtn.disabled = true;
            
            sendAjaxRequest(formData, 'Descuento guardado correctamente')
                .finally(() => {
                    // Restaurar botón
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                });
        });
    }
    
    // Cerrar modal al hacer clic fuera
    const modal = document.getElementById('discountModal');
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });
    }
    
    // Validación de fechas
    const fechaInicio = document.getElementById('fecha_inicio');
    if (fechaInicio) {
        fechaInicio.addEventListener('change', function() {
            const inicio = this.value;
            const fin = document.getElementById('fecha_fin').value;
            
            if (inicio && fin && inicio > fin) {
                alert('La fecha de inicio no puede ser posterior a la fecha de fin');
                this.value = '';
            }
        });
    }
    
    const fechaFin = document.getElementById('fecha_fin');
    if (fechaFin) {
        fechaFin.addEventListener('change', function() {
            const fin = this.value;
            const inicio = document.getElementById('fecha_inicio').value;
            
            if (inicio && fin && inicio > fin) {
                alert('La fecha de fin no puede ser anterior a la fecha de inicio');
                this.value = '';
            }
        });
    }
});

// Función para cambiar estado
function toggleStatus(id) {
    if (!confirm('¿Desea cambiar el estado de este descuento?')) return;
    
    const formData = new FormData();
    formData.append('action', 'toggle');
    formData.append('id', id);
    
    sendAjaxRequest(formData, 'Estado actualizado correctamente');
}

// Función para eliminar
function deleteDiscount(id) {
    if (!confirm('¿Está seguro de eliminar este descuento? Esta acción no se puede deshacer.')) return;
    
    const formData = new FormData();
    formData.append('action', 'delete');
    formData.append('id', id);
    
    sendAjaxRequest(formData, 'Descuento eliminado correctamente');
}
</script>