<?php
session_start();

if (!isset($_SESSION['user_logged'])) {
    header('Location: index.php');
    exit;
}

$username = $_SESSION['username'];
$password = $_SESSION['password'];
$server_url = $_SESSION['server_url'];
$server_name = $_SESSION['server_name'];

function makeApiRequest($url, $action, $params = []) {
    global $username, $password, $server_url;
    
    $base_params = [
        'username' => $username,
        'password' => $password,
        'action' => $action
    ];
    
    $all_params = array_merge($base_params, $params);
    $query_string = http_build_query($all_params);
    $full_url = rtrim($server_url, '/') . '/player_api.php?' . $query_string;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $full_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($response && $http_code == 200) {
        return json_decode($response, true);
    }
    
    return false;
}

function searchContent($search_query) {
    $search_query = strtolower(trim($search_query));
    
    $movies_api = makeApiRequest('', 'get_vod_streams') ?: [];
    $series_api = makeApiRequest('', 'get_series') ?: [];
    
    $movie_results = [];
    $series_results = [];
    
    foreach ($movies_api as $movie) {
        if (stripos(strtolower($movie['name']), $search_query) !== false) {
            $movie_results[] = [
                'title' => htmlspecialchars($movie['name']),
                'id' => htmlspecialchars($movie['stream_id']),
                'poster' => filter_var($movie['stream_icon'], FILTER_VALIDATE_URL) ? $movie['stream_icon'] : "https://via.placeholder.com/300x450/232f3e/00a8e1?text=No+Image",
                'rating' => isset($movie['rating']) ? floatval($movie['rating']) : 0,
                'year' => isset($movie['year']) ? intval($movie['year']) : 0,
                'description' => isset($movie['plot']) ? htmlspecialchars($movie['plot']) : '',
                'genre' => isset($movie['genre']) ? htmlspecialchars($movie['genre']) : '',
                'duration' => isset($movie['duration']) ? htmlspecialchars($movie['duration']) : '',
                'quality' => isset($movie['container_extension']) ? strtoupper($movie['container_extension']) : 'HD'
            ];
        }
    }
    
    foreach ($series_api as $series) {
        if (stripos(strtolower($series['name']), $search_query) !== false) {
            $series_results[] = [
                'title' => htmlspecialchars($series['name']),
                'id' => htmlspecialchars($series['series_id']),
                'poster' => filter_var($series['cover'], FILTER_VALIDATE_URL) ? $series['cover'] : "https://via.placeholder.com/300x450/232f3e/00a8e1?text=No+Image",
                'rating' => isset($series['rating']) ? floatval($series['rating']) : 0,
                'year' => isset($series['year']) ? intval($series['year']) : 0,
                'description' => isset($series['plot']) ? htmlspecialchars($series['plot']) : '',
                'genre' => isset($series['genre']) ? htmlspecialchars($series['genre']) : ''
            ];
        }
    }
    
    return ['movies' => $movie_results, 'series' => $series_results];
}

$search_query = isset($_GET['q']) ? trim($_GET['q']) : '';
$search_results = [];

if (!empty($search_query)) {
    $search_results = searchContent($search_query);
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Búsqueda - IPTV Pro</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: #141414;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
            color: #ffffff;
            overflow-x: hidden;
        }

        /* Header styling - Netflix style */
        .netflix-header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
            background: linear-gradient(to bottom, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0.7) 50%, transparent 100%);
            padding: 1.2rem 3rem;
            transition: all 0.3s ease;
        }

        .netflix-header.scrolled {
            background: #141414;
            padding: 0.8rem 3rem;
            box-shadow: 0 1px 10px rgba(0,0,0,0.5);
        }

        /* Main content area */
        .content-area {
            min-height: 100vh;
            background: #141414;
            padding-top: 80px;
        }

        /* Hero Search Section */
        .search-hero {
            background: linear-gradient(135deg, #1a1a1a 0%, #0a0a0a 100%);
            padding: 40px 0 60px 0;
            margin-bottom: 30px;
            border-bottom: 1px solid #333;
        }

        .search-header {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 40px;
            text-align: center;
        }

        .search-icon {
            font-size: 3rem;
            color: #e50914;
            margin-bottom: 20px;
        }

        .search-header h1 {
            font-size: 3rem;
            font-weight: 700;
            margin-bottom: 15px;
            letter-spacing: -1px;
        }

        .search-query {
            color: #e50914;
            font-size: 1.2rem;
            display: inline-block;
            margin-top: 10px;
            padding: 5px 15px;
            background: rgba(229, 9, 20, 0.1);
            border-radius: 20px;
        }

        /* Stats Cards - Netflix style */
        .stats-container {
            max-width: 1200px;
            margin: -30px auto 30px;
            padding: 0 40px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 25px;
        }

        .stat-card {
            background: linear-gradient(135deg, #1a1a1a 0%, #0f0f0f 100%);
            border-radius: 12px;
            padding: 25px;
            text-align: center;
            transition: transform 0.3s ease;
            border: 1px solid #333;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            border-color: #e50914;
        }

        .stat-number {
            font-size: 2.5rem;
            font-weight: 800;
            color: #e50914;
            display: block;
            margin-bottom: 10px;
        }

        .stat-label {
            font-size: 0.9rem;
            color: #999;
            text-transform: uppercase;
            letter-spacing: 2px;
            font-weight: 600;
        }

        /* Tab Navigation - Netflix style */
        .tab-container {
            max-width: 1200px;
            margin: 0 auto 30px;
            padding: 0 40px;
        }

        .tab-navigation {
            display: flex;
            gap: 10px;
            background: #1a1a1a;
            border-radius: 12px;
            padding: 8px;
            border: 1px solid #333;
        }

        .tab-btn {
            flex: 1;
            background: transparent;
            border: none;
            color: #999;
            padding: 12px 20px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .tab-btn i {
            font-size: 1.1rem;
        }

        .tab-btn.active {
            background: #e50914;
            color: white;
        }

        .tab-btn:hover:not(.active) {
            color: white;
            background: #333;
        }

        /* Movie Grid - Netflix style */
        .movies-section {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 40px 60px;
        }

        .section-title {
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 25px;
            padding-left: 5px;
            border-left: 4px solid #e50914;
        }

        .movie-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 25px;
        }

        .movie-card {
            cursor: pointer;
            transition: transform 0.3s ease;
            border-radius: 8px;
            overflow: hidden;
            background: #1a1a1a;
        }

        .movie-card:hover {
            transform: scale(1.05);
            z-index: 10;
        }

        .movie-poster-container {
            position: relative;
            aspect-ratio: 2/3;
            overflow: hidden;
            background: linear-gradient(135deg, #2a2a2a, #1a1a1a);
        }

        .movie-poster {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
        }

        .movie-card:hover .movie-poster {
            transform: scale(1.1);
        }

        .movie-badges {
            position: absolute;
            top: 10px;
            left: 10px;
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .badge {
            background: rgba(0,0,0,0.8);
            backdrop-filter: blur(5px);
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: 700;
            text-transform: uppercase;
        }

        .badge-quality {
            background: #e50914;
            color: white;
        }

        .badge-series {
            background: #4a4a4a;
            color: white;
        }

        .rating-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(0,0,0,0.8);
            backdrop-filter: blur(5px);
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .rating-badge i {
            color: #ffd700;
            font-size: 0.7rem;
        }

        .movie-info {
            padding: 15px;
        }

        .movie-title {
            font-weight: 700;
            font-size: 1rem;
            margin-bottom: 8px;
            line-height: 1.3;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .movie-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #999;
            font-size: 0.8rem;
            margin-bottom: 8px;
        }

        .movie-genre {
            color: #e50914;
            font-size: 0.75rem;
            font-weight: 600;
            margin-bottom: 8px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .movie-description {
            color: #999;
            font-size: 0.75rem;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 80px 20px;
        }

        .empty-state i {
            font-size: 5rem;
            color: #333;
            margin-bottom: 20px;
        }

        .empty-state h3 {
            font-size: 1.8rem;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .empty-state p {
            color: #999;
            font-size: 1rem;
        }

        /* Tab Panels */
        .tab-panel {
            display: none;
        }

        .tab-panel.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Responsive */
        @media (max-width: 768px) {
            .netflix-header {
                padding: 1rem 1.5rem;
            }

            .search-header {
                padding: 0 20px;
            }

            .search-header h1 {
                font-size: 2rem;
            }

            .stats-grid {
                gap: 15px;
            }

            .stat-card {
                padding: 15px;
            }

            .stat-number {
                font-size: 1.8rem;
            }

            .movies-section {
                padding: 0 20px 40px;
            }

            .movie-grid {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
                gap: 15px;
            }

            .movie-title {
                font-size: 0.85rem;
            }
        }

        /* Scrollbar styling */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #1a1a1a;
        }

        ::-webkit-scrollbar-thumb {
            background: #e50914;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #ff0a16;
        }

        /* Loading effect */
        .movie-card.loading {
            opacity: 0.7;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <?php include 'header.php'; ?>

    <div class="content-area">
        <!-- Hero Section -->
        <div class="search-hero">
            <div class="search-header">
                <div class="search-icon">
                    <i class="fas fa-search"></i>
                </div>
                <h1>Resultados de Búsqueda</h1>
                <?php if (!empty($search_query)): ?>
                    <div class="search-query">
                        <i class="fas fa-quote-left"></i> <?= htmlspecialchars($search_query) ?> <i class="fas fa-quote-right"></i>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php if (!empty($search_query) && (!empty($search_results['movies']) || !empty($search_results['series']))): ?>
            
            <!-- Stats Section -->
            <div class="stats-container">
                <div class="stats-grid">
                    <div class="stat-card">
                        <span class="stat-number"><?= count($search_results['movies']) ?></span>
                        <span class="stat-label">Películas</span>
                    </div>
                    <div class="stat-card">
                        <span class="stat-number"><?= count($search_results['series']) ?></span>
                        <span class="stat-label">Series</span>
                    </div>
                    <div class="stat-card">
                        <span class="stat-number"><?= count($search_results['movies']) + count($search_results['series']) ?></span>
                        <span class="stat-label">Total</span>
                    </div>
                </div>
            </div>

            <!-- Tab Navigation -->
            <div class="tab-container">
                <div class="tab-navigation">
                    <button class="tab-btn active" data-tab="movies">
                        <i class="fas fa-film"></i>
                        Películas <span style="margin-left: 5px;">(<?= count($search_results['movies']) ?>)</span>
                    </button>
                    <button class="tab-btn" data-tab="series">
                        <i class="fas fa-tv"></i>
                        Series <span style="margin-left: 5px;">(<?= count($search_results['series']) ?>)</span>
                    </button>
                </div>
            </div>

            <!-- Movies Tab -->
            <div id="movies-panel" class="tab-panel active">
                <div class="movies-section">
                    <?php if (!empty($search_results['movies'])): ?>
                        <h2 class="section-title">
                            <i class="fas fa-film" style="margin-right: 10px;"></i>
                            Películas
                        </h2>
                        <div class="movie-grid">
                            <?php foreach ($search_results['movies'] as $movie): ?>
                                <div class="movie-card" onclick="openMovie(<?= $movie['id'] ?>)">
                                    <div class="movie-poster-container">
                                        <img class="movie-poster" 
                                             src="<?= $movie['poster'] ?>" 
                                             alt="<?= $movie['title'] ?>"
                                             loading="lazy"
                                             onerror="this.src='https://via.placeholder.com/300x450/141414/e50914?text=No+Image'">
                                        <div class="movie-badges">
                                            <?php if (!empty($movie['quality'])): ?>
                                                <div class="badge badge-quality"><?= $movie['quality'] ?></div>
                                            <?php endif; ?>
                                        </div>
                                        <?php if ($movie['rating'] > 0): ?>
                                            <div class="rating-badge">
                                                <i class="fas fa-star"></i>
                                                <?= number_format($movie['rating'], 1) ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="movie-info">
                                        <div class="movie-title"><?= $movie['title'] ?></div>
                                        <div class="movie-meta">
                                            <span><?= $movie['year'] > 0 ? $movie['year'] : 'N/A' ?></span>
                                            <?php if (!empty($movie['duration'])): ?>
                                                <span><i class="far fa-clock"></i> <?= $movie['duration'] ?></span>
                                            <?php endif; ?>
                                        </div>
                                        <?php if (!empty($movie['genre'])): ?>
                                            <div class="movie-genre"><?= htmlspecialchars(substr($movie['genre'], 0, 30)) ?></div>
                                        <?php endif; ?>
                                        <?php if (!empty($movie['description'])): ?>
                                            <div class="movie-description"><?= htmlspecialchars(substr($movie['description'], 0, 80)) ?>...</div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-film"></i>
                            <h3>No hay películas</h3>
                            <p>No se encontraron películas para "<?= htmlspecialchars($search_query) ?>"</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Series Tab -->
            <div id="series-panel" class="tab-panel">
                <div class="movies-section">
                    <?php if (!empty($search_results['series'])): ?>
                        <h2 class="section-title">
                            <i class="fas fa-tv" style="margin-right: 10px;"></i>
                            Series
                        </h2>
                        <div class="movie-grid">
                            <?php foreach ($search_results['series'] as $series): ?>
                                <div class="movie-card" onclick="openSeries(<?= $series['id'] ?>)">
                                    <div class="movie-poster-container">
                                        <img class="movie-poster" 
                                             src="<?= $series['poster'] ?>" 
                                             alt="<?= $series['title'] ?>"
                                             loading="lazy"
                                             onerror="this.src='https://via.placeholder.com/300x450/141414/e50914?text=No+Image'">
                                        <div class="movie-badges">
                                            <div class="badge badge-series">SERIE</div>
                                        </div>
                                        <?php if ($series['rating'] > 0): ?>
                                            <div class="rating-badge">
                                                <i class="fas fa-star"></i>
                                                <?= number_format($series['rating'], 1) ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="movie-info">
                                        <div class="movie-title"><?= $series['title'] ?></div>
                                        <div class="movie-meta">
                                            <span><?= $series['year'] > 0 ? $series['year'] : 'N/A' ?></span>
                                            <span><i class="fas fa-tv"></i> Series</span>
                                        </div>
                                        <?php if (!empty($series['genre'])): ?>
                                            <div class="movie-genre"><?= htmlspecialchars(substr($series['genre'], 0, 30)) ?></div>
                                        <?php endif; ?>
                                        <?php if (!empty($series['description'])): ?>
                                            <div class="movie-description"><?= htmlspecialchars(substr($series['description'], 0, 80)) ?>...</div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-tv"></i>
                            <h3>No hay series</h3>
                            <p>No se encontraron series para "<?= htmlspecialchars($search_query) ?>"</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

        <?php elseif (!empty($search_query)): ?>
            <div class="empty-state">
                <i class="fas fa-search"></i>
                <h3>Sin resultados</h3>
                <p>No se encontró contenido para "<?= htmlspecialchars($search_query) ?>"</p>
                <p style="margin-top: 20px; font-size: 0.9rem;">Prueba con otras palabras clave</p>
            </div>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-search"></i>
                <h3>Buscar contenido</h3>
                <p>Usa la búsqueda para encontrar películas y series</p>
                <p style="margin-top: 10px; font-size: 0.9rem;">Escribe el título, actor o género</p>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function openMovie(movieId) {
            const card = event.currentTarget;
            card.classList.add('loading');
            setTimeout(() => {
                window.location.href = `movie-detail.php?id=${movieId}`;
            }, 200);
        }

        function openSeries(seriesId) {
            const card = event.currentTarget;
            card.classList.add('loading');
            setTimeout(() => {
                window.location.href = `series-detail.php?id=${seriesId}`;
            }, 200);
        }

        // Tab switching
        document.addEventListener('DOMContentLoaded', function() {
            const tabBtns = document.querySelectorAll('.tab-btn');
            const tabPanels = document.querySelectorAll('.tab-panel');

            tabBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    const targetTab = this.getAttribute('data-tab');
                    
                    tabBtns.forEach(b => b.classList.remove('active'));
                    tabPanels.forEach(p => p.classList.remove('active'));
                    
                    this.classList.add('active');
                    document.getElementById(targetTab + '-panel').classList.add('active');
                });
            });

            // Header scroll effect
            const header = document.querySelector('.netflix-header');
            if (header) {
                window.addEventListener('scroll', function() {
                    if (window.scrollY > 50) {
                        header.classList.add('scrolled');
                    } else {
                        header.classList.remove('scrolled');
                    }
                });
            }

            // Lazy load images with Intersection Observer
            const imageObserver = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        img.src = img.dataset.src || img.src;
                        observer.unobserve(img);
                    }
                });
            });

            document.querySelectorAll('.movie-poster').forEach(img => {
                imageObserver.observe(img);
            });
        });
    </script>
</body>
</html>