<?php

class PeliculasController
{
    private PDO $pdo;

    public function __construct()
    {
        $db = new Database();
        $this->pdo = $db->connect();
    }

    public function index(): void
    {
        $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

        if ($id) {
            $this->show($id);
            return;
        }

        $buscar = trim((string)($_GET['buscar'] ?? ''));
        $tipo = trim((string)($_GET['tipo'] ?? ''));
        $genero = trim((string)($_GET['genero'] ?? ''));
        $pais = trim((string)($_GET['pais'] ?? ''));
        $apoyo = trim((string)($_GET['apoyo'] ?? ''));
        $duracion = trim((string)($_GET['duracion'] ?? ''));
        $orden = trim((string)($_GET['orden'] ?? 'titulo_asc'));

        $anio = filter_input(INPUT_GET, 'anio', FILTER_VALIDATE_INT);
        $anioDesde = filter_input(INPUT_GET, 'anio_desde', FILTER_VALIDATE_INT);
        $anioHasta = filter_input(INPUT_GET, 'anio_hasta', FILTER_VALIDATE_INT);

        $page = max(1, (int)($_GET['page'] ?? 1));
        $limit = min(24, max(1, (int)($_GET['limit'] ?? 12)));
        $offset = ($page - 1) * $limit;

        $where = ['p.info_publica = 1'];
        $params = [];

        if ($buscar !== '') {
            $searchColumns = [
                'p.titulo_original',
                'p.titulo_espanol',
                'p.titulo_ingles',
                'p.direccion',
                'p.produccion',
                'p.guion',
                'p.reparto',
                'p.compania_productora',
                'p.apoyos',
                'p.sinopsis_espanol'
            ];

            $searchParts = [];
            foreach ($searchColumns as $index => $column) {
                $key = ':buscar_' . $index;
                $searchParts[] = "{$column} LIKE {$key}";
                $params[$key] = "%{$buscar}%";
            }

            $where[] = '(' . implode(' OR ', $searchParts) . ')';
        }

        if ($anio) {
            $where[] = 'p.anio = :anio';
            $params[':anio'] = $anio;
        }

        if ($anioDesde) {
            $where[] = 'p.anio >= :anio_desde';
            $params[':anio_desde'] = $anioDesde;
        }

        if ($anioHasta) {
            $where[] = 'p.anio <= :anio_hasta';
            $params[':anio_hasta'] = $anioHasta;
        }

        if ($tipo !== '') {
            $where[] = 'p.tipo_produccion LIKE :tipo';
            $params[':tipo'] = "%{$tipo}%";
        }

        if ($genero !== '') {
            $where[] = 'p.genero LIKE :genero';
            $params[':genero'] = "%{$genero}%";
        }

        if ($pais !== '') {
            $where[] = 'p.pais LIKE :pais';
            $params[':pais'] = "%{$pais}%";
        }

        if ($apoyo !== '') {
            $where[] = 'p.apoyos LIKE :apoyo';
            $params[':apoyo'] = "%{$apoyo}%";
        }

        switch ($duracion) {
            case 'corta':
                $where[] = 'CAST(p.duracion AS UNSIGNED) BETWEEN 1 AND 30';
                break;
            case 'media':
                $where[] = 'CAST(p.duracion AS UNSIGNED) BETWEEN 31 AND 60';
                break;
            case 'larga':
                $where[] = 'CAST(p.duracion AS UNSIGNED) > 60';
                break;
        }

        $orderOptions = [
            'titulo_asc' => "COALESCE(NULLIF(p.titulo_espanol, ''), NULLIF(p.titulo_original, ''), p.titulo_ingles) ASC",
            'titulo_desc' => "COALESCE(NULLIF(p.titulo_espanol, ''), NULLIF(p.titulo_original, ''), p.titulo_ingles) DESC",
            'anio_desc' => "p.anio DESC, COALESCE(NULLIF(p.titulo_espanol, ''), NULLIF(p.titulo_original, ''), p.titulo_ingles) ASC",
            'anio_asc' => "p.anio ASC, COALESCE(NULLIF(p.titulo_espanol, ''), NULLIF(p.titulo_original, ''), p.titulo_ingles) ASC"
        ];

        $orderBy = $orderOptions[$orden] ?? $orderOptions['titulo_asc'];
        $whereSql = implode(' AND ', $where);

        $countSql = "SELECT COUNT(*) AS total FROM peliculas p WHERE {$whereSql}";
        $countStmt = $this->pdo->prepare($countSql);
        $countStmt->execute($params);
        $total = (int)($countStmt->fetch()['total'] ?? 0);
        $totalPages = max(1, (int)ceil($total / $limit));

        if ($page > $totalPages) {
            $page = $totalPages;
            $offset = ($page - 1) * $limit;
        }

        $sql = "
            SELECT
                p.id,
                p.sic_id,
                p.titulo_original,
                p.titulo_espanol,
                p.titulo_ingles,
                p.pais,
                p.anio,
                p.duracion,
                p.tipo_produccion,
                p.genero,
                p.idioma,
                p.direccion,
                p.produccion,
                p.compania_productora,
                p.apoyos,
                p.sinopsis_espanol,
                (
                    SELECT pi.url
                    FROM peliculas_imagenes pi
                    WHERE pi.pelicula_sic_id = p.sic_id
                    ORDER BY
                        CASE WHEN pi.tipo = 'principal' THEN 0 ELSE 1 END,
                        pi.id ASC
                    LIMIT 1
                ) AS imagen_principal
            FROM peliculas p
            WHERE {$whereSql}
            ORDER BY {$orderBy}
            LIMIT :limit OFFSET :offset
        ";

        $stmt = $this->pdo->prepare($sql);

        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
        }

        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();

        $peliculas = $stmt->fetchAll();

        jsonResponse([
            'success' => true,
            'data' => $peliculas,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => $total,
                'total_items' => $total,
                'total_pages' => $totalPages
            ],
            'filters' => [
                'buscar' => $buscar,
                'anio' => $anio ?: '',
                'anio_desde' => $anioDesde ?: '',
                'anio_hasta' => $anioHasta ?: '',
                'tipo' => $tipo,
                'genero' => $genero,
                'pais' => $pais,
                'duracion' => $duracion,
                'apoyo' => $apoyo,
                'orden' => $orden
            ]
        ]);
    }

    private function show(int $id): void
    {
        $sql = "
            SELECT *
            FROM peliculas
            WHERE sic_id = :id
              AND info_publica = 1
            LIMIT 1
        ";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $pelicula = $stmt->fetch();

        if (!$pelicula) {
            jsonResponse([
                'success' => false,
                'message' => 'Película no encontrada'
            ], 404);
        }

        $imgStmt = $this->pdo->prepare("
            SELECT
                id,
                imagen_id,
                url,
                tipo,
                pie,
                descripcion,
                autor,
                fecha_incorporacion
            FROM peliculas_imagenes
            WHERE pelicula_sic_id = :sic_id
            ORDER BY
                CASE WHEN tipo = 'principal' THEN 0 ELSE 1 END,
                id ASC
        ");

        $imgStmt->execute([':sic_id' => $pelicula['sic_id']]);
        $imagenes = $imgStmt->fetchAll();

        unset($pelicula['raw_json']);

        jsonResponse([
            'success' => true,
            'data' => [
                'pelicula' => $pelicula,
                'imagenes' => $imagenes
            ]
        ]);
    }
}
