<?php
include("../public/impOpreation.php");
include("../public/include_dao.php");

include_once("../public/config.php");
include_once("dailyentryfun.php");

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

//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();


$do = $_GET['do'];
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");
if (empty($do)) {
    $smarty->display("header.html");
    $smarty->display("customerAccountMatchingview/add.html");
    $smarty->display("footer.html");
} else if ($do == "appendproduct") {
    $itr = filter_input(INPUT_POST, 'itr');
    $smarty->assign('itr', $itr);
    $smarty->display("customerAccountMatchingview/appendproduct.html");
} elseif ($do == "show") {
    $smarty->display("header.html");
    $smarty->display("customerAccountMatchingview/show.html");
    // $smarty->assign("realestateunits", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    $id = filter_input(INPUT_GET, 'id');
    $editdata = R::load('customerqccountmatching', $id);
    $client = R::getRow('SELECT * FROM `client` WHERE clientid = ?', [$editdata->clientid]);
    $editdata->clientname = $client['clientname'];
    $smarty->assign('editdata', $editdata);
    // $mechandisereturnproducts = R::findAll('mechandisereturnproduct','customerAccountMatchingid = ? and conditions = 0',[$id]);
    // foreach( $mechandisereturnproducts  as  $mechandisereturnproduct){
    //     $product = R::getRow('SELECT * FROM `product` WHERE productId = ?',[$mechandisereturnproduct->productid]);
    //     $mechandisereturnproduct->productname = $product['productName'];
    // }
    // $smarty->assign('mechandisereturnproducts', $mechandisereturnproducts);
    $smarty->display("header.html");
    $smarty->display("customerAccountMatchingview/edit.html");
    $smarty->display("footer.html");
} else if ($do == 'savedata') {
    savedata();
} else if ($do == 'showajax') {
    showajax();
} else if ($do == 'select2client') {
    select2client();
} else if ($do == 'select2product') {
    select2product();
} else if ($do == 'removeappend') {
    removeappend();
} else if ($do == 'agrees') {
    agrees();
} else if ($do == 'remove') {
    remove();
}


function agrees()
{
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $id = filter_input(INPUT_POST, 'id');
    $agrees = filter_input(INPUT_POST, 'agrees');
    $tables = R::load('customerqccountmatching', $id);
    $tables->agrees = $agrees;
    $tables->agreetoday = $today;
    $tables->agreeuserid = $userid;
    try {
        R::store($tables);
        echo 1;
    } catch (Exception $e) {
        echo 0;
    }
}
function select2product()
{
    $name = $_POST['searchTerm'];
    $productsData = R::getAll("SELECT productId, CONCAT(productName) as texts
    FROM product WHERE conditions = 0 and CONCAT(productName) LIKE '%" . $name . "%' limit 50");
    $return_arr = array();
    foreach ($productsData as $pro) {
        $row_array = array();
        $row_array['id'] = $pro['productId'];
        $row_array['text'] = $pro['texts'];
        array_push($return_arr, $row_array);
    }
    echo json_encode($return_arr);
}




function select2client()
{
    $name = $_POST['searchTerm'];
    $productsData = R::getAll("SELECT clientid, clientdebt, CONCAT(clientname,'/',clientphone) as texts
    FROM client WHERE conditions = 0 and CONCAT(clientname,'/',clientphone) LIKE '%" . $name . "%' limit 50");
    $return_arr = array();
    foreach ($productsData as $pro) {
        $row_array = array();
        $row_array['id'] = $pro['clientid'];
        $row_array['text'] = $pro['texts'];
        $row_array['debt'] = $pro['clientdebt'];
        array_push($return_arr, $row_array);
    }
    echo json_encode($return_arr);
}




function savedata()
{
    global $clientDAO;
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $identical = filter_input(INPUT_POST, 'identical');
    $clientid = filter_input(INPUT_POST, 'clientid');
    $newclientdebt = filter_input(INPUT_POST, 'newclientdebt');
    $comment = filter_input(INPUT_POST, 'comment');
    $id = filter_input(INPUT_POST, 'id');


    if (!$id) {
        $realestates = R::dispense('customerqccountmatching');
        $realestates->conditions = 0;
        $realestates->addtoday = $today;
        $realestates->adduserid = $userid;
        $realestates->deltoday = '';
        $realestates->deluserid = '';
    } else {
        $realestates = R::load('customerqccountmatching', $id);
        $realestates->updatetoday = $today;
        $realestates->updateuserid = $userid;
    }
    $clientdataSP = getClientDataFromClientInUseSP($clientid);
    $debtbefore = $clientdataSP->clientdebt;

    $client = R::getRow('SELECT * FROM `client` WHERE clientid = ?', [$clientid]);
    $clientdebt = $client['clientdebt'];
    if ($identical == 1) {
        $newclientdebt = $clientdebt;
        $comment = 'مطابقة حساب عميل';
    } else {
        R::exec("UPDATE `client` SET clientdebt = $newclientdebt where clientid = ? ", [$clientid]);
        markClientAsNOTInUse($clientid);
    }

    $realestates->comment = $comment;
    $realestates->clientid = $clientid;
    $realestates->newclientdebt = $newclientdebt;
    $realestates->clientdebt =  $clientdebt;
    $realestates->identical = $identical;
    try {
        $customerqccountmatchingid = R::store($realestates);

        if ($newclientdebt > $clientdebt) {
            $clientdebtchangetype = 0;
        } else {
            $clientdebtchangetype = 1;
        }
        $amount = ABS($clientdebt - $newclientdebt);


        R::exec("INSERT INTO `clientdebtchange`(`clientid`, `clientdebtchangebefore`, 
         `clientdebtchangeamount`, `clientdebtchangetype`, `processname`, `clientdebtchangemodelid`, 
         `clientdebtchangeafter`, `clientdebtchangedate`, `userid`, `tablename`, `comment`, `totalOperationCost`,
          `discount`, `reciptid`, `del`, `dailyentryid`, `num`, `billid`, `paytype`, `seller`, `discountearlyRepayment`, 
          `costcenterid`, `currencyId`, `conversionFactor`, `payedInCurrency`, `saveConversionFactor`)
           VALUES ($clientid,$clientdebt,$amount,$clientdebtchangetype,
           'مطابقة حساب عميل',$customerqccountmatchingid,$newclientdebt,
           '$today',$userid,'customerqccountmatching','$comment',$amount,0,null,0,0,null,null,' ',0,null,0,1,1,0,1)");

        if ($clientdebtchangetype == 0) {
            $clientData = $clientDAO->load($clientid);
            $dailyEntry->entryComment = ' مطابقة حساب العميل ' . $clientData->clientname . '';
            //////////////// start العميل

            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $amount;

            $dataClient = $clientDAO->load($clientid);

            $idTreeClient = $dataClient->treeId;
            $dailyEntryDebtor->accountstreeid = $idTreeClient;

            //end  العميل

            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $amount;
            $dailyEntryCreditor->accountstreeid = 146; //ايرادات الخصم المكتسب

            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

            insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
        } else {
            $clientData = $clientDAO->load($clientid);

            $dailyEntry->entryComment = ' مطابقة حساب العميل ' . $clientData->clientname . '';

            ////////////////  معالجة عجز عملاء

            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $amount;
            $dailyEntryDebtor->accountstreeid = 398; //خصم مسموح به
            ////////////////  العميل

            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $amount;

            $dataClient = $clientDAO->load($clientid);

            $idTreeClient = $dataClient->treeId;
            $dailyEntryCreditor->accountstreeid = $idTreeClient;

            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

            insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
        }

        header("location:customerAccountMatching.php?do=show");
        exit();
    } catch (Exception $e) {
        echo 0;
    }
}




function showajax()
{
    $columns = array('customerqccountmatching.id', 'clientname', 'customerqccountmatching.identical', 'clientdebt',  'newclientdebt', 'customerqccountmatching.comment', 'customerqccountmatching.addtoday', 'employeename', 'customerqccountmatching.id', 'customerqccountmatching.id');
    $start_date = filter_input(INPUT_POST, 'start_date');
    $end_date = filter_input(INPUT_POST, 'end_date');
    $conditions = filter_input(INPUT_POST, 'conditions');
    $clientid = filter_input(INPUT_POST, 'clientid');
    $identical = filter_input(INPUT_POST, 'identical');

    $searchQuery = " ";
    $searchjoin = " ";
    if ($clientid) {
        $searchQuery .=  " and customerqccountmatching.clientid = " . $clientid . " ";
    }
    if ($conditions) {
        $searchQuery .= " and customerqccountmatching.conditions =  " . $conditions . " ";
    }

    if ($identical) {
        $searchQuery .=  " and customerqccountmatching.identical = " . $identical . " ";
    }




    if ($start_date != '' && $end_date != '') {
        $searchQuery .= ' and  customerqccountmatching.addtoday  >= "' . $start_date . ' 00-00-00" and customerqccountmatching.addtoday <= "' . $end_date . ' 23-59-55" ';
    }


    if (isset($_POST['searchval']) && $_POST['searchval'] != "") {
        $searchQuery .= "and ( customerqccountmatching.id LIKE " % '.$_POST["searchval"].' % " 
                    OR clientname LIKE " % '.$_POST["searchval"].' % "
                    OR customerqccountmatching.addtoday LIKE " % '.$_POST["searchval"].' % "
                    OR employeename LIKE " % '.$_POST["searchval"].' % "
        )
     ";
    }

    if (isset($_POST["ordercol"])) {
        $searchQuery .= 'ORDER BY ' . $columns[$_POST['ordercol']] . ' ' . $_POST['orderdir'] . '  ';
    } else {
        $searchQuery .= "ORDER BY  customerqccountmatching.id DESC ";
    }


    $totals = R::count('customerqccountmatching', 'LEFT JOIN user ON customerqccountmatching.adduserid = user.userid 
        ' . $searchjoin . ' WHERE 1 ' . $searchQuery . ' ');

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

    $rResult = R::getAll('SELECT customerqccountmatching.* ,employeename,clientname   FROM `customerqccountmatching` 
    LEFT JOIN user ON customerqccountmatching.adduserid = user.userid
    LEFT JOIN client ON customerqccountmatching.clientid = client.clientid ' . $searchjoin . '  WHERE 1 ' . $searchQuery . ' ');

    $output = array(
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => count($rResult),
        "recordsFiltered" => $totals,
        "data" => array()
    );

    foreach ($rResult as $row) {

        $sub_array = array();
        $sub_array[] = $row["id"];
        $sub_array[] = $row["clientname"];
        if ($row["identical"] == 1) {
            $sub_array[] = ' مطابق ';
        } else {
            $sub_array[] = '    غير مطابق  ';
        }
        $sub_array[] = $row["clientdebt"];
        $sub_array[] = $row["newclientdebt"];
        $sub_array[] = $row["comment"];
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row['employeename'];
        if ($row["del"] < 2) {
            // if($row["agrees"] == 2){
            //     $sub_array[] = '  مرتجع للتسليم ' ;  
            // }else{
            $sub_array[] = '<a href="customerAccountMatching.php?do=edit&id=' . $row["id"] . '" type="button" class="btn btn-default btn-lg editicon"></a>';
            // }
            $sub_array[] = '<a href="customerAccountMatching.php?do=remove&id=' . $row["id"] . '" type="button" class="btn btn-default btn-lg deleteicon"></a>';
        } else {
            // if($row["agrees"] == 2){
            //     $sub_array[] = '  مرتجع للتسليم ' ;  
            // }else{
            $sub_array[] = '<a href="customerAccountMatching.php?do=edit&id=' . $row["id"] . '" type="button" class="btn btn-default btn-lm ">تفاصيل</a>';

            // }
            $sub_array[] = 'محذوف ';
        }

        $output['data'][] = $sub_array;
    }
    echo json_encode($output, JSON_UNESCAPED_SLASHES);
}



function removeappend()
{
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $id = filter_input(INPUT_POST, 'id');
    $tables = R::load('mechandisereturnproduct', $id);
    $tables->conditions = 1;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;
    try {
        R::store($tables);
        echo 1;
    } catch (Exception $e) {
        echo 0;
    }
}

function remove()
{
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $id = filter_input(INPUT_GET, 'id');
    $tables = R::load('customerqccountmatching', $id);
    $tables->conditions = 1;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;
    try {
        R::store($tables);
        header("location:customerAccountMatching.php?do=show");
        exit();
    } catch (Exception $e) {
        echo 0;
    }
}

function getClientDataFromClientInUseSP($clientid)
{
    global $clientExt;
    global $clientDAO;

    if ($clientid == 1) {
        $client_data = $clientDAO->load($clientid);
    } elseif ($clientid > 1) {
        $noOfTries = 0;
        $client_data = $clientExt->callClientInUseSP($clientid);
        while ($client_data->clientdebt == 'in_use') {
            sleep(1);
            $noOfTries++;
            if ($noOfTries > 15) { // mean 15 sec as sleep is 1 sec her
                //markClientAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
                liveBackupComment("-- force free client=$clientid with redbean");
                R::exec('UPDATE client SET  inUse = 0 where clientid = ' . $clientid);
            }
            $client_data = $clientExt->callClientInUseSP($clientid);
        }
    }
    return $client_data;
}

function markClientAsNOTInUse($clientid)
{ //mark as not in use "free him to be able to change debt again"
    global $clientExt;
    if ($clientid == 1) {
        //do no thing. we didnot mark it as in use at begining
    } else {
        $clientExt->markClientAsNOTInUse($clientid);
    }
}
