<?php

//the global file operation
include("../public/impOpreation.php");
include_once("initiateStaticSessionCommingWithCurl.php");

//to check if the page from .htacess
// get the config file
include_once("../public/config.php");

$operatingSystem = 'linux'; //default not windows use linux mac
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    $operatingSystem = 'WIN';
}

//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");
//Breadcrumb
require_once("../library/breadcrumb.php");

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');


//get the do the action
$do = $_GET['do'];

$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");

/* ======================
  Controller Name :- saveCTRL اضافة وتعديل وعرض الخزن
  ======================== */


//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("header.html");
}


//here goes the instances and general variables
//Breadcrumb
$breadcrumbObject = new Breadcrumb();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();


//check and use the condetion that suite this action
if (empty($do)) {
    ##get connection data
    $pathToConnection = '../models/sql/ConnectionProperty.class.php'; //Absolute path
    $handle = fopen($pathToConnection, "r");
    if ($handle) {
        $dbUser = '';
        $dbPassword = '';
        $dbName = $_SESSION['dbname'];
        while (($line = fgets($handle)) !== false) {
            if (strpos($line, 'private static $user') !== false) {
                $dbUser = explode("'", $line)[1];
            } else if (strpos($line, 'private static $password') !== false) {
                $dbPassword = explode("'", $line)[1];
            }
        }
        fclose($handle);
    }
    $smarty->assign("dbUser", $dbUser);
    $smarty->assign("dbPassword", $dbPassword);
    $smarty->assign("dbName", $dbName);
    ##get versions
    $currentVersionDate = getCurrentVersion();
    $files = getVersions($currentVersionDate);


    $smarty->assign("files", $files);
    $smarty->assign("customVersion", 1);

    //here the smarty templates
    $smarty->display("versionView/wizard.html");
} elseif ($do == "restoreOldBackup") {
    $smarty->assign("customVersion", 1);
    //here the smarty templates
    $smarty->display("versionView/restoreOldBackup.html");
} elseif ($do == "sucess") {

    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {

    //here the smarty templates
    $smarty->display("error.html");
}
$smarty->assign("customSave", 1);
$smarty->assign("customValidation", 1);

//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("footer.html");
}

/* ===============================
  function in this CONTROLLER
  ================================ */

function getCurrentVersion() {
    $file = fopen("../views/default/footer.html", "r");
    while ($line = fgets($file)) {
        if (strpos($line, "<span>") !== false) {
            $versionData = trim(explode('</span>', explode('<span>', $line)[1])[0]);
            $dateParts = explode('.', str_replace('v', '', $versionData));
            $currentVersion = $dateParts[2] . '-' . $dateParts[1] . '-' . $dateParts[0];
            fclose($file);
            return $currentVersion;
        }
    }
}

function getVersions($givenDate = '') {
    ## 1 get file names
    $versionsDirPath = dirname(dirname(getcwd())) . '/_versions';
    $files = array();
    if (is_dir($versionsDirPath)) {
        $dirHandle = opendir($versionsDirPath);
        while (($file = readdir($dirHandle)) !== false) {
            if ($file != '.' && $file != '..') {
                if (pathinfo($file, PATHINFO_EXTENSION) == 'zip') {
                    $files[] = $file;
                }
            }
        }
        closedir($dirHandle);
    }

    ## 2 sort by date in the name
    $order = 'desc';
    usort($files, function($a, $b) use ($order) {
        $dateA = strtotime(explode('.', str_replace("erp", "", $a))[0]);
        $dateB = strtotime(explode('.', str_replace("erp", "", $b))[0]);
        if ($order == 'ASC') {
            return $dateA - $dateB;
        } else {
            return $dateB - $dateA;
        }
    });
    ## given date
    if ($givenDate != "") {
        $files = array_filter($files, function($a) use ($givenDate) {
            $date = strtotime(explode('.', str_replace("erp", "", $a))[0]);
            return $date > strtotime($givenDate);
        });
    }
    return $files;
}
