<?php

//the global file operation
session_start();
ob_start();
//global varable
global $showoutside;
//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");
//here the db files that include in the file
include("../public/include_dao.php");

include_once("dailyentryfun.php");
include_once("billsfunctions.php");

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

//Clientdebtchange
$myClientdebtchange = new Clientdebtchange();
$myClientdebtchangeRecord = new ClientdebtchangeMySqlDAO();
$myClientdebtchangeEx = new ClientdebtchangeMySqlExtDAO();

//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();

$kashf = new Kashf();
$kashfDAO = new KashfMySqlDAO();
$kashfDAOEx = new KashfMySqlExtDAO();

//doctorkashf
$doctorKashf = new Doctorkashf();
$doctorKashfDAO = new DoctorkashfMySqlDAO();
$doctorKashfEX = new DoctorkashfMySqlExtDAO();

//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();

$transactions = new Transaction();
##
if ($do == "syncclients") {

//Handling CORS requests properly
    $http_origin = $_SERVER['HTTP_ORIGIN'];
    header("Access-Control-Allow-Origin: $http_origin");
    header('Access-Control-Allow-Credentials: true');
    //        ini_set('session.cookie_domain', '.buvpgsr.com');
//        session_set_cookie_params(0, '/', '.buvpgsr.com');
//        session_set_cookie_params(time() + 3600, '/', '.buvpgsr.com');
//        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    // Access-Control headers are received during OPTIONS requests

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: POST");         //GET, POST, OPTIONS

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    $databaseName = filter_input(INPUT_POST, "databaseName");
    $_SESSION['dbname'] = $databaseName;

//header('Access-Control-Allow-Origin: *');
//http://stackoverflow.com/questions/22489426/unable-to-create-session-in-php-on-ajax-call
//
    #########################################
    try {

        $result = addNewClient('client_');
        echo json_encode($result);
    }
    #########################################
    catch (Exception $e) {
        $result['flag'] = -1;
        $result['note'] = 'خطأ أثناء الرفع  ';
        $result['noteen'] = 'error while uploading ...';
        $result['ex'] = $e;
        $result['clientid'] = '';
        echo json_encode($result);
    }
}

##
if ($do == "synckashf") {

//Handling CORS requests properly
    $http_origin = $_SERVER['HTTP_ORIGIN'];
    header("Access-Control-Allow-Origin: $http_origin");
    header('Access-Control-Allow-Credentials: true');

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: POST");         //GET, POST, OPTIONS

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    $databaseName = filter_input(INPUT_POST, "databaseName");
    $_SESSION['dbname'] = $databaseName;

    #########################################
    try {
        $clientId = filter_input(INPUT_POST, "kashf_customerid");
        if ($clientId < 0) {
            $result1 = addNewClient('client_');
            $clientId = $result1['clientid'];
        }
        $kashfId = saveKashfDetails($clientId, 1);

        $result['flag'] = 0;
        $result['note'] = '';
        $result['noteen'] = '';
        $result['kashid'] = $kashfId;


        echo json_encode($result);
    }
    #########################################
    catch (Exception $e) {
        $result['flag'] = -1;
        $result['note'] = 'خطأ أثناء الرفع  ';
        $result['noteen'] = 'error while uploading ...';
        $result['ex'] = $e;
        $result['kashid'] = '';
        echo json_encode($result);
    }
}

##
if ($do == "syncdockashf") {

//Handling CORS requests properly
    $http_origin = $_SERVER['HTTP_ORIGIN'];
    header("Access-Control-Allow-Origin: $http_origin");
    header('Access-Control-Allow-Credentials: true');

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: POST");         //GET, POST, OPTIONS

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    $databaseName = filter_input(INPUT_POST, "databaseName");
    $_SESSION['dbname'] = $databaseName;

    #########################################
    try {
        $clientId = filter_input(INPUT_POST, "doctorkashf_customerid");
        if ($clientId < 0) {
            $result1 = addNewClient('client_');
            $clientId = $result1['clientid'];
        }

        $kashfId = filter_input(INPUT_POST, "doctorkashf_kashfid");
        if ($kashfId > 0) {
            $kashfId = saveKashfDetails($clientId, 1);
        }

        $doctorId = filter_input(INPUT_POST, 'doctorkashf_doctorid');
        $docKashfId = saveDoctorlKashfDetails($clientId, 1, $kashfId, $doctorId);

        $result['flag'] = 0;
        $result['note'] = '';
        $result['noteen'] = '';
        $result['dockashid'] = $docKashfId;


        echo json_encode($result);
    }
    #########################################
    catch (Exception $e) {
        $result['flag'] = -1;
        $result['note'] = 'خطأ أثناء الرفع  ';
        $result['noteen'] = 'error while uploading ...';
        $result['ex'] = $e;
        $result['dockashid'] = '';
        echo json_encode($result);
    }
}

##
elseif ($do == "syncbills") {
//Handling CORS requests properly
    $http_origin = $_SERVER['HTTP_ORIGIN'];
    header("Access-Control-Allow-Origin: $http_origin");
    header('Access-Control-Allow-Credentials: true');
    //        ini_set('session.cookie_domain', '.buvpgsr.com');
//        session_set_cookie_params(0, '/', '.buvpgsr.com');
//        session_set_cookie_params(time() + 3600, '/', '.buvpgsr.com');
//        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    // Access-Control headers are received during OPTIONS requests




    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: POST");         //GET, POST, OPTIONS

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    $databaseName = filter_input(INPUT_POST, "databaseName");
    $_SESSION['dbname'] = $databaseName;

//header('Access-Control-Allow-Origin: *');
//http://stackoverflow.com/questions/22489426/unable-to-create-session-in-php-on-ajax-call
//
    #########################################
    try {
//         echo filter_input(INPUT_POST, "bill_rondomtxt");
//        echo '----';
//        echo filter_input(INPUT_POST, "bill_cash");
        $result = array();
        ### check rondom text exist
        $rondomTxt = filter_input(INPUT_POST, "bill_rondomtxt");
        $bills = $billsEX->queryByRondomText($rondomTxt);
        if (count($bills) > 0) {
            $result['flag'] = 1;
            $result['note'] = 'هذه الفاتورة رفعت من قبل ';
            $result['noteen'] = 'this bill uploaded before';
            $result['ex'] = '';
            $result['billId'] = '';
        } else {
            $resultAdd = add(1);
            if ($resultAdd[2]['flag'] == 0) {
                $result['flag'] = 2;
                $result['note'] = 'تم رفع الفاتورة ';
                $result['noteen'] = 'bill uploaded successfully ....';
                $result['ex'] = '';
                $result['billId'] = $resultAdd[1];
            } else {
                $result['flag'] = -1;
                $result['note'] = $resultAdd[2]['note'];
                $result['noteen'] = $resultAdd[2]['noteen'];
                $result['ex'] = '';
                $result['billId'] = '';
            }
        }
        $transactions->commit();
        echo json_encode($result);
    }
    #########################################
    catch (Exception $e) {
        $result['flag'] = -1;
        $result['note'] = 'خطأ أثناء الرفع  ';
        $result['noteen'] = 'error while uploading ...';
        $result['ex'] = $e;
        $result['billId'] = '';
        $transactions->rollback();
        echo json_encode($result);
    }
}

##
elseif ($do == "createupdatefile") {
//Handling CORS requests properly
    $http_origin = $_SERVER['HTTP_ORIGIN'];
    header("Access-Control-Allow-Origin: $http_origin");
    header('Access-Control-Allow-Credentials: true');

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: POST");         //GET, POST, OPTIONS

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    $databaseName = filter_input(INPUT_POST, "databaseName");
    $_SESSION['dbname'] = $databaseName;

    $dbhostc = ConnectionProperty::getHost();
    $dbuserc = ConnectionProperty::getUser();
    $dbpasswordc = ConnectionProperty::getPassword();
    $dbnamec = ConnectionProperty::getDatabase();


    prepareSqlFile($dbhostc, $dbuserc, $dbpasswordc, $dbnamec);
    #########################################
}

function prepareSqlFile($host, $user, $pass, $name) {
    $tables = array("client", 'kashf', 'doctorkashf');

    EXPORT_TABLES($host, $user, $pass, $name, $tables);
}

function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false) {
    $mysqli = new mysqli($host, $user, $pass, $name);
    mysql_set_charset("UTF8", $mysqli);

    $mysqli->select_db($name);

    //$mysqli->query("SET NAMES 'utf8'");
    $queryTables = $mysqli->query('SHOW TABLES');
    while ($row = $queryTables->fetch_row()) {
        $target_tables[] = $row[0];
    } if ($tables !== false) {
        $target_tables = array_intersect($target_tables, $tables);
    }

    foreach ($target_tables as $table) {
        $result = $mysqli->query('SELECT * FROM ' . $table);
        $fields_amount = $result->field_count;
        $rows_num = $mysqli->affected_rows;
        $res = $mysqli->query('SHOW CREATE TABLE ' . $table);
        $TableMLine = $res->fetch_row();

        //   $content = (!isset($content) ? '' : $content) . "\n\n DROP TABLE " . $table . " ;\n\n" . $TableMLine[1] . ";\n\n";
        $content = (!isset($content) ? '' : $content) . "\n\n";
        for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0) {
            while ($row = $result->fetch_row()) { //when started (and every after 100 command cycle):
                if ($st_counter % 100 == 0 || $st_counter == 0) {
                    $content .= "\nREPLACE INTO " . $table . " VALUES";
                }
                $content .= "\n(";
                for ($j = 0; $j < $fields_amount; $j++) {
                    $row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
                    if (isset($row[$j])) {
                        $content .= '"' . $row[$j] . '"';
                    } else {
                        $content .= '""';
                    } if ($j < ($fields_amount - 1)) {
                        $content .= ',';
                    }
                }
                $content .= ")";
                //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num) {
                    $content .= ";";
                } else {
                    $content .= ",";
                } $st_counter = $st_counter + 1;
            }
        }
        $content .= "\n\n\n";
        $content .= "#########delimiter########";
        $content .= "\n";
    }

    #######################################################################
    #############################   save file
    $handle = fopen('backup/tables_updates_ex.sql', 'w+');
    fwrite($handle, $content);
    fclose($handle);

    echo 111;

    #######################################################################
}

?>