<?php
namespace App\Controllers;

use App\Services\TelegramBot;
use App\Middleware\RoleMiddleware;
use App\Helpers\Response;

class TelegramController
{
    private $bot;
    
    public function __construct()
    {
        $this->bot = new TelegramBot();
    }
    
    public function index()
    {
        RoleMiddleware::admin();
        
        $info = $this->bot->getWebhookInfo();
        $params = [
            'info' => $info['result'] ?? null,
            'defaultUrl' => siteUrl('telegram/webhook.php')
        ];
        
        // Renderizar vista (simulado devolviendo datos, la vista la incluirá)
        return $params;
    }
    
    public function setup()
    {
        RoleMiddleware::admin();
        
        if (isPost()) {
            if (!verifyCsrfToken(post('csrf_token'))) {
                flash('error', 'Token inválido');
                redirect(siteUrl('admin/telegram.php'));
            }
            
            $url = post('webhook_url');
            
            if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
                flash('error', 'URL inválida');
                redirect(siteUrl('admin/telegram.php'));
            }
            
            $response = $this->bot->setWebhook($url);
            $res = json_decode($response, true);
            
            if ($res && $res['ok']) {
                flash('success', 'Webhook configurado correctamente');
            } else {
                flash('error', 'Error al configurar: ' . ($res['description'] ?? 'Desconocido'));
            }
            
            redirect(siteUrl('admin/telegram.php'));
        }
    }
    
    public function delete()
    {
        RoleMiddleware::admin();
        
        if (isPost()) {
            if (!verifyCsrfToken(post('csrf_token'))) {
                flash('error', 'Token inválido');
                redirect(siteUrl('admin/telegram.php'));
            }
            
            $response = $this->bot->deleteWebhook();
            $res = json_decode($response, true);
            
            if ($res && $res['ok']) {
                flash('success', 'Webhook eliminado correctamente');
            } else {
                flash('error', 'Error al eliminar: ' . ($res['description'] ?? 'Desconocido'));
            }
            
            redirect(siteUrl('admin/telegram.php'));
        }
    }
}
