<?php
/**
 * get_pinfeeds_turbo.php - Versão TURBO OTIMIZADA
 * 
 * Funcionalidades de busca:
 * - Busca normal: palavra ou frase
 * - Busca exata: "frase entre aspas"
 * - Busca por domínio: source:exemplo.com
 * - Busca por autor: author:nome
 * - Busca por tag: tag:palavra
 * - Busca por categoria: category:1
 * - Busca combinada: palavra source:site.com author:joao
 * - Busca com exclusão: palavra -excluir
 * - Busca por data: date:2024-01-01
 */

// Otimizações de performance
ini_set('memory_limit', '128M');
opcache_enable();

session_start();

// Configurações
$config = [
    'host' => 'localhost',
    'db' => 'digupdog_FEED',
    'user' => 'digupdog_FEEDadmin',
    'pass' => 'Raimundinho1',
    'charset' => 'utf8mb4',
    'per_page' => 21,
    'max_results' => 10000,
    'cache_enabled' => true,
    'cache_ttl' => 300 // 5 minutos
];

// Cache simples em arquivo
class SimpleCache {
    private $cacheDir = '/tmp/feed_cache/';
    
    public function __construct() {
        if (!is_dir($this->cacheDir)) {
            @mkdir($this->cacheDir, 0777, true);
        }
    }
    
    public function get($key) {
        $file = $this->cacheDir . md5($key) . '.cache';
        if (file_exists($file) && (time() - filemtime($file) < 300)) {
            return unserialize(file_get_contents($file));
        }
        return false;
    }
    
    public function set($key, $data) {
        $file = $this->cacheDir . md5($key) . '.cache';
        file_put_contents($file, serialize($data));
    }
}

// Parser de busca avançada
class SearchParser {
    private $filters = [];
    private $keywords = [];
    private $exclude = [];
    
    public function parse($searchString) {
        // Regex para capturar diferentes tipos de busca
        $patterns = [
            'quoted' => '/"([^"]+)"/',
            'source' => '/source:(\S+)/',
            'author' => '/author:(\S+)/',
            'tag' => '/tag:(\S+)/',
            'category' => '/category:(\d+)/',
            'date' => '/date:(\d{4}-\d{2}-\d{2})/',
            'exclude' => '/-(\S+)/'
        ];
        
        $remaining = $searchString;
        
        // Processar cada padrão
        foreach ($patterns as $type => $pattern) {
            preg_match_all($pattern, $remaining, $matches);
            if (!empty($matches[1])) {
                if ($type === 'exclude') {
                    $this->exclude = array_merge($this->exclude, $matches[1]);
                } else {
                    $this->filters[$type] = $matches[1];
                }
                // Remover do string para não processar novamente
                $remaining = preg_replace($pattern, '', $remaining);
            }
        }
        
        // Palavras restantes são keywords normais
        $words = array_filter(explode(' ', trim($remaining)));
        $this->keywords = array_merge($this->keywords, $words);
        
        return $this;
    }
    
    public function buildQuery(&$params) {
        $conditions = [];
        $paramIndex = 0;
        
        // Keywords normais - busca em título, descrição e tags
        if (!empty($this->keywords)) {
            $keywordConditions = [];
            foreach ($this->keywords as $keyword) {
                $paramName = ':keyword' . $paramIndex++;
                $params[$paramName] = '%' . $keyword . '%';
                $keywordConditions[] = "(
                    title LIKE $paramName OR 
                    description LIKE $paramName OR 
                    tags LIKE $paramName
                )";
            }
            if (!empty($keywordConditions)) {
                $conditions[] = '(' . implode(' AND ', $keywordConditions) . ')';
            }
        }
        
        // Frases exatas (quoted)
        if (!empty($this->filters['quoted'])) {
            $quotedConditions = [];
            foreach ($this->filters['quoted'] as $phrase) {
                $paramName = ':quoted' . $paramIndex++;
                $params[$paramName] = '%' . $phrase . '%';
                $quotedConditions[] = "(
                    title LIKE $paramName OR 
                    description LIKE $paramName
                )";
            }
            if (!empty($quotedConditions)) {
                $conditions[] = '(' . implode(' OR ', $quotedConditions) . ')';
            }
        }
        
        // Filtro por domínio/source
        if (!empty($this->filters['source'])) {
            $sourceConditions = [];
            foreach ($this->filters['source'] as $source) {
                $paramName = ':source' . $paramIndex++;
                $params[$paramName] = '%' . $source . '%';
                $sourceConditions[] = "(
                    link LIKE $paramName OR 
                    source_domain LIKE $paramName OR
                    source LIKE $paramName
                )";
            }
            if (!empty($sourceConditions)) {
                $conditions[] = '(' . implode(' OR ', $sourceConditions) . ')';
            }
        }
        
        // Filtro por autor
        if (!empty($this->filters['author'])) {
            $authorConditions = [];
            foreach ($this->filters['author'] as $author) {
                $paramName = ':author' . $paramIndex++;
                $params[$paramName] = '%' . $author . '%';
                $authorConditions[] = "author LIKE $paramName";
            }
            if (!empty($authorConditions)) {
                $conditions[] = '(' . implode(' OR ', $authorConditions) . ')';
            }
        }
        
        // Filtro por tag
        if (!empty($this->filters['tag'])) {
            $tagConditions = [];
            foreach ($this->filters['tag'] as $tag) {
                $paramName = ':tag' . $paramIndex++;
                $params[$paramName] = '%' . $tag . '%';
                $tagConditions[] = "tags LIKE $paramName";
            }
            if (!empty($tagConditions)) {
                $conditions[] = '(' . implode(' OR ', $tagConditions) . ')';
            }
        }
        
        // Filtro por categoria
        if (!empty($this->filters['category'])) {
            $categoryIds = array_map('intval', $this->filters['category']);
            $conditions[] = 'category IN (' . implode(',', $categoryIds) . ')';
        }
        
        // Filtro por data
        if (!empty($this->filters['date'])) {
            foreach ($this->filters['date'] as $date) {
                $paramName = ':date' . $paramIndex++;
                $params[$paramName] = $date;
                $conditions[] = "DATE(pubDate) = $paramName";
            }
        }
        
        // Exclusões
        if (!empty($this->exclude)) {
            foreach ($this->exclude as $exclude) {
                $paramName = ':exclude' . $paramIndex++;
                $params[$paramName] = '%' . $exclude . '%';
                $conditions[] = "(
                    title NOT LIKE $paramName AND 
                    description NOT LIKE $paramName AND
                    tags NOT LIKE $paramName
                )";
            }
        }
        
        return !empty($conditions) ? ' AND ' . implode(' AND ', $conditions) : '';
    }
    
    public function hasFilters() {
        return !empty($this->keywords) || !empty($this->filters) || !empty($this->exclude);
    }
}

// Conexão otimizada com PDO
try {
    $dsn = "mysql:host={$config['host']};dbname={$config['db']};charset={$config['charset']}";
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false, // Economiza memória
        PDO::ATTR_PERSISTENT => true // Conexão persistente
    ];
    $pdo = new PDO($dsn, $config['user'], $config['pass'], $options);
    
    // Otimizações MySQL
    $pdo->exec("SET SESSION sql_mode = 'TRADITIONAL'");
    $pdo->exec("SET SESSION query_cache_type = ON");
    
} catch (PDOException $e) {
    header('Content-Type: application/json');
    die(json_encode(['error' => 'Database connection failed']));
}

// Parâmetros de entrada
$searchQuery = $_GET['search'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$offset = ($page - 1) * $config['per_page'];

// Cache
$cache = new SimpleCache();
$cacheKey = "feeds_v3_{$page}_" . md5($searchQuery);

// Verificar cache
if ($config['cache_enabled'] && $searchQuery === '') {
    $cached = $cache->get($cacheKey);
    if ($cached !== false) {
        header('Content-Type: application/json');
        header('X-Cache: HIT');
        echo json_encode($cached);
        exit;
    }
}

// Parser de busca
$parser = new SearchParser();
$parser->parse($searchQuery);

// Construir query
$sql = "SELECT 
    id,
    user_id,
    title,
    link,
    category,
    tags,
    thumbnail,
    website_source,
    upload_date,
    user_reactions,
    user_level,
    image,
    description,
    pubDate,
    guid,
    source,
    updated,
    favicon,
    embed,
    iframe,
    categories,
    actors,
    source_website,
    channel,
    author,
    video_time,
    embed_code,
    slug,
    source_domain,
    main_category_id,
    source_domain_id,
    title_cat_id,
    description_cat_id,
    tag_cat_id,
    likes,
    dislikes,
    0 as comments_count,
    0 as isSaved,
    NULL as user_action,
    0 as user_has_commented,
    '[]' as comments
FROM pinfeeds 
WHERE 1=1";

$params = [];

// Adicionar condições de busca
if ($parser->hasFilters()) {
    $sql .= $parser->buildQuery($params);
}

// Ordenação otimizada
$sql .= " ORDER BY id DESC LIMIT :offset, :limit";

// Preparar e executar
try {
    $stmt = $pdo->prepare($sql);
    
    // Bind dos parâmetros
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->bindValue(':limit', $config['per_page'], PDO::PARAM_INT);
    
    // Executar
    $startTime = microtime(true);
    $stmt->execute();
    
    // Buscar resultados
    $feeds = [];
    while ($row = $stmt->fetch()) {
        // Processar campos JSON
        if (!empty($row['user_reactions'])) {
            $row['user_reactions'] = json_decode($row['user_reactions'], true);
        }
        
        // Converter campo comments para array
        $row['comments'] = [];
        
        $feeds[] = $row;
    }
    
    $executionTime = microtime(true) - $startTime;
    
    // Salvar no cache se não houver busca
    if ($config['cache_enabled'] && $searchQuery === '') {
        $cache->set($cacheKey, $feeds);
    }
    
    // Headers de resposta
    header('Content-Type: application/json');
    header('X-Execution-Time: ' . round($executionTime * 1000, 2) . 'ms');
    header('X-Cache: MISS');
    header('Cache-Control: public, max-age=60');
    
    // Compressão
    $json = json_encode($feeds, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    
    if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'] ?? '', 'gzip') !== false) {
        header('Content-Encoding: gzip');
        echo gzencode($json, 9);
    } else {
        echo $json;
    }
    
} catch (PDOException $e) {
    header('Content-Type: application/json');
    http_response_code(500);
    echo json_encode([
        'error' => 'Query failed',
        'message' => $e->getMessage()
    ]);
}

// Fechar conexão
$pdo = null;
?>