<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Session;
use App\Custom\SQLConnection;
use App\Custom\Misc;
use DateTime;


class PrensaController extends Controller
{
    public static function prensaPorIdCanal(){
        $id_canal = Request::input('id_channel');        
        #$pagina = Request::input('pagina') ?? 1;
        $fechaDesde = Request::input('fecha_desde') ?? date('Y-m-d');
        $fechaHasta = Request::input('fecha_hasta') ?? date('Y-m-d');        
        
        if (empty($id_canal)) {
            http_response_code(400);
            return response()->json([
                "status" => "error",
                "code" => 400,
                "message" => "id_canal is required",
                "data" => null,
                "meta" => [
                    "timestamp" => now()->toISOString(),
                    "request_id" => uniqid(),
                    "version" => "1.0"
                ]
            ]); 
        }
        
        $verificar_token = self::verificarTokenPrensa();        

        if ($verificar_token == 0) {
            http_response_code(401);
            return response()->json([
                "status" => "error",
                "code" => 401,
                "message" => "Can't generate token for API",
                "data" => null,
                "meta" => [
                    "timestamp" => now()->toISOString(),
                    "request_id" => uniqid(),
                    "version" => "1.0"
                ]
            ]);
        }
        
        $token = $verificar_token;

        $url = env('PRENSA_CANAL_URL_2');

        $data = ["token" => $token, "id_canal" => $id_canal, "fecha_desde" => $fechaDesde , "fecha_hasta" => $fechaHasta ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            http_response_code(500);
            return response()->json([
                "status" => "error",
                "code" => 500,
                "message" => 'Error en cURL: ' . curl_error($ch),
                "data" => null,
                "meta" => [
                    "timestamp" => now()->toISOString(),
                    "request_id" => uniqid(),
                    "version" => "1.0"
                ]
            ]);
        }

        curl_close($ch);
        
        $responseArray = json_decode($response, true);     
        
        if (empty($responseArray['ejes_content'][0][0])) {
            http_response_code(404);
            return response()->json([
                "status" => "error",
                "code" => 404,
                "message" => "chanel not found",
                "data" => null,
                "meta" => [
                    "timestamp" => now()->toISOString(),
                    "request_id" => uniqid(),
                    "version" => "1.0"
                ]
            ]);
        }

        $canal = $responseArray['ejes_content'][0][0];
        $apiStatus = $responseArray['error'] ?? null;        
        $noticias = $responseArray['ejes_content'][0][0]['noticias'] ?? [];     
           

        if (empty($noticias)) {           
            http_response_code(200);
            return response()->json([
                "status" => "200",
                "code" => 200,
                "message" => "No news found for the specified channel",
                "data" => null,
                "meta" => [
                    "timestamp" => now()->toISOString(),
                    "request_id" => uniqid(),
                    "version" => "1.0"
                ]
            ]);
        }
                
        foreach ($noticias as $noticia) {
            $id_noticia     = $noticia['id_noticia'] ?? null;
            $fecha          = $noticia['fecha'] ?? null;
            $fecha_hora     = $noticia['fecha_hora'] ?? null;
            $medio          = $noticia['medio'] ?? null;
            $tipo_medio     = $noticia['tipo_medio'] ?? null;
            $programa       = $noticia['programa'] ?? null;
            $precopete      = !empty($noticia['precopete']) ? $noticia['precopete'] : null;
            $titulo         = !empty($noticia['titulo']) ? $noticia['titulo'] : null;
            $copete         = !empty($noticia['copete']) ? $noticia['copete'] : null;
            $entrevistado   = !empty($noticia['entrevistado']) ? $noticia['entrevistado'] : null;
            $texto_anticipo = !empty($noticia['texto_anticipo']) ? $noticia['texto_anticipo'] : null;
            $menciones      = !empty($noticia['menciones']) ? $noticia['menciones'] : null;
            $icono_noticia  = !empty($noticia['icono_noticia']) ? $noticia['icono_noticia'] : null;
            $captura_web    = !empty($noticia['captura_web']) ? $noticia['captura_web'] : null;
            $imagenes       = !empty($noticia['imagenes']) ? json_encode($noticia['imagenes']) : null;
            $thumbnails     = !empty($noticia['thumbnails']) ? json_encode($noticia['thumbnails']) : null;
            $videos         = !empty($noticia['videos']) ? json_encode($noticia['videos']) : null;
            $audios         = !empty($noticia['audios']) ? json_encode($noticia['audios']) : null;
            $url_web        = !empty($noticia['url_web']) ? $noticia['url_web'] : null;
            $id_canal       = $noticia['id_canal'] ?? null;
            $audiencia    = $noticia['audiencia'] ?? null;

            $mapCanalContraparte = [
                6510840 => [
                    'contraparte' => 259089,
                    'nombre'      => 'PELLEGRINI S A GERENTE DE FONDOS COMUNES DE INVERSION'
                ],
                8062891 => [
                    'contraparte' => 263478,
                    'nombre'      => 'NACION SERVICIOS SA'
                ],
                3090230 => [
                    'contraparte' => 259094,
                    'nombre'      => 'NACION SEGUROS SOCIEDAD ANONIMA'
                ],
                3807164 => [
                    'contraparte' => 259096,
                    'nombre'      => 'NACION SEGUROS DE RETIRO SA'
                ],
                7717356 => [
                    'contraparte' => 259835,
                    'nombre'      => 'NACION REASEGUROS SA'
                ],
                5134745 => [
                    'contraparte' => 259091,
                    'nombre'      => 'NACION BURSATIL SA'
                ],
                4786316 => [
                    'contraparte' => 259099,
                    'nombre'      => 'GARANTIZAR SOCIEDAD DE GARANTIA RECIPROCA'
                ],
            ];

            
            $contraparte   = $mapCanalContraparte[$id_canal]['contraparte'] ?? null;
            #$nombreEntidad = $mapCanalContraparte[$id_canal]['nombre'] ?? null;    
           
            SQLConnection::backendStoreProcedure('prensa_insertar', [
                $id_noticia,
                $fecha,
                $fecha_hora,
                $medio,
                $tipo_medio,
                $programa,
                $precopete,
                $titulo,
                $copete,
                $entrevistado,
                $texto_anticipo,
                $menciones,
                $icono_noticia,
                $captura_web,
                $imagenes,
                $thumbnails,
                $videos,
                $audios,
                $url_web,
                $id_canal,
                $audiencia,
                $contraparte
            ]); 
        }           

        return response()->json([
            "status" => $apiStatus['status'] ?? "ok",
            "code" => (int)($apiStatus['status_code'] ?? 200),
            "message" => $apiStatus['message'] ?? "OK",
            "data" => [
                "id_canal" => $canal['id_canal'],
                "nombre" => $canal['nombre_canal'],
                "tags" => explode(',', $canal['tags']),
                "noticias" => $canal['noticias'],
            ],
            "meta" => [
                "timestamp" => now()->toISOString(),
                "request_id" => uniqid(),
                "version" => "1.0"
            ]
        ]);

    }


    public static function verificarTokenPrensa(){        
        //Primero verifico si existe un token valido
        $tokenData = SQLConnection::backendStoreProcedure('prensa_getToken', ['get_token']);        

        if (empty($tokenData)) {
            $buscarToken = self::tokenPrensaExterno();

            if ($buscarToken == 0) {
                return 0;
            }
            
            return $buscarToken;
        }else{
            $fechaExpira = new DateTime($tokenData[0]->expira);
            $ahora = new DateTime();

            $diffSegundos = $ahora->getTimestamp() - $fechaExpira->getTimestamp();

            // Si el token expiro hace mas de 1 hora
            if ($diffSegundos > 3600) {
                $buscarToken = self::tokenPrensaExterno();

                if ($buscarToken == 0) {
                    return 0;
                }

                return $buscarToken;
            } else {
                return $tokenData[0]->token;
            }

        }        
    }

    //#Funcion para generar token de prensa externo
    //# Obtenemos tambien los datos de los canales asociados al usuario
    public static function tokenPrensaExterno()
    {
        $username = env('PRENSA_USER');
        $password = env('PRENSA_PASS');

        
        if (empty($username) || empty($password)) {          
            return 0;    
        }

        $url = env('PRENSA_URL');
        $data = ["username" => $username, "password" => $password];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        $response = curl_exec($ch);

        curl_close($ch);

        $responseArray = json_decode($response, true);
        
        $token = $responseArray['ejes_content'][0]['token'];
        $expira = $responseArray['ejes_content'][0]['expires'];
        
        //Guardo el token        
        SQLConnection::backendStoreProcedure('prensa_getToken', ['insert_token', $token, $expira]);
        
        return $token;
    }

    public static function analisisPrensa()
    {
        $action = Request::input('action'); 
        $response = null;

        switch ($action) {
            case 'data':
                $data = SQLConnection::backendStoreProcedure('prensa_sentiment', ['datos_prensa',1,1]);

                if (empty($data)) {
                    return response()->json([
                        "status" => "error",
                        "code" => 404,
                        "message" => "data not found",
                        "data" => null,
                        "meta" => self::meta()
                    ], 404);
                }

                $response = [
                    "status" => "ok",
                    "code" => 200,
                    "message" => "OK",
                    "data" => $data,
                    "meta" => self::meta()
                ];
                break;

            case 'sentiment':
                $idNoticia = Request::input('id_noticia');
                $sentiment = Request::input('sentiment'); // P, N, NE   
                
                if (empty($idNoticia || $sentiment)) {
                    return response()->json([
                        "status" => "error",
                        "code" => 404,
                        "message" => "id_noticia or sentiment not found",
                        "data" => null,
                        "meta" => self::meta()
                    ], 404);
                }

                SQLConnection::backendStoreProcedure(
                    'prensa_sentiment',
                    ['update_prensa',1,1, $idNoticia, $sentiment]
                );

                $response = [
                    "status" => "ok",
                    "code" => 200,
                    "message" => "Sentiment updated",
                    "data" => null,
                    "meta" => self::meta()
                ];
                break;

            case 'mencionados':
                $idNoticia = Request::input('id_noticia');
                $nombre    = Request::input('nombre_persona');
                $dni       = Request::input('dni');
                $cuit      = Request::input('cuit');
                $tipo      = Request::input('tipo_persona'); 

                if ($tipo === 'empresa') {
                    $tipo = 'J';
                } elseif ($tipo === 'persona') {
                    $tipo = 'F';
                }else {
                    $tipo = null;
                }
                
                SQLConnection::backendStoreProcedure(
                    'prensa_mencionados',
                    [$idNoticia, $nombre, $dni, $cuit, $tipo]
                );

                $response = [
                    "status" => "ok",
                    "code" => 200,
                    "message" => "Mencionado insertado",
                    "data" => null,
                    "meta" => self::meta()
                ];
                break;

            default:
                return response()->json([
                    "status" => "error",
                    "code" => 400,
                    "message" => "Invalid action",
                    "data" => null,
                    "meta" => self::meta()
                ], 400);
        }

        return response()->json($response, $response['code']);
    }

    public static function meta(): array
    {
        return [
            "timestamp" => date('Y-m-d H:i:s'),
            "request_id" => uniqid(),
            "version" => "1.0"
        ];
    }
}
