<?php
// Gestión de sesión y seguridad
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

$username = $_SESSION['username'] ?? 'Usuario';
$password = $_SESSION['password'] ?? '';
$server_url = $_SESSION['server_url'] ?? '';

// Función para peticiones a la API
function makeApiRequest($action, $params = []) {
    global $username, $password, $server_url;
    
    if (empty($server_url)) return false;

    $base_params = [
        'username' => $username,
        'password' => $password,
        'action' => $action
    ];
    
    $all_params = array_merge($base_params, $params);
    $full_url = rtrim($server_url, '/') . '/player_api.php?' . http_build_query($all_params);
    
    $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_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return ($response && $http_code == 200) ? json_decode($response, true) : false;
}

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

if (!empty($search_query)) {
    $q = strtolower($search_query);
    
    // Obtener datos
    $all_movies = makeApiRequest('get_vod_streams') ?: [];
    $all_series = makeApiRequest('get_series') ?: [];
    
    // Filtrar Películas
    foreach ($all_movies as $m) {
        if (stripos(strtolower($m['name']), $q) !== false) {
            $movie_results[] = $m;
        }
    }
    
    // Filtrar Series
    foreach ($all_series as $s) {
        if (stripos(strtolower($s['name']), $q) !== false) {
            $series_results[] = $s;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Búsqueda: <?= htmlspecialchars($search_query) ?> - JTECH TV</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --netflix-red: #E50914;
            --netflix-black: #141414;
            --netflix-dark-gray: #181818;
            --text-white: #ffffff;
            --text-gray: #a3a3a3;
        }

        body {
            background-color: var(--netflix-black);
            color: var(--text-white);
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            margin: 0;
            overflow-x: hidden;
        }

        /* Ajuste para el header fijo */
        .main-content {
            padding-top: 100px;
            padding-bottom: 50px;
            min-height: 100vh;
        }

        .container-fluid {
            padding: 0 4%;
        }

        .search-info {
            margin-bottom: 30px;
        }

        .search-info h2 {
            font-size: 1.5rem;
            color: var(--text-gray);
            font-weight: 400;
        }

        .search-info b {
            color: var(--text-white);
        }

        /* Secciones Estilo Netflix */
        .content-section {
            margin-bottom: 40px;
        }

        .section-title {
            font-size: 1.4rem;
            font-weight: 700;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* Grid de Películas y Series */
        .content-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 10px;
        }

        .content-card {
            position: relative;
            background: var(--netflix-dark-gray);
            border-radius: 4px;
            overflow: hidden;
            transition: transform 0.3s ease, z-index 0.3s ease;
            cursor: pointer;
            aspect-ratio: 2/3;
        }

        .content-card:hover {
            transform: scale(1.1);
            z-index: 10;
            box-shadow: 0 10px 20px rgba(0,0,0,0.6);
        }

        .content-card img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .card-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(to top, rgba(0,0,0,0.9) 0%, transparent 100%);
            padding: 15px 10px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .content-card:hover .card-overlay {
            opacity: 1;
        }

        .card-title {
            font-size: 0.9rem;
            font-weight: bold;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .card-meta {
            font-size: 0.75rem;
            display: flex;
            align-items: center;
            gap: 8px;
            color: #46d369; /* Verde estilo Netflix rating */
        }

        .badge-hd {
            border: 1px solid var(--text-gray);
            padding: 0 4px;
            border-radius: 2px;
            font-size: 0.6rem;
            color: var(--text-white);
        }

        /* Mensaje de vacío */
        .no-results {
            text-align: center;
            padding: 100px 20px;
            color: var(--text-gray);
        }

        .no-results i {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.3;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .content-grid {
                grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
            }
            .main-content { padding-top: 80px; }
        }
    </style>
</head>
<body>

    <?php include 'header.php'; ?>

    <main class="main-content">
        <div class="container-fluid">
            
            <?php if (!empty($search_query)): ?>
                <div class="search-info">
                    <h2>Resultados para: <b>"<?= htmlspecialchars($search_query) ?>"</b></h2>
                </div>

                <?php if (empty($movie_results) && empty($series_results)): ?>
                    <div class="no-results">
                        <i class="fas fa-search-minus"></i>
                        <h3>No encontramos coincidencias</h3>
                        <p>Intenta con palabras más generales o el nombre original.</p>
                    </div>
                <?php else: ?>

                    <!-- SECCIÓN PELÍCULAS -->
                    <?php if (!empty($movie_results)): ?>
                    <section class="content-section">
                        <h3 class="section-title"><i class="fas fa-film text-danger"></i> Películas</h3>
                        <div class="content-grid">
                            <?php foreach ($movie_results as $movie): ?>
                                <div class="content-card" onclick="location.href='movie-detail.php?id=<?= $movie['stream_id'] ?>'">
                                    <img src="<?= $movie['stream_icon'] ?>" onerror="this.src='https://via.placeholder.com/300x450/181818/ffffff?text=Sin+Imagen'">
                                    <div class="card-overlay">
                                        <div class="card-title"><?= htmlspecialchars($movie['name']) ?></div>
                                        <div class="card-meta">
                                            <span><?= round($movie['rating'] ?? 0, 1) ?> <i class="fas fa-star"></i></span>
                                            <span class="badge-hd">HD</span>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </section>
                    <?php endif; ?>

                    <!-- SECCIÓN SERIES -->
                    <?php if (!empty($series_results)): ?>
                    <section class="content-section">
                        <h3 class="section-title"><i class="fas fa-tv text-primary"></i> Series</h3>
                        <div class="content-grid">
                            <?php foreach ($series_results as $series): ?>
                                <div class="content-card" onclick="location.href='series-detail.php?id=<?= $series['series_id'] ?>'">
                                    <img src="<?= $series['cover'] ?>" onerror="this.src='https://via.placeholder.com/300x450/181818/ffffff?text=Sin+Imagen'">
                                    <div class="card-overlay">
                                        <div class="card-title"><?= htmlspecialchars($series['name']) ?></div>
                                        <div class="card-meta">
                                            <span><?= round($series['rating'] ?? 0, 1) ?> <i class="fas fa-star"></i></span>
                                            <span class="badge-hd">SERIE</span>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </section>
                    <?php endif; ?>

                <?php endif; ?>

            <?php else: ?>
                <div class="no-results">
                    <i class="fas fa-search"></i>
                    <h3>¿Qué quieres ver hoy?</h3>
                    <p>Escribe el nombre de una película o serie en el buscador del menú.</p>
                </div>
            <?php endif; ?>

        </div>
    </main>

</body>
</html>