<?php

new class {

    protected $post;
    protected $message = [];

    public function __construct() {

        if( $_SERVER['REQUEST_METHOD'] != 'POST' ) return;

        $this->post = $_POST;

        array_walk_recursive($this->post, function(&$value) {
            $value = Uss::$global['mysqli']->real_escape_string(trim($value));
        });

        $this->post['detail']['title'] = array_map(function($value) {
            $value = strtolower($value);
            $value = str_replace(" ", "_", $value);
            return $value;
        }, $this->post['detail']['title']);

        $this->post['detail'] = array_combine( $this->post['detail']['title'], $this->post['detail']['value'] );
        $this->post['detail'] = json_encode( $this->post['detail'] );

        $this->getFile();

        $this->setGateway();

    }

    public function getFile() {

        $file = $_FILES['icon'];
        if( $file['error'] ) return;

        try {
            $link = Udash::uploadFile( "image/jpeg|png|gif|webp|jpg", $file, GATEWAY_DIR . "/images" );
            $this->post['icon'] = $link;
        } catch(Exception $e) {
            $this->message[] = "File was not uploaded";
        };

    }

    public function setGateway() {

        if( empty($this->post['id']) ) {

            unset( $this->post['id'] );

            $SQL = SQuery::insert( DB_TABLE_PREFIX . "_payment_methods", $this->post );
            $status = Uss::$global['mysqli']->query( $SQL );
            $req = "added";

        } else {

            $SQL = SQuery::update( DB_TABLE_PREFIX . "_payment_methods", $this->post, "id = '{$this->post['id']}'" );
            $status = Uss::$global['mysqli']->query( $SQL );
            $req = "updated";
            
        };

        if( $status ) {
            $type = 'success';
            $this->message[] = "The payment gateway has been {$req}";
        } else {
            $type = 'error';
            $this->message[] = "The payment gateway was not {$req}";
        };

        Bank::log( $type, implode("<br/>", $this->message) );

    }

};