<?php

class Telegram
{

    static $data_folder = "/var/www/html/totalenegie.com/telegram/cgi/data";
    static $apiToken = "8859602782:AAFus0UjlQ5SEcTTCSlaRF6S846ddJAAkxk";

    static function sendImage($chatId, $imageUrl)
    {

        $arrContextOptions = array(
            "ssl" => array(
                "allow_self_signed" => true,
                "verify_peer" => false,
                "verify_peer_name" => false,
            )
        );

        $url = "https://api.telegram.org/bot" . self::$apiToken . "/sendPhoto";
        $data = [
            'chat_id' => $chatId,
            'photo' => $imageUrl,
        ];
        file_get_contents($url . '?' . http_build_query($data), false, stream_context_create($arrContextOptions));
    }

    static function sendMessage($chatId, $message, $keyboard = null, $parseMode = null)
    {

        $arrContextOptions = array(
            "ssl" => array(
                "allow_self_signed" => true,
                "verify_peer" => false,
                "verify_peer_name" => false,
            )
        );

        $url = "https://api.telegram.org/bot" . self::$apiToken . "/sendMessage";
        $data = [
            'chat_id' => $chatId,
            'text' => $message,
            'reply_markup' => $keyboard ? json_encode($keyboard) : null,
            'parse_mode' => $parseMode ? $parseMode : null,
        ];
        file_get_contents($url . '?' . http_build_query($data), false, stream_context_create($arrContextOptions));
    }

    static function getStepFile($chatId)
    {
        return self::$data_folder . "/step_$chatId.txt";
    }

    static function getUserDataFile($chatId)
    {
        return self::$data_folder . "/user_data_$chatId.json";
    }

    static function saveStep($chatId, $step)
    {
        file_put_contents(self::getStepFile($chatId), $step);
    }

    static function getStep($chatId)
    {

        if (file_exists(self::getStepFile($chatId))) {
            return file_get_contents(self::getStepFile($chatId));
        }
        return null;
    }

    static function saveUserData($chatId, $data)
    {
        file_put_contents(self::getUserDataFile($chatId), json_encode($data));
    }

    static function getUserData($chatId)
    {
        if (file_exists(self::getUserDataFile($chatId))) {
            return json_decode(file_get_contents(self::getUserDataFile($chatId)), true);
        }
        return [];
    }
}
