<?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("../library/num_to_ar.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');

//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');

//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');

///Offerpricebill
require_once('../models/dao/OfferpricebillDAO.class.php');
require_once('../models/dto/Offerpricebill.class.php');
require_once('../models/mysql/OfferpricebillMySqlDAO.class.php');
require_once('../models/mysql/ext/OfferpricebillMySqlExtDAO.class.php');

//Offerpricebillprop
require_once('../models/dao/OfferpricebillpropDAO.class.php');
require_once('../models/dto/Offerpricebillprop.class.php');
require_once('../models/mysql/OfferpricebillpropMySqlDAO.class.php');
require_once('../models/mysql/ext/OfferpricebillpropMySqlExtDAO.class.php');



//Offerpricecondition
require_once('../models/dao/OfferpriceconditionDAO.class.php');
require_once('../models/dto/Offerpricecondition.class.php');
require_once('../models/mysql/OfferpriceconditionMySqlDAO.class.php');
require_once('../models/mysql/ext/OfferpriceconditionMySqlExtDAO.class.php');
//
require_once('../models/dao/SizecolorstoredetailDAO.class.php');
require_once('../models/dto/Sizecolorstoredetail.class.php');
require_once('../models/mysql/SizecolorstoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SizecolorstoredetailMySqlExtDAO.class.php');

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

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

  Controller Name :- productController

  OPERTATION in Controller

  1- display add form, add supplier cat and supplier with ajax
  2- add in supplier tbl
  2.1- insert into supplier unit tbl
  2.2- insert into storedetail tbl
  2.3- insert new row into storereport tbl
  3- display show and tempdelete
  4- edit supplier
  5- update supplier
  5.1- update supplier tbl with supplierid
  5.2- delete supplier units associated to this supplier from productunit tbl, then insert it again

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

//here goes the instances and general variables

$Client = new Client();
$ClientDAO = new ClientMySqlDAO();
$ClientEx = new ClientMySqlExtDAO();

//Product
$myProductRecord = new ProductMySqlDAO();
$productExt = $myProductEx = new ProductMySqlExtDAO();

//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();

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

$Offerpricebill = new Offerpricebill();
$OfferpricebillDAO = new OfferpricebillMySqlDAO();
$OfferpricebillEx = new OfferpricebillMySqlExtDAO();

//Offerpricebillprop
$Offerpricebillprop = new Offerpricebillprop();
$OfferpricebillpropDAO = new OfferpricebillpropMySqlDAO();
$OfferpricebillpropEx = new OfferpricebillpropMySqlExtDAO();

//Offerpricecondition
$Offerpricecondition = new Offerpricecondition();
$OfferpriceconditionDAO = new OfferpriceconditionMySqlDAO();
$OfferpriceconditionEx = new OfferpriceconditionMySqlExtDAO();

//Productcat
$myProductcatEx = new ProductcatMySqlExtDAO();


//check and use the condition that suite this action
if (empty($do)) {
} elseif ($do == "writtenmoney") {
    $price = filter_input(INPUT_POST, "price");
    $ar_number = '';
    try {
        $ar_number = new convert_ar($price, "male");
        $arabic_num = $ar_number->convert_number();
        $Programsettingdata = $ProgramsettingDAO->load(1);
        $arabic_num .= ' ' . $Programsettingdata->currancy . ' فقط لاغير';
    } catch (Exception $ex) {
        $arabic_num .= ' عفوا العدد خارج النطاق ';
    }

    echo $arabic_num;
}

/* ========sellprice ==================== */ elseif ($do == "getproductsellprice") {

    $productid = $_GET['productid'];
    $proofferData = $productExt->loadEX($productid);
    echo json_encode($proofferData);
}

/* =================clients=========== */ elseif ($do == "getclients") {

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);

    $row_array = array();
    $return_arr = array();

    $allclient = $ClientEx->getClientsforoffer($name);

    foreach ($allclient as $client) {
        $row_array['id'] = $client->value;
        $row_array['text'] = $client->label;

        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
} elseif ($do == 'saveandprint') {
    $offerpricebillid = add();
    printbill($offerpricebillid);
    $smarty->display("priceoffersview/print.html");
} elseif ($do == 'updateandprint') {
    $offerpricebillid = update();
    printbill($offerpricebillid);
    $smarty->display("priceoffersview/print.html");
} elseif ($do == "loadProductByParcode") {
    $parcode = $_GET['parcode'];
    loadProductByParcode($parcode);
} elseif ($do == "getLastOffers") {
    $lastOffers = R::getAll('SELECT * from offerpricebillprop order by id desc limit 10');
    $productsArr = [];
    foreach($lastOffers as $offer)
    {
        $productsArr[$offer['id']] = R::getAll('select * from offerpricebill where offerpricebillid = '.$offer['id']);
    }
    $smarty->assign('lastOffers', $lastOffers);
    $smarty->assign('productsArr', $productsArr);
    $smarty->display('sellbillview/latestoffers.html');
}
/* ===============================
  function in this CONTROLLER
  ================================ */

function add()
{
    global $Offerpricebillprop;
    global $OfferpricebillpropDAO;
    global $Offerpricebill;
    global $OfferpricebillDAO;
    global $Offerpricecondition;
    global $OfferpriceconditionDAO;
    global $OfferpriceconditionEx;
    ///var
    $newclientname = filter_input(INPUT_POST, 'newclientname', FILTER_DEFAULT);
    $oldclientname = filter_input(INPUT_POST, 'oldclientname', FILTER_DEFAULT);
    $clienttype = filter_input(INPUT_POST, 'clienttype', FILTER_DEFAULT);
    $generalcondition = filter_input(INPUT_POST, 'generalcondition', FILTER_DEFAULT);
    $introductioncondition = filter_input(INPUT_POST, 'introductioncondition', FILTER_DEFAULT);

    $offerhidden_itr = filter_input(INPUT_POST, 'offerhidden_itr', FILTER_DEFAULT);
    $totalsellbillprice = filter_input(INPUT_POST, 'offer_sellbillpricenew', FILTER_DEFAULT);
    $realtotalprice = filter_input(INPUT_POST, 'offer_sellbillpricenew', FILTER_DEFAULT);
    #####serialno
    $serialno = getserails();
    ###############insert totla price and clientname
    if ($clienttype == 0) {
        $clientname = R::getCell('select clientname from client where clientid = ' . $oldclientname);
        $Offerpricebillprop->clientid = $oldclientname;
        $Offerpricebillprop->clientname = $clientname;
    } else {
        $Offerpricebillprop->clientid = 0;
        $Offerpricebillprop->clientname = $newclientname;
    }

    $Offerpricebillprop->offerpricebillid = $offerpricebillid;
    $Offerpricebillprop->totalprice = $totalsellbillprice;
    $Offerpricebillprop->realtotalprice = $realtotalprice;
    $Offerpricebillprop->serialno = $serialno;
    $Offerpricebillprop->sysdate = date("Y-m-d");


    $offerpricebillid = $OfferpricebillpropDAO->insert($Offerpricebillprop);

    for ($i = 1; $i <= $offerhidden_itr; $i++) {

        $productid = filter_input(INPUT_POST, 'offerproudctid' . $i);
        $offerproudctname = filter_input(INPUT_POST, 'offerproudctname' . $i);
        $offerproprice = filter_input(INPUT_POST, 'offerproprice' . $i);
        $prodescrp = filter_input(INPUT_POST, 'prodescrp' . $i);
        $offerpronumber = filter_input(INPUT_POST, 'offerpronumber' . $i);
        $offertotal = filter_input(INPUT_POST, 'div_pr_offertotal' . $i);


        if (empty($productid) && empty($offerproudctname)) {

            continue;
        }

        ################product
        if (empty($productid) && !empty($offerproudctname)) {
            $Offerpricebill->productid = 0;
            $Offerpricebill->productname = $offerproudctname;
        } else {
            $Offerpricebill->productid = $productid;
            $Offerpricebill->productname = '';
        }
        ####Offerprice bill
        $Offerpricebill->offerpricebillid = $offerpricebillid;
        $Offerpricebill->prodescrption = $prodescrp;
        $Offerpricebill->sellprice = $offerproprice;
        $Offerpricebill->pronumber = $offerpronumber;
        $Offerpricebill->totalprice = $offertotal;

        $OfferpricebillDAO->insert($Offerpricebill);
    }


    #######condition
    $allconditions = $OfferpriceconditionDAO->queryAll();
    if (count($allconditions) == 0) {
        $Offerpricecondition->introduction = $introductioncondition;
        $Offerpricecondition->detail = $generalcondition;
        $OfferpriceconditionDAO->insert($Offerpricecondition);
    } else {
        $lastcondition = $OfferpriceconditionEx->getlastid();
        $lastconditionid = $lastcondition->id;

        $Offerpricecondition->id = $lastconditionid;
        $Offerpricecondition->introduction = $introductioncondition;
        $Offerpricecondition->detail = $generalcondition;
        $OfferpriceconditionDAO->update($Offerpricecondition);
    }


    return $offerpricebillid;
}

function update()
{
    global $Offerpricebillprop;
    global $OfferpricebillpropDAO;
    global $Offerpricebill;
    global $OfferpricebillDAO;
    global $Offerpricecondition;
    global $OfferpriceconditionDAO;
    ///var
    $newclientname = filter_input(INPUT_POST, 'newclientname', FILTER_DEFAULT);
    $oldclientname = filter_input(INPUT_POST, 'oldclientname', FILTER_DEFAULT);
    $clienttype = filter_input(INPUT_POST, 'clienttype', FILTER_DEFAULT);
    $editid = filter_input(INPUT_POST, 'editid', FILTER_DEFAULT);
    $generalcondition = filter_input(INPUT_POST, 'generalcondition', FILTER_DEFAULT);
    $generalconditionId = filter_input(INPUT_POST, 'generalconditionId', FILTER_DEFAULT);
    $introductioncondition = filter_input(INPUT_POST, 'introductioncondition', FILTER_DEFAULT);

    $offerhidden_itr = filter_input(INPUT_POST, 'offerhidden_itr', FILTER_DEFAULT);
    $totalsellbillprice = filter_input(INPUT_POST, 'offer_sellbillpricenew', FILTER_DEFAULT);

    $serialno = filter_input(INPUT_POST, 'serialno', FILTER_DEFAULT);
    $billdate = filter_input(INPUT_POST, 'billdate', FILTER_DEFAULT);
    $realtotalprice = filter_input(INPUT_POST, 'offer_sellbillpricenew', FILTER_DEFAULT);



    ###############insert totla price and clientname
    if ($clienttype == 0) {
        $Offerpricebillprop->clientid = $oldclientname;
        $Offerpricebillprop->clientname = '';
    } else {
        $Offerpricebillprop->clientid = 0;
        $Offerpricebillprop->clientname = $newclientname;
    }
    $Offerpricebillprop->id = $editid;
    $Offerpricebillprop->offerpricebillid = $offerpricebillid;
    $Offerpricebillprop->totalprice = $totalsellbillprice;
    $Offerpricebillprop->realtotalprice = $realtotalprice;
    $Offerpricebillprop->serialno = $serialno;
    $Offerpricebillprop->sysdate = $billdate;

    $updateid = $OfferpricebillpropDAO->update($Offerpricebillprop);
    #####delete all products in this bill
    $OfferpricebillDAO->deleteByOfferpricebillid($editid);

    ####insert new products
    for ($i = 1; $i <= $offerhidden_itr; $i++) {

        $productid = filter_input(INPUT_POST, 'offerproudctid' . $i);
        $offerproudctname = filter_input(INPUT_POST, 'offerproudctname' . $i);
        $offerproprice = filter_input(INPUT_POST, 'offerproprice' . $i);
        $prodescrp = filter_input(INPUT_POST, 'prodescrp' . $i);
        $offerpronumber = filter_input(INPUT_POST, 'offerpronumber' . $i);
        $offertotal = filter_input(INPUT_POST, 'div_pr_offertotal' . $i);


        if (empty($productid) && empty($offerproudctname)) {

            continue;
        }

        ################product
        if (empty($productid) && !empty($offerproudctname)) {
            $Offerpricebill->productid = 0;
            $Offerpricebill->productname = $offerproudctname;
        } else {
            $Offerpricebill->productid = $productid;
            $Offerpricebill->productname = '';
        }
        ####Offerprice bill
        $Offerpricebill->offerpricebillid = $editid;
        $Offerpricebill->prodescrption = $prodescrp;
        $Offerpricebill->sellprice = $offerproprice;
        $Offerpricebill->pronumber = $offerpronumber;
        $Offerpricebill->totalprice = $offertotal;


        ##### insert
        $OfferpricebillDAO->insert($Offerpricebill);
    }


    ######condition
    $Offerpricecondition->id = $generalconditionId;
    $Offerpricecondition->introduction = $introductioncondition;
    $Offerpricecondition->detail = $generalcondition;
    $OfferpriceconditionDAO->update($Offerpricecondition);

    return $editid;
}

function printbill($id)
{
    global $Offerpricebillprop;
    global $OfferpricebillpropDAO;
    global $Offerpricebill;
    global $OfferpricebillDAO;
    global $Offerpricecondition;
    global $OfferpriceconditionDAO;
    global $OfferpriceconditionEx;
    global $ClientDAO;
    global $myProductRecord;
    global $ProgramsettingDAO;
    global $smarty;


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

    $conditionData = $OfferpriceconditionEx->getlastid();
    $smarty->assign('conditionData', $conditionData);

    $offerpriceData = $OfferpricebillpropDAO->load($id);
    $smarty->assign('offerpriceData', $offerpriceData);


    $totalpricestring = $offerpriceData->totalprice;
    $arabic_num = '';
    try {
        $ar_number = new convert_ar($totalpricestring, "male");
        $arabic_num = $ar_number->convert_number();
        $arabic_num .= ' ' . $Programsettingdata->currancy . ' فقط لاغير';
    } catch (Exception $ex) {
        $arabic_num .= ' عفوا العدد خارج النطاق ';
    }

    $smarty->assign('arabic_num', $arabic_num);


    $clientname = "";
    if ($offerpriceData->clientid > 0) {
        $clientData = $ClientDAO->load($offerpriceData->clientid);
        $clientname = $clientData->clientname;
    } else {
        $clientname = $offerpriceData->clientname;
    }
    $smarty->assign('clientname', $clientname);


    #####billproductprop
    ###all products in bill
    $allproductdata = $OfferpricebillDAO->queryByOfferpricebillid($id);
    foreach ($allproductdata as $data) {

        if ($data->productid > 0) {
            $productData = $myProductRecord->load($data->productid);
            $productName = $productData->productName;
            $data->productName = $productName;
        } else {
            $data->productName = $data->productname;
        }
    }

    $smarty->assign('allproductdata', $allproductdata);
}

/* =========================serial ============================== */

function getserails()
{
    global $OfferpricebillpropEx;

    function generateRandomString($length = 4)
    {
        $newnum = substr(str_shuffle("0123456789"), 0, $length);
        return date("Y") . '' . $newnum;
    }

    $number = generateRandomString();

    //to make sure there are no duplicate serails

    $checkifthere = $OfferpricebillpropEx->queryAllbyserialno($number);
    if (count($checkifthere) > 0) {
        $number = generateRandomString();
    }

    return $number;
}

function loadProductByParcode($parcode)
{
    global $myProductEx;
    global $sizeColorStoreDetailEX;
    global $ProgramsettingDAO;

    $Programsettingdata = $ProgramsettingDAO->load(1);

    ##check if parcode scale is used
    $WeightPricePart;
    $posType;
    $useParcodeBalance = 0;
    //
    $arr = array();
    $categories;
    // select all data from product tbl
    if ($parcode[0] == 'i' && $Programsettingdata->usedParcode == 1) { //usedParcode == 1 it is id coming after i) {) {
        $productData = array();
    } else {
        $productData = $myProductEx->queryWithSerialnumberAndAvailable($parcode);
    }

    if (count($productData) <= 0) {
        if ($parcode[0] == 'i' && $Programsettingdata->usedParcode == 1) { //usedParcode == 1 it is id coming after i) {
            $parcode = str_replace("i", "", $parcode);
            $productData = $myProductEx->loadProduct((int) $parcode);
        } else {
            $productData = $myProductEx->queryWithParcode($parcode);
        }
        if (count($productData) <= 0) {
            //so check if it is producthassizecolor
            $sizeColor = $sizeColorStoreDetailEX->queryByParcodeEX($parcode);
            $arr['id'] = "hasSizeColor" . $sizeColor->productid . "-" . $sizeColor->sizeid . "-" . $sizeColor->colorid;
            $arr['text'] = $sizeColor->productName . "/" . $sizeColor->productCatName . "/" . $sizeColor->sizeName . "/" . $sizeColor->colorName;
        } else {
            if ($productData->hasSizeAndColor == 0) {
                $arr['id'] = $productData->productId;
                //names of product's parents
                $parentId = $productData->productCatId;
                $pathArr = fetch_recursive($parentId, $categories);
                //
                $arr['text'] = $productData->productName . '/' . $pathArr;
            } else {
                //means no data
                $arr['id'] = 0;
                $arr['text'] = '';
            }
        }
    } else {
        $arr['id'] = $productData->productId;
        //names of product's parents
        $parentId = $productData->productCatId;
        $pathArr = fetch_recursive($parentId, $categories);
        //
        $arr['text'] = $productData->productName . '/' . $pathArr;
    }
    echo json_encode($arr);
}

function fetch_recursive($parentid, $categories)
{
    global $myProductcatEx;
    //print($parentid."<br>");
    $catData = $myProductcatEx->getCategoryAndParentByCatId($parentid);
    //print_r($catData);
    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

        //if($newParentId != 0 && isset($newParentId))
        {
            //$newParentName = $catData->parentName;
            //$categories .= $newParentName.'/';
            return fetch_recursive($newParentId, $categories);
        }
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}
