<?php

//the global file operation
include("../public/impOpreation.php");
//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");



require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.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");

$storeExt = new StoreMySqlExtDAO();
/* ======================

  Controller Name :- runsqlfile

  ======================== */

//here the global templates
$smarty->display("header.html");
//here goes the instances and general variables
//check and use the condition that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

    //here the smarty templates
    $smarty->display("runsqlfileview/uploadfiles.html");
    $smarty->assign("runsqlfilescript", 1);
}

##
elseif ($do == "addfiles") {
    include_once("../public/authentication.php");

    try {
        run_sql_file();
        echo "sucess";
    } catch (Exception $e) {
        echo $e;
        // echo "error";
    }
}
##
elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
//here the global templates
$smarty->display("footer.html");

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

##for excel uploads

function run_sql_file() {

    global $storeExt;

    $commands = $_POST['sql'];

    //delete comments
    $lines = explode("\n", $commands);
    $commands = '';
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line && !strpos($line, '--')) {
            $commands .= $line . "\n";
        }
    }

    //convert to array
    $commands = explode(";", $commands);
    /* 	print_r("<pre>");
      print_r($commands);
      print_r("<pre>"); */
    //run commands
    $total = $success = 0;
    foreach ($commands as $command) {

        if (trim($command)) {
            $storeExt->run($command);
        }
    }

    //return number of successful queries and total number of queries found
    return array(
        "success" => $success,
        "total" => $total
    );
}

?>