<?php
    require_once($_SERVER['DOCUMENT_ROOT'] . '/rss/php/autoload.php');
    use App\Main;

    $classList = array(
        'Main' => Main::class,
    );

    session_start();

    if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/rss/php/conf.php')){
        require_once($_SERVER['DOCUMENT_ROOT'] . '/rss/php/conf.php');
    }
    
    if(isset($_POST['function']) && !empty($_POST['function']) && isset($_POST['target']) && !empty($_POST['target'])){
        $t_class = trim($_POST['target']);
        $t_func = trim($_POST['function']);
        if(array_key_exists($t_class, $classList) && class_exists($classList[$t_class])){
            if(method_exists($classList[$t_class], $t_func)){
                $_class = new $classList[$t_class];

                if(count($_POST) > 2){
                    foreach($_POST as $prop => $val){
                        if(property_exists($classList[$t_class], $prop)){
                            $_class->$prop = $val;
                        }
                    }
                }

                if(isset($_FILES) && !empty($_FILES)){
                    foreach($_FILES as $prop => $val){
                        if(property_exists($classList[$t_class], $prop)){
                            $_class->$prop = $val;
                        }
                    }
                }

                $response = $_class->$t_func();
                if($response){
                    $msg = $response;
                }else{
                    $msg = new stdClass();
                    $msg->status = 'fail';
                    $msg->message = $response;
                }
            }else{
                $msg = new stdClass();
                $msg->status = 'fail';
                $msg->message = 'Invalid function';
            }
        }else{
            $msg = new stdClass();
            $msg->status = 'fail';
            $msg->message = 'Invalid class';
        }
    }

    die(json_encode($msg));