<?php
	if (isset($_POST) && isset($_POST['_r']) && isset($_POST['_a'])) {
		$action = $_POST['_a'];
		$res = [
            'success' => false,
            'message' => 'Cannot found action'
        ];
		
		function our_global_exception_handler($exception) {
			echo "Exception: " . $exception->getMessage();
		}
		set_exception_handler('our_global_exception_handler');
		
		function startInstalling() {
		    $access_token = $_POST['access_token'];
		    $package_path = $_POST['package_path'];
		    
		    if ($access_token == '') {
		        return [
                    'success' => false,
                    'message' => 'Access token is required'
                ];
            }
			if ($package_path == '') {
				return [
					'success' => false,
					'message' => 'Package path is required'
				];
			}
			if (!is_file($package_path) || !file_exists($package_path)) {
				return [
					'success' => false,
					'message' => 'Package path does not exist'
				];
            }
			
			if ($access_token != 'KiltzAnShtKrgaZDC1RJ6GeBp5gT8C') {
				return [
					'success' => false,
					'message' => 'Access token is invalid'
				];
            }
            $parent_path = dirname($package_path);
			if ($parent_path != dirname(__FILE__)) {
			    return [
                    'success' => false,
                    'message' => 'Package path is invalid'
                ];
            }
			
			$package_zip = new ZipArchive();
			if (!$package_zip->open($package_path)) {
				return [
                    'success' => false,
                    'message' => 'Cannot open package zip, please check again'
                ];
			}
			
			$url = "https://attechteam.com/api/coremigrate/core-migrate-installer.zip?time=".time();
			$zip_file = "installer.zip";
			$extract_path = dirname(__FILE__);
			$zip_resource = fopen($zip_file, "w");
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_FAILONERROR, true);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			curl_setopt($ch, CURLOPT_AUTOREFERER, true);
			curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
			curl_setopt($ch, CURLOPT_TIMEOUT, 10);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_FILE, $zip_resource);
			
			$page = curl_exec($ch);
			if (!$page) {
				return [
                    'success' => false,
                    'message' => "Error: " . curl_error($ch)
                ];
			}
			curl_close($ch);
			$zip = new ZipArchive;
			if (!$zip->open($zip_file) === true) {
                return [
                    'success' => false,
                    'message' => 'Error: Unable to open the zip file'
                ];
			}
            $zip->extractTo($extract_path);
            $zip->close();
            
            unlink($extract_path . "/installer.zip");
			
			$package_zip->extractTo($extract_path, array('coremigrate_context.json', 'backup.mysql'));
			$package_zip->close();
			
			$path_file_context = $extract_path . '/coremigrate_context.json';
			$path_file_backup = $extract_path . '/backup.mysql';
			if (!is_file($path_file_context)) {
			    return [
                    'success' => false,
                    'message' => 'Cannot found context file'
                ];
            }
			rename($path_file_context, $extract_path . '/core-migrate-installer/coremigrate_context.json');
            if (is_file($path_file_backup)) {
			    rename($path_file_backup, $extract_path . '/core-migrate-installer/backup.mysql');
            }
            return [
                'success' => true,
                'message' => 'The installation process was completed successfully',
                'data' => [
                    'extract_path' => $extract_path,
                    'package_path' => $package_path
                ]
            ];
        }
        
		if ($action == 'start_installing') {
		    $res = startInstalling();
        }
		
		die(json_encode($res));
	}
	$current_folder = dirname(__FILE__);
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Installer</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.css" integrity="sha512-3pIirOrwegjM6erE5gPSwkUzO+3cTjpnV9lexlNZqvupR64iZBnOOTiiLPb9M36zpMScbmUNIcHUqKD47M719g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        .main {
            margin-right: 400px;
        }

        .-img {
            position: absolute;
            top: 0;
            right: 0;
            width: 400px;
        }

        .container-md {
            position: relative;
        }
    </style>
</head>
<body>
	<div class="container-md">
		<div class='main'>
            <div class="header fs-3 mt-3 mb-3">
                AT Migrate Installer
            </div>
            <div class="content">
                <form>
                    <div class="mb-3">
                        <label for="access_token" class="form-label">Access token</label>
                        <input type="text" name='access_token' class="form-control" placeholder="Enter your access token" id="access_token" aria-describedby="emailHelp">
                        <div class="form-text">Enter the access token we gave you to be able to download the installer. If you do not have access token, please contact us.</div>
                    </div>
                    <div class="mb-3">
                        <label for="package_path" class="form-label">Package path</label>
                        <input type="text" value='<?php echo $current_folder; ?>' name='package_path' placeholder="Enter your Package path" class="form-control" id="package_path">
                    </div>
                    <button type="submit" class="btn btn-primary btn-start-install">Start install</button>
                </form>
            </div>
        </div>
        <div class='-img'>
            <img src="https://attechteam.com/images/install.svg">
        </div>
	</div>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
	<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" integrity="sha512-VEd+nq25CkR676O+pLBnDW09R7VQX9Mdiij052gVCp5yVH3jGtH70Ho/UUv4mJDsEdTvqRCFZg0NKGiojGnUCw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
		$(document).ready(function() {
			$(".btn-start-install").click(function(e) {
				e.preventDefault();
				var $that = $(this);
				loadingBtnInstall($that);
				$.ajax({
                    url: "./installer.php",
                    method: "POST",
                    data: {
                        _a: 'start_installing',
                        _r: 1,
	                    access_token: $("input[name='access_token']").val(),
	                    package_path: $("input[name='package_path']").val(),
                    },
					dataType: 'json',
					success: function(res) {
	                    loadingBtnInstall($that, false);
                        if (!res.success) {
                        	return toastr.error(res.message);
                        }
	                    toastr.success(res.message);
                        var data = res.data;
                        setTimeout(function() {
                            var current_path = window.location.href;
                            current_path = current_path.replace("installer.php", "core-migrate-installer/installer.php");
                            window.location.href = `${current_path}?extract_path=${data.extract_path}&package_path=${data.package_path}`;
                        }, 2000);
                    }
                });
			});
			
			function loadingBtnInstall(ref, loading = true) {
				if (loading) {
					return ref.html(`
						<span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
  						Installing...
					`).attr('disabled', true);
				}
				ref.html('Start install').removeAttr('disabled');
			}
		});
	</script>
</body>
</html>