<?php
/**
 * @package   Jollyany Framework
 * @author    TemPlaza https://www.templaza.com
 * @copyright Copyright (C) 2011 - 2022 TemPlaza.
 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3 or Later
 */
define('_JOLLYANY', 1);
require_once 'functions.php';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$jollyany   =   $_REQUEST['jollyany'];

switch ($jollyany) {
    case 'download_package':
        $return = array();
        try {
            $license    =   maybe_unserialize(get_license());
            if ( is_object( $license ) && isset( $license->purchase_code ) ) {
                $install_code          =   $_REQUEST['install_code'];
                $step                  =   $_REQUEST['step'];
                $file_name             =   $_REQUEST['file_name'];

                $templates             =   get_data();
                if (is_array($templates) && isset($templates[$install_code])) {
                    $template          =   $templates[$install_code];
                }

                $tmp_part       =   JPATH_BASE ;
                $url            =   get_apiurl().'/index.php?option=com_tz_membership';
                //install quickstart package
                /* Get package zip file from server */
                ini_set('memory_limit', '-1');
                $data = array(
                    'task'          => 'download.package',
                    'produce'       => $install_code,
                    'purchase_code' => $license->purchase_code,
                    'domain'        => $_SERVER['HTTP_HOST'],
                    'step'          => $step,
                    'type'          => 'quickstart-api'
                );
                $response   =   HTTPPost($url, $data);

                if($response) {
                    $header     = $response -> headers;
                    if (isset($header['Files-Part-Count'])) {
                        $filePartCount  = $header['Files-Part-Count'];
                    } elseif (isset($header['files-part-count'])) {
                        $filePartCount  = $header['files-part-count'];
                    } else {
                        $filePartCount  = 0;
                    }
                    if (isset($header['Content-Disposition']) && $header['Content-Disposition']) {
                        $f_name =   preg_replace('/(^[^=]+=)|(;$)/', '', $header['Content-Disposition']);
                        if ( is_array($f_name) && isset($f_name[0]) ) {
                            $f_name =   $f_name[0];
                        } elseif ( !is_string($f_name) ) {
                            $f_name =   null;
                        }
                    } elseif (isset($header['content-disposition']) && $header['content-disposition']) {
                        $f_name =   preg_replace('/(^[^=]+=)|(;$)/', '', $header['content-disposition']);
                        if ( is_array($f_name) && isset($f_name[0]) ) {
                            $f_name =   $f_name[0];
                        } elseif ( !is_string($f_name) ) {
                            $f_name =   null;
                        }
                    } else {
                        $f_name = null;
                    }
                    if (!$f_name) throw new \Exception('Can not download package!');
                    $file_name  =   $file_name.'.'.getExt($f_name);
                    $filePartCount = is_array($filePartCount) && isset($filePartCount[0]) ? $filePartCount[0] : $filePartCount;
                    if($filePartCount && $step <= $filePartCount){
                        if (!file_exists($tmp_part.'/'.$file_name)) {
                            file_put_contents($tmp_part.'/'.$file_name, $response -> body);
                        } else {
                            file_put_contents($tmp_part.'/'.$file_name, $response -> body, FILE_APPEND);
                        }

                        $return["pathcount"]    =   $filePartCount;
                        if ($step == $filePartCount) {
                            $return['archive']  =   $tmp_part.'/'.$file_name;
                        }
                    } else {
                        throw new \Exception('Wrong file part count!');
                    }
                } else {
                    throw new \Exception('Can not connect to TemPlaza server!');
                }
                $return["status"] = "success";
                $return["code"] = 200;
            } else {
                throw new \Exception('Your license is invalid!');
            }
        } catch (\Exception $e) {
            $return["status"] = "error";
            $return["code"] = $e->getCode();
            $return["message"] = $e->getMessage();
        }
        echo \json_encode($return);
        die();
        break;
    case 'unzip_package':
        $return = array();
        try {
            $license    =   maybe_unserialize(get_license());
            if ( is_object( $license ) && isset( $license->purchase_code ) ) {
                $p_filename            =   $_REQUEST['archive'];
                //unzip quickstart package
                $zip = new ZipArchive;
                $res = $zip->open($p_filename);
                if ($res === TRUE) {
                    // Extract file
                    $zip->extractTo(JPATH_BASE);
                    $zip->close();
                } else {
                    throw new \Exception('Can not unzip package!');
                }
                $return["url_root"] = preg_replace('/jollyany_installation\/ajax\.php/i','', $_SERVER['SCRIPT_URI']);
                $return["status"] = "success";
                $return["code"] = 200;
            } else {
                throw new \Exception(\JText::_('JOLLYANY_AJAX_ERROR_NO_LICENSE'));
            }
        } catch (\Exception $e) {
            $return["status"] = "error";
            $return["code"] = $e->getCode();
            $return["message"] = $e->getMessage();
        }
        echo \json_encode($return);
        die();
        break;
}