<?php

namespace App\TelegramBot\Keyboard;

class Keyboard{

    private $keyboard;

    public function __construct(String $type="keyboard")
    {
        $this->type = $type;
        $this->keyboard = [];
    }

    public function addRow(Array $row){
        $this->keyboard[] = $row;
        return $this;
    }

    public function get($user){
        $keyboard_actions = [];

        if($user->keyboard_actions!="0"){
            $user_keyboard_actions = json_decode($user->keyboard_actions,true);
        }else{
            $user_keyboard_actions = [];
        }

        if($this->type=="keyboard"){
            foreach ($this->keyboard as $row){
                foreach ($row as $button) {
                    if(!empty($button['payload'])){
                        $keyboard_actions[$button['text']] = $button['payload'];
                    }
                }
            }
            $user_keyboard_actions['bottom'] = $keyboard_actions;
        }else{
            $user_keyboard_actions['inline'] = [];
            foreach ($this->keyboard as $row){
                foreach ($row as $button) {
                    if(!empty($button['payload'])){
                        $keyboard_actions[$button['callback_data']] = $button['payload'];
                    }
                }
            }
            $user_keyboard_actions['inline'] = $keyboard_actions;
        }

        $user->keyboard_actions = json_encode($user_keyboard_actions,JSON_UNESCAPED_UNICODE);
        $user->save();
        return $this->keyboard;
    }

}
