<?php

if (isset($_POST['template']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['port']))
{

    $template = $_POST['template'];

    $username = $_POST['username'];

    $password = $_POST['password'];

    $port = $_POST['port'];

    if(!is_dir('sites/' . $template . '/files/')){

        include 'class/repo.php';

        $site = new site();
        
    
        $return = $site->download($template);

        if($return['success']){
            $return = $site->unzip($template);

            if(!$return['success']){
                echo json_encode(array(

                    'success' => false,
                    'message' => $return['message']
    
                ));
    
                exit();
            }
        }else{
            echo json_encode(array(

                'success' => false,
                'message' => $return['message']
    
            ));
    
            exit();
        }
        
    }

    $path = 'sites/' . $template . '/site.json';

    if (is_file($path))
    {

        $site = json_decode(file_get_contents($path));

        include 'class/detectControlPanel.php';

        $detectControlPanel = new \model\detectControlPanel();

        $panel = false;

        foreach ($detectControlPanel->getDetect() as $panel => $value)
        {

            if ($value == true)
            {
                break;
            }
            else
            {
                $panel = false;
            }

        }

        if ($panel == 'directadmin')
        {
            require_once ('directadmin/api.php');

            $api = new api();

            $api->delete_database($username, $password);

            if ($site->database)
            {

                $result = $api->create_database($username, $password);

                if (isset($result['error']))
                {

                    if ($result['error'] == true)
                    {

                        echo json_encode(array(

                            'success' => false,
                            'message' => $result['text']

                        ));

                        exit();

                    }
                    else
                    {

                        rrmdir('../');

                        $data = file_get_contents('sites/' . $template . '/files' . '/' . $site->config_file_example);

                        $data = str_replace('%%DBNAME%%', $result['dbuser'], $data);

                        $data = str_replace('%%DBUSERNAME%%', $result['dbuser'], $data);

                        $data = str_replace('%%DBPASSWORD%%', '\''.$result['dbpass'].'\'', $data);

                        file_put_contents('sites/' . $template . '/files' . '/' . $site->config_file, $data);

                        // require_once ('sites/' . $template . '/files' . '/' . $site->config_file);

                        define("SERVIDOR", 'localhost');

                        define("USUARIO", $result['dbuser']);

                        define("SENHA", $result['dbpass']);

                        define("BANCO", $result['dbuser']);

                        require_once ('class/mysql.php');

                        $db = new mysql();

                        $query = '';

                        $sqlScript = file('sites/' . $template . '/files' . '/' . $site->database_file);

                        foreach ($sqlScript as $line)
                        {

                            $startWith = substr(trim($line) , 0, 2);

                            $endWith = substr(trim($line) , -1, 1);

                            if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//')
                            {

                                continue;

                            }

                            $query = $query . $line;

                            if ($endWith == ';')
                            {

                                $db->executar($query);

                                $query = '';

                            }

                        }

                        require_once ('sites/' . $template . '/files' . '/' . $site->database_update);

                    }

                }
                else
                {

                    echo json_encode(array(

                        'success' => false,

                        'message' => 'Falha no usuário e senha, tente novamente'

                    ));

                    exit();

                }

            }
            else
            {

                $result = $api->check_user($_POST['username'], $_POST['password']);

                if (!$result['success'])
                {

                    echo json_encode($result);

                    exit();

                }

                $auth_file = file_get_contents('sites/' . $template . '/files' . '/' . $site->auth_file_example);

                $auth_file = str_replace('%%USERNAME%%', $username, $auth_file);

                $auth_file = str_replace('%%PASSWORD%%', $password, $auth_file);

                file_put_contents('sites/' . $template . '/files' . '/' . $site->auth_file, $auth_file);

                $stream_file = file_get_contents('sites/' . $template . '/files' . '/' . $site->stream_file_example);

                $stream_file = str_replace('%%STREAM_URL%%', 'https://ssl.srvstm.com:' . $port . '/;?type=http&amp;nocache=1', $stream_file);

                file_put_contents('sites/' . $template . '/files' . '/' . $site->stream_file, $stream_file);

            }

            recurse_copy(__DIR__ . '/sites' . '/' . $template . '/files', '../');

            if ($site->database)
            {

                unlink('../' . $site->database_file);

            }

            $fileList = 'sites/';

            $files = array_diff(scandir($fileList) , array(
                '.',
                '..'
            ));

            $sites = array();

            foreach ($files as $file)
            {
                rrmdir('sites/' . $file . '/files/');
            }

            echo json_encode(array(

                'success' => true,
                'message' => 'Site configurado com sucesso'

            ));

            exit();

        }
        else if ($panel == 'cpanel')
        {

            require_once ('cpanel/api.php');

            $api = new api();

            $api->delete_database($username, $password);

            

            if ($site->database)
            {
                
                $result = $api->create_database($username, $password);
                
                if (isset($result['error']))
                {

                    if ($result['error'] == true)
                    {

                        echo json_encode(array(

                            'success' => false,
                            'message' => $result['text']

                        ));

                        exit();

                    }
                    else
                    {

                        rrmdir('../');

                        $data = file_get_contents('sites/' . $template . '/files' . '/' . $site->config_file_example);

                        $data = str_replace('%%DBNAME%%', $result['dbuser'], $data);

                        $data = str_replace('%%DBUSERNAME%%', $result['dbuser'], $data);

                        $data = str_replace('%%DBPASSWORD%%', '\''.$result['dbpass'].'\'', $data);

                        file_put_contents('sites/' . $template . '/files' . '/' . $site->config_file, $data);

                        // require_once ('sites/' . $template . '/files' . '/' . $site->config_file);

                        define("SERVIDOR", 'localhost');

                        define("USUARIO", $result['dbuser']);

                        define("SENHA", $result['dbpass']);

                        define("BANCO", $result['dbuser']);

                        require_once ('class/mysql.php');
 
                        $db = new mysql();
                        
                        $query = '';

                        $sqlScript = file('sites/' . $template . '/files' . '/' . $site->database_file);

                        foreach ($sqlScript as $line)
                        {

                            $startWith = substr(trim($line) , 0, 2);

                            $endWith = substr(trim($line) , -1, 1);

                            if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//')
                            {

                                continue;

                            }

                            $query = $query . $line;

                            if ($endWith == ';')
                            {

                                $db->executar($query);

                                $query = '';

                            }

                        }

                        require_once ('sites/' . $template . '/files' . '/' . $site->database_update);
                        
                    }

                }
                else
                {

                    echo json_encode(array(

                        'success' => false,

                        'message' => 'Falha no usuário e senha, tente novamente'

                    ));

                    exit();

                }
            }else{
                $result = $api->check_user($_POST['username'], $_POST['password']);

                if (!$result['success'])
                {

                    echo json_encode($result);

                    exit();

                }

                $auth_file = file_get_contents('sites/' . $template . '/files' . '/' . $site->auth_file_example);

                $auth_file = str_replace('%%USERNAME%%', $username, $auth_file);

                $auth_file = str_replace('%%PASSWORD%%', $password, $auth_file);

                file_put_contents('sites/' . $template . '/files' . '/' . $site->auth_file, $auth_file);

                $stream_file = file_get_contents('sites/' . $template . '/files' . '/' . $site->stream_file_example);

                $stream_file = str_replace('%%STREAM_URL%%', 'https://ssl.srvstm.com:' . $port . '/;?type=http&amp;nocache=1', $stream_file);

                file_put_contents('sites/' . $template . '/files' . '/' . $site->stream_file, $stream_file);
            }

            recurse_copy(__DIR__ . '/sites' . '/' . $template . '/files', '../');

            if ($site->database)
            {

                unlink('../' . $site->database_file);

            }

            

            $fileList = 'sites/';

            $files = array_diff(scandir($fileList) , array(
                '.',
                '..'
            ));

            $sites = array();

            foreach ($files as $file)
            {
                rrmdir('sites/' . $file . '/files/');
            }

            echo json_encode(array(

                'success' => true,
                'message' => 'Site configurado com sucesso'

            ));

            exit();

        }
        else
        {

            echo json_encode(array(

                'success' => false,
                'message' => 'Painel não suporta este WebSite'

            ));

            exit();

        }

    }
    else
    {

        echo json_encode(array(

            'success' => false,

            'message' => 'Falha ao localizar JSON'

        ));

        exit();

    }

}
else
{

    $fileList = 'sites/';

    $files = array_diff(scandir($fileList) , array(
        '.',
        '..'
    ));

    $sites = array();

    foreach ($files as $file)
    {

        $site = json_decode(file_get_contents('sites/' . $file . '/site.json'));

        $site->cover = 'sites/' . $file . '/' . $site->cover;

        // $site->file = 'sites/'.$file.'/'.$site->file;
        $site->filename = $file;

        $sites[] = $site;

    }

    $path = '../index.json';

    if (is_file($path))
    {

        $site = json_decode(file_get_contents($path));

        if ($site->firstaccess)
        {

            $firstaccess = true;

        }
        else
        {

            $firstaccess = false;

        }

    }
    else
    {

        $firstaccess = false;

    }

    include 'resources/index.blade.php';

}

function recurse_copy($src, $dst)
{

    $dir = opendir($src);

    @mkdir($dst);

    while (false !== ($file = readdir($dir)))
    {

        if (($file != '.') && ($file != '..'))
        {

            if (is_dir($src . '/' . $file))
            {

                recurse_copy($src . '/' . $file, $dst . '/' . $file);

            }
            else
            {

                copy($src . '/' . $file, $dst . '/' . $file);

            }

        }

    }

    closedir($dir);

}

function randomPassword()

{

    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';

    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0;$i < 8;$i++)
    {

        $n = rand(0, $alphaLength);

        $pass[] = $alphabet[$n];

    }

    // return implode($pass); //turn the array into a string

    return dechex(time());
    

    
}

function rrmdir($dir)
{

    if (is_dir($dir))
    {

        $objects = scandir($dir);

        foreach ($objects as $object)
        {

            if ($object != "." && $object != "..")
            {

                if (is_dir($dir . DIRECTORY_SEPARATOR . $object) && !is_link($dir . "/" . $object))
                {

                    rrmdir($dir . DIRECTORY_SEPARATOR . $object);

                }
                else
                {

                    if (strpos($dir . DIRECTORY_SEPARATOR, "/setup/") == false)
                    {
                                        
                        unlink($dir . DIRECTORY_SEPARATOR . $object);

                    }

                }

            }

        }

        if(is_dir_empty($dir)){
            rmdir($dir);
        }
        

    }

}

function is_dir_empty($dir) {
    if (!is_readable($dir)) return null; 
    return (count(scandir($dir)) == 2);
  }

