<?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");

//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.class.php');


//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');

//Billname
require_once('../models/dao/BillnameDAO.class.php');
require_once('../models/dto/Billname.class.php');
require_once('../models/mysql/BillnameMySqlDAO.class.php');
require_once('../models/mysql/ext/BillnameMySqlExtDAO.class.php');

//Billsetting
require_once('../models/dao/BillsettingsDAO.class.php');
require_once('../models/dto/Billsetting.class.php');
require_once('../models/mysql/BillsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsettingsMySqlExtDAO.class.php');

//Faida
require_once('../models/dao/FaidaDAO.class.php');
require_once('../models/dto/Faida.class.php');
require_once('../models/mysql/FaidaMySqlDAO.class.php');
require_once('../models/mysql/ext/FaidaMySqlExtDAO.class.php');

//FaidaProduct
require_once('../models/dao/FaidaproductDAO.class.php');
require_once('../models/dto/Faidaproduct.class.php');
require_once('../models/mysql/FaidaproductMySqlDAO.class.php');
require_once('../models/mysql/ext/FaidaproductMySqlExtDAO.class.php');

//Sellbilldetail
require_once('../models/dao/SellbilldetailDAO.class.php');
require_once('../models/dto/Sellbilldetail.class.php');
require_once('../models/mysql/SellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailMySqlExtDAO.class.php');

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

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

  Controller Name :- productionExecutionAjaxController

  OPERTATION in Controller
  ======================== */

//here goes the instances and general variables

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

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();

//Billname
$myBillnameRecord = new BillnameMySqlDAO();
$myBillnameEx = new BillnameMySqlExtDAO();

//Billsetting
$myBillsettingEx = new BillsettingsMySqlExtDAO();

//Faida
$myFaida = new Faida();
$myFaidaDAO = new FaidaMySqlDAO();
$myFaidaEx = new FaidaMySqlExtDAO();

//Faida_product
$myFaidaProduct = new Faidaproduct();
$myFaidaProductDAO = new FaidaproductMySqlDAO();
$myFaidaProductEx = new FaidaproductMySqlExtDAO();


//Sellbilldetail
$mySellbilldetail = new Sellbilldetail();
$mySellbilldetailRecord = new SellbilldetailMySqlDAO();
$mySellbilldetailEx = new SellbilldetailMySqlExtDAO();


$today = date("Y-m-d");
$smarty->assign("today", $today);



if ($do == "getDataFaida") {

    $id = filter_input(INPUT_POST, 'id');
    $item = filter_input(INPUT_POST, 'item');
    $faidaData = $myFaidaEx->queryWithFaidaId($id);

//    var_dump($faidaData);
    echo json_encode($faidaData);

}

if ($do == "getDataFaidaProduct") {

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
    $smarty->assign("Programsettingdata", $Programsettingdata);

    $billnameData = $myBillnameRecord->load(3);
    $smarty->assign("billnameData", $billnameData);

    $billsettingsData = loadBillProperty(3);
    $smarty->assign("billsettingsData", $billsettingsData);

    $smarty->assign("billnameid", 3);
    $id = filter_input(INPUT_POST, 'id');
    $faidaProductData = $myFaidaProductEx->queryWithFaidaId($id);
    $faidatotal = 0;
    foreach ($faidaProductData as $item) {
        $faidatotal += $item->faidaproducttotalprice;
        $item->nametotal = $item->productName  .'/' . $item->productCatName;
    }

    $smarty->assign("faidaProductData", $faidaProductData);
    $smarty->assign("faidatotal", $faidatotal);

    $smarty->display("faidaview/auto.html");
}

if ($do == "showallajaxapproval") {
    showallajaxapproval();
}

if ($do == "showallajaxRefusal") {
    showallajaxRefusal();
}


// select from Billname tbl
function loadBillProperty($billnameid) {
    global $myBillsettingEx;

    // select all data from Billname
    $billsettingsData = $myBillsettingEx->queryWithBillnameId($billnameid);
    return $billsettingsData;
}

function showallajaxapproval() {
    global $myFaidaEx;
    global $ProgramsettingDAO;
    global $myFaidaProductDAO;
    $sIndexColumn = "id";

    /* DB table to use */
    //stable what is after from in sql statment
    ##this was right statment but slow
    $sTable = " faida
                LEFT JOIN client ON faida.client_id = client.clientid
                LEFT JOIN user ON faida.user_id = user.userid";


    $aColumns = array('faida.id','faida.client_id','faida.user_id','faida.conditions','client.clientname','user.username','faida.id as faida_id',);

    // Indexed column (used for fast and accurate table cardinality)

    /*
     * Paging
     */
    $sLimit = "";
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
        $sLimit = "LIMIT " . intval($_POST['start']) . ", " .
            intval($_POST['length']);
    }

    /*
     * Ordering
     */
    $sOrder = "";

    if (isset($_POST['order'][0])) {
        $sOrder = "ORDER BY  ";
        for ($i = 0; $i < intval($_POST['columns']); $i++) {
            $orderByColumnIndex = $_POST['order'][0]['column'] - 1; //this - 1 is because first column is not counted as it is checkbox
            $sOrder .= $aColumns[intval($_POST['columns'][$orderByColumnIndex]['data'])] . "
              " . ($_POST['order'][$i]['dir'] === 'asc' ? 'asc' : 'desc') . ", ";
        }
        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY ") {
            $sOrder = "";
        }
    }

    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    // where del =0 and aqarstatus =0 and updatestatus in(1,2,3,4) and complete=1
    $sWhere = '';
    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
        $sWhere = " where  (";
        for ($i = 0; $i < count($aColumns); $i++) {
            if ($aColumns[$i] == "sellbilldate") {
                //to get numbers and english chars only
                ##only alpha numeric is allowed . space not allowed
                $search = preg_replace('/[^#A-Za-z0-9]/', '', $_POST['search']['value']); // Removes special chars.
                if (!empty($search)) {
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $search . "%' OR ";
                }
            } else {
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_POST['search']['value'] . "%' OR ";
            }
        }
        $sWhere = substr_replace($sWhere, "", -3);
        $sWhere .= ")";
    }
    //-- search ------------------------------------------------------------
    if ($sWhere == '') {
        $queryString = ' WHERE faida.conditions = 1';
    } else {
        $queryString = ' AND';
    }


    $arr = explode(' ', $queryString);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {//remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
        if ($lastWord == 'WHERE') {//remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }

        //print("<br>queryString: ".$queryString."<br>");
    }

    $sWhere .= $queryString;
    //----------------------------------------------------------------------


    $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM  $sTable $sWhere $sOrder $sLimit ";
//    echo $sQuery;

    $rResult = $myFaidaEx->runSelectQuery($sQuery);

    /* Data set length after filtering */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as id  FROM  $sTable $sWhere "; //$sOrder
    $rResultFilterTotal = $myFaidaEx->runSelectQuery($sQuery);
    foreach ($rResultFilterTotal as $oneis) {
        $countis = $oneis->id;
    }
    $iFilteredTotal = $countis;
    /* Total data set length */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as id FROM  $sTable";
    $rResultTotal = $myFaidaEx->runSelectQuery($sQuery);


    foreach ($rResultTotal as $oneis) {
        $countit = $oneis->id;
    }
    //$aResultTotal = mysql_fetch_array($rResultTotal);
    $iTotal = $countit;

    $output = array(
        "draw" => intval(filter_input(INPUT_POST, 'sEcho')), //$_REQUEST['draw'], //intval(filter_input(INPUT_POST, 'sEcho')),
        "recordsTotal" => intval($iTotal),
        "recordsFiltered" => intval($iFilteredTotal),
        "totals" => array(),
        "data" => array()
    );
    $rowno = 1;
//    $sellQuantity = 0; //$piecesCount
//    $sellbilltotalpayed = 0; //payedTotal
//    $sellbillfinalbill = 0; //remainTotal
//    $sellbillaftertotalbill = 0; //totalBills//totalBills2
    foreach ($rResult as $aRow) {
//        var_dump($aRow->clientname);
        $row = array();
        for ($i = 0; $i < count($aColumns); $i++) {
            switch ($aColumns[$i]) {
                case "faida.id" :
                    $row[] = $aRow->id;
                    break;
                case "user.username" :
                    $row[] = $aRow->username;
                    break;
                case "client.clientname" :
                    $row[] = $aRow->clientname;
                    break;
                case "faida.id as faida_id" :
                    $row[] = '<a href="FaidaController.php?do=details&id='. $aRow->id . '" type="button"
                                                      class="btn btn-default btn-lg notesicon"></a>';
                    break;
                default :
                    break;
            }
        }



        $output['data'][] = $row;
        $rowno++;
    }
//    print_r($output);
    echo json_encode($output, JSON_UNESCAPED_SLASHES);
}

function showallajaxRefusal() {
    global $myFaidaEx;
    global $ProgramsettingDAO;
    global $myFaidaProductDAO;
    $sIndexColumn = "id";

    /* DB table to use */
    //stable what is after from in sql statment
    ##this was right statment but slow
    $sTable = " faida
                LEFT JOIN client ON faida.client_id = client.clientid
                LEFT JOIN user ON faida.user_id = user.userid";


    $aColumns = array('faida.id','faida.client_id','faida.user_id','faida.conditions','client.clientname','user.username','faida.id as faida_id',);

    // Indexed column (used for fast and accurate table cardinality)

    /*
     * Paging
     */
    $sLimit = "";
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
        $sLimit = "LIMIT " . intval($_POST['start']) . ", " .
            intval($_POST['length']);
    }

    /*
     * Ordering
     */
    $sOrder = "";

    if (isset($_POST['order'][0])) {
        $sOrder = "ORDER BY  ";
        for ($i = 0; $i < intval($_POST['columns']); $i++) {
            $orderByColumnIndex = $_POST['order'][0]['column'] - 1; //this - 1 is because first column is not counted as it is checkbox
            $sOrder .= $aColumns[intval($_POST['columns'][$orderByColumnIndex]['data'])] . "
              " . ($_POST['order'][$i]['dir'] === 'asc' ? 'asc' : 'desc') . ", ";
        }
        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY ") {
            $sOrder = "";
        }
    }

    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    // where del =0 and aqarstatus =0 and updatestatus in(1,2,3,4) and complete=1
    $sWhere = '';
    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
        $sWhere = " where  (";
        for ($i = 0; $i < count($aColumns); $i++) {
            if ($aColumns[$i] == "sellbilldate") {
                //to get numbers and english chars only
                ##only alpha numeric is allowed . space not allowed
                $search = preg_replace('/[^#A-Za-z0-9]/', '', $_POST['search']['value']); // Removes special chars.
                if (!empty($search)) {
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $search . "%' OR ";
                }
            } else {
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_POST['search']['value'] . "%' OR ";
            }
        }
        $sWhere = substr_replace($sWhere, "", -3);
        $sWhere .= ")";
    }
    //-- search ------------------------------------------------------------
    if ($sWhere == '') {
        $queryString = ' WHERE faida.conditions = 2';
    } else {
        $queryString = ' AND';
    }


    $arr = explode(' ', $queryString);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {//remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
        if ($lastWord == 'WHERE') {//remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }

        //print("<br>queryString: ".$queryString."<br>");
    }

    $sWhere .= $queryString;
    //----------------------------------------------------------------------


    $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM  $sTable $sWhere $sOrder $sLimit ";
//    echo $sQuery;

    $rResult = $myFaidaEx->runSelectQuery($sQuery);

    /* Data set length after filtering */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as id  FROM  $sTable $sWhere "; //$sOrder
    $rResultFilterTotal = $myFaidaEx->runSelectQuery($sQuery);
    foreach ($rResultFilterTotal as $oneis) {
        $countis = $oneis->id;
    }
    $iFilteredTotal = $countis;
    /* Total data set length */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as id FROM  $sTable";
    $rResultTotal = $myFaidaEx->runSelectQuery($sQuery);


    foreach ($rResultTotal as $oneis) {
        $countit = $oneis->id;
    }
    //$aResultTotal = mysql_fetch_array($rResultTotal);
    $iTotal = $countit;

    $output = array(
        "draw" => intval(filter_input(INPUT_POST, 'sEcho')), //$_REQUEST['draw'], //intval(filter_input(INPUT_POST, 'sEcho')),
        "recordsTotal" => intval($iTotal),
        "recordsFiltered" => intval($iFilteredTotal),
        "totals" => array(),
        "data" => array()
    );
    $rowno = 1;
//    $sellQuantity = 0; //$piecesCount
//    $sellbilltotalpayed = 0; //payedTotal
//    $sellbillfinalbill = 0; //remainTotal
//    $sellbillaftertotalbill = 0; //totalBills//totalBills2
    foreach ($rResult as $aRow) {
//        var_dump($aRow->clientname);
        $row = array();
        for ($i = 0; $i < count($aColumns); $i++) {
            switch ($aColumns[$i]) {
                case "faida.id" :
                    $row[] = $aRow->id;
                    break;
                case "user.username" :
                    $row[] = $aRow->username;
                    break;
                case "client.clientname" :
                    $row[] = $aRow->clientname;
                    break;
                case "faida.id as faida_id" :
                    $row[] = '<a href="FaidaController.php?do=details&id='. $aRow->id . '" type="button"
                                                      class="btn btn-default btn-lg notesicon"></a>';
                case "faida.id as faida_id" :
                    $row[] = '<a class="btn btn-info" href="#" data-id="'. $aRow->id . '" id="approval" data-toggle="modal"
                                       data-target="#myModal" role="button" >موافقه</a>';
                    break;
                default :
                    break;
            }
        }



        $output['data'][] = $row;
        $rowno++;
    }
//    print_r($output);
    echo json_encode($output, JSON_UNESCAPED_SLASHES);
}


?>