<?php
/**
 * Get list of all of the instructions the repo has for patching.
 */

$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");

$response = array(
    'success' => false,
    'instructions' => array()
);

if ( !isset($_REQUEST) || empty($_REQUEST['version']) ) {
    die(json_encode($response));
}

$downloaded_repo_location = SITE_PATH."/../cms-patching/".$_REQUEST['version']."/";

$it = new RecursiveDirectoryIterator($downloaded_repo_location);
foreach(new RecursiveIteratorIterator($it) as $file) {
    if (strpos($file,'patching_tool_instruction_') !== false) {

        $instruction_json = file_get_contents($file->getPathname());

        if ( empty($instruction_json) ) {
            continue;
        }

        $instruction = CmsPatching::parsePatchingInstructionJson($instruction_json, $downloaded_repo_location, SITE_PATH."/");

        if ( empty($instruction) ) {
            continue;
        }

        $response['instructions'][] = array(
            'path' => $file->getPathname(),
            'file_instructions' => ( empty($instruction['file_instructions']) ? array() : $instruction['file_instructions'] ),
            'sql_instructions' => ( empty($instruction['sql_instructions']) ? array() : $instruction['sql_instructions'] ),
            'php_instructions' => ( empty($instruction['php_instructions']) ? array() : $instruction['php_instructions'] ),
            'description' => ( empty($instruction['description']) ? "" : $instruction['description'] ),
            'name' => ( empty($instruction['name']) ? $file->getFilename() : $instruction['name'] )
        );
    }
}

$response['success'] = true;

die(json_encode($response));