<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit;
}

require_once __DIR__ . '/helpers/response.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/services/SicService.php';
require_once __DIR__ . '/controllers/SyncController.php';
require_once __DIR__ . '/controllers/PeliculasController.php';

$route = $_GET['r'] ?? '';

try {
    switch ($route) {

        case 'test':
            jsonResponse([
                'success' => true,
                'message' => 'API Cinema México funcionando correctamente'
            ]);
            break;

        case 'db/test':
            $db = new Database();
            $pdo = $db->connect();

            $stmt = $pdo->query('SELECT NOW() AS fecha_servidor');

            jsonResponse([
                'success' => true,
                'message' => 'Conexión a base de datos correcta',
                'data' => $stmt->fetch()
            ]);
            break;

        case 'sic/peliculas':
            $sic = new SicService();
            $data = $sic->getRecords('produccion_cine');

            jsonResponse([
                'success' => true,
                'total' => count($data),
                'sample' => array_slice($data, 0, 3)
            ]);
            break;

        case 'sic/peliculas-imagenes':
            $sic = new SicService();
            $data = $sic->getImages('produccion_cine');

            jsonResponse([
                'success' => true,
                'total' => count($data),
                'sample' => array_slice($data, 0, 3)
            ]);
            break;

        case 'sync/peliculas':
            $controller = new SyncController();
            $controller->syncPeliculas();
            break;
        
        case 'peliculas':
            $controller = new PeliculasController();
            $controller->index();
            break;    
        case 'sic/buscar-imagen':
            $q = trim($_GET['q'] ?? '');

            if ($q === '') {
                jsonResponse([
                    'success' => false,
                    'message' => 'Debes enviar un texto de búsqueda'
                ], 422);
            }

            $sic = new SicService();
            $imagenes = $sic->getImages('produccion_cine');

            $filtradas = array_values(array_filter($imagenes, function ($img) use ($q) {
                $url = $img['url'] ?? '';
                $tablaId = (string)($img['tabla_id'] ?? '');
                $imagenId = (string)($img['imagen_id'] ?? '');

                return stripos($url, $q) !== false
                    || stripos($tablaId, $q) !== false
                    || stripos($imagenId, $q) !== false;
            }));

            jsonResponse([
                'success' => true,
                'busqueda' => $q,
                'total' => count($filtradas),
                'data' => $filtradas
            ]);
            break;
        
        case 'sic/imagenes-por-pelicula':
    $id = (int)($_GET['id'] ?? 0);

    if ($id <= 0) {
        jsonResponse([
            'success' => false,
            'message' => 'ID inválido'
        ], 422);
    }

    $sic = new SicService();
    $imagenes = $sic->getImages('produccion_cine');

    $filtradas = array_values(array_filter($imagenes, function ($img) use ($id) {
        return (int)($img['tabla_id'] ?? 0) === $id;
    }));

    jsonResponse([
        'success' => true,
        'sic_id' => $id,
        'total' => count($filtradas),
        'data' => $filtradas
    ]);
    break;
        
            default:
            jsonResponse([
                'success' => false,
                'message' => 'Ruta no encontrada',
                'route' => $route
            ], 404);
    }

} catch (Exception $e) {
    jsonResponse([
        'success' => false,
        'message' => 'Error en la API',
        'error' => $e->getMessage()
    ], 500);
}