<?php

namespace app\modules\apiv1; 

use Yii;
use sizeg\jwt\JwtHttpBearerAuth;

class Apiv1Module extends \yii\base\Module
{
    public $controllerNamespace = 'app\modules\apiv1\controllers';

    public function init()  
    {
        parent::init();
        Yii::$app->user->enableSession = false; 
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    }  

    public function behaviors()
    { 
        $behaviors = parent::behaviors();

        // Agregar autenticador y validación de token
        $auth = $behaviors['authenticator'] = [
            'class' => JwtHttpBearerAuth::class,
            'except' => [
                'login/*',           // Excluye rutas de login
                'options',           // Excluye las peticiones OPTIONS (preflight)
                'pdf/*',
                // 'pdf/generate',      // Excluye la ruta de generación de PDF
                'product-image/public-image',
                'transaction-qr/confirm-payment',
                'ssl-printer/*'
            ],
        ];
        
        // Remover autenticador temporalmente
        unset($behaviors['authenticator']);

        // Configuración de CORS
        $behaviors['corsFilter'] = [
            'class' => \yii\filters\Cors::class,
            'cors' => [
                'Origin' => static::allowedDomains(),
                'Access-Control-Request-Method' => ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'], // Métodos permitidos
                'Access-Control-Allow-Credentials' => true, // Permitir credenciales (si es necesario)
                'Access-Control-Allow-Headers' => ['authorization', 'X-Requested-With', 'content-type'],
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
                'Access-Control-Max-Age' => 3600,
            ],
        ];

        // Volver a habilitar autenticador y excluir las opciones
        $behaviors['authenticator'] = $auth;
        $behaviors['authenticator']['except'] = array_merge(
            $auth['except'], 
            ['options'] // Excluir también las solicitudes OPTIONS
        );

        return $behaviors;
    }
    
    public static function allowedDomains() {
        return [
            $_SERVER["REMOTE_ADDR"], 
            'http://localhost', 
            'http://localhost:5173',  
            'http://localhost:5174', 
            'http://localhost:5175', 
            'http://localhost:7143',
            'http://localhost:5176', 
            'http://192.168.0.100:5173',
            'https://dev.restaurante.ioox.io', 
            'https://restaurante.velooz.io',
            'https://dev.tienda.ioox.io',
            'http://tienda.ioox.io',
            'https://dev.servicio.ioox.io',
        ];
    }
}
