<?php 
session_start();
error_reporting(E_ALL);
if(!isset($_SESSION['update_step']) || $_SESSION['update_step'] < 4) {
	header("location:./admin_details.php");
	exit();
}
include("db/connect.php");

function SplitSQL($file,$mysqli,$delimiter = ';') {
	$templine = "";
	$lines = file($file);
	foreach ($lines as $line) {
		if (substr($line, 0, 2) == '--' || $line == '') {
			continue;
		}
		$templine .= $line;
		if(substr(trim($line), -1, 1) == ';')	{		
			$mysqli->query($templine) or die($mysqli->error);
			$templine = '';
		}
	}
}

function create_json_files()
{
    $lib_path = dirname( dirname(__FILE__) )."/application/libraries/";         
    $files = scandir($lib_path);
    $ignore_files = array(".", "..", "index.html", "sources");
    foreach($files as $file)
    {
        if(in_array($file, $ignore_files)) continue;
        
        $file_name_parts = explode(".", $file);
        $json_path =  $lib_path . "/sources/".$file_name_parts[0].".json";
        if(file_exists($json_path) == FALSE)
        {
            $default_data = array("order" => "1", "icon" => ( strtolower($file_name_parts[0]) . ".png") , "status" => "1", "linkCacheTime" => "3600" );
            file_put_contents($json_path, json_encode($default_data));            
        }
    }
}

function update_keys_in_libs($mysqli)
{
    $rec = $mysqli->query("select * FROM `api-keys`");
    
    $row = $rec->fetch_assoc();
    
    if(!empty($row['facebookAppId']) && !empty($row["facebookAppSecret"]))
    {
        $fb_lib_path = "../application/libraries/sources/Facebook.json";
        if(file_exists($fb_lib_path))
        {
            $content = file_get_contents($fb_lib_path);
            $json    = json_decode($content, TRUE);
            $json['fb_app_id']      = $row["facebookAppId"];
            $json['fb_app_secret']  = $row["facebookAppSecret"];
               
            
            file_put_contents($fb_lib_path, json_encode($json));
        }        
    }
    
    if(!empty($row['soundcloud']))
    {
        $sc_lib_path = "../application/libraries/sources/Soundcloud.json";
        if(file_exists($sc_lib_path))
        {
            $content                 = file_get_contents($sc_lib_path);
            $json                   = json_decode($content, TRUE);
            $json['sc_api_key']     = $row["soundcloud"];
            
            file_put_contents($sc_lib_path, json_encode($json));
        }        
    }    
}


$rec = $mysqli->query("SELECT `version` FROM `general-settings`");
$row = $rec->fetch_assoc();
$version = $row['version'];

create_json_files();

$versions = array('1','1.1','1.2', '1.3');
$totalVersions = count($versions);
$currentVersion = array_search($version, $versions);
for($i = $currentVersion+1; $i < $totalVersions; $i++) 
{    
    if($versions[$i] == "1.3")
    {
        update_keys_in_libs($mysqli);
    }
    
    $sql_filename = "db/".$versions[$i].".sql";
    if(file_exists($sql_filename)) {
            SplitSQL($sql_filename,$mysqli);
    }
}


$_SESSION['version'] = $version;
$_SESSION['update_step'] = 5;

include("includes/head.php"); 
?>
<title>Database Quries</title>
<?php include("includes/header.php"); ?>
<?php include("includes/sidebar.php"); ?>
<div class="rightSide">
	<div class="col-xs-12">
		<div class="tab-content shadow-1">
			<div class="tab-pane active">
				<div class="alert alert-success alert-dismissable">
					<a class="close" data-dismiss="alert" aria-label="close">&times;</a>
					<strong>Success!</strong> Database quires executed successfully click below button to proceed.
				</div>
				<a href="./finish.php" class="btn btn-theme btn-lg">Continue!</a>
			</div>
		</div>
	</div>
</div>
<?php include("includes/footer.php"); ?>