<?php

namespace App\Modules\Notification\Controllers;

use App\Core\BaseApiController;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Telegram Webhook Controller
 * 
 * Handles incoming webhook requests from Telegram.
 */
class TelegramWebhookController extends BaseApiController
{
    /**
     * Handle Telegram webhook
     * 
     * POST /api/telegram/webhook
     * 
     * For now, just parse updates and log into writable/logs
     * 
     * @return ResponseInterface
     */
    public function index(): ResponseInterface
    {
        // Get JSON input from Telegram
        $input = $this->request->getJSON(true);

        // Log the webhook data
        $logData = [
            'timestamp' => date('Y-m-d H:i:s'),
            'update_id' => $input['update_id'] ?? null,
            'message'   => $input['message'] ?? null,
            'callback_query' => $input['callback_query'] ?? null,
            'raw_data'  => $input,
        ];

        // Write to log file
        $logFile = WRITEPATH . 'logs/telegram_webhook_' . date('Y-m-d') . '.log';
        $logMessage = date('Y-m-d H:i:s') . ' - ' . json_encode($logData, JSON_PRETTY_PRINT) . PHP_EOL . PHP_EOL;
        
        file_put_contents($logFile, $logMessage, FILE_APPEND);

        // Parse update
        $update = $this->parseUpdate($input);

        // For now, just return success
        // In the future, this will process commands and messages
        return $this->successResponse(
            [
                'update_id' => $update['update_id'] ?? null,
                'type'      => $update['type'] ?? 'unknown',
                'processed' => true,
            ],
            'Webhook received and logged'
        );
    }

    /**
     * Parse Telegram update
     * 
     * @param array $input Raw webhook data
     * @return array Parsed update data
     */
    protected function parseUpdate(array $input): array
    {
        $update = [
            'update_id' => $input['update_id'] ?? null,
            'type'      => 'unknown',
        ];

        // Check for message
        if (isset($input['message'])) {
            $update['type'] = 'message';
            $update['message'] = [
                'message_id' => $input['message']['message_id'] ?? null,
                'from'       => $input['message']['from'] ?? null,
                'chat'       => $input['message']['chat'] ?? null,
                'date'       => $input['message']['date'] ?? null,
                'text'       => $input['message']['text'] ?? null,
            ];
        }

        // Check for callback query
        if (isset($input['callback_query'])) {
            $update['type'] = 'callback_query';
            $update['callback_query'] = [
                'id'      => $input['callback_query']['id'] ?? null,
                'from'    => $input['callback_query']['from'] ?? null,
                'message' => $input['callback_query']['message'] ?? null,
                'data'    => $input['callback_query']['data'] ?? null,
            ];
        }

        // Check for edited message
        if (isset($input['edited_message'])) {
            $update['type'] = 'edited_message';
            $update['edited_message'] = $input['edited_message'];
        }

        return $update;
    }
}
