<?php
#Fungsi: Simpan ke Tabel FIFO baik untuk FIFO In maupun Out

Function SaveFIFO( $strBranchCode ,  $strTableRef ,$strDocumentNo,$dtpTransDate,$strIndex,
                          $strItemCode ,  $dblQty ,  $dblPrice,  $strWarehouseFrom,  $strWarehouseTo ,$strBarcode ,$intUnique) {
   
    $flagInv = RetRstField("SELECT ftitem_code FROM tlstock_hdr WHERE ftstock_category_code = 'inv' and ftitem_code = '{$strItemCode}' ");
    if ($flagInv != '') {    
        #Generate ID FIFO
        $ssql="SELECT MAX(fnIdFIFO) AS fnIdFIFO
                              FROM TXStockFIFO
                              WHERE ftBranch_Code = '" . $strBranchCode. "' ORDER BY fnIdFIFO";
        $rsAdd=mysql_query($ssql) or die($ssql);
        $Last=0;
        while($rAdd=mysql_fetch_assoc($rsAdd)) {
               #Ambil fnIdFIFO Terakhir sebagai referensi untuk Record FIFO yang baru
              $Last = $rAdd["fnIdFIFO"];
        }


        $fnIdFIFO=$Last+1;
        If($dblQty > 0)   {
            #'Qty > 0, berati Record FIFO In
            $ssql= "INSERT INTO txstockfifo
                          (fnIdFIFO, ftBranch_Code, ftDocument_No,
                              ftTableRef, fdTrans_Date, fnIndex,
                              ftItem_Code, ftWarehouse_Code, ftBarcode,
                              fnUnique_Barcode, ftBatch_Code, fcNet_Price,
                              fnQty, fnQty_Outstanding, fnIdFIFORef,
                              fnPriority, fnStatus, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date )
                      SELECT  '{$fnIdFIFO}' AS fnIdFIFO, '{$strBranchCode}' AS ftBranch_Code,'{$strDocumentNo}'   AS ftDocument_No,
                              '{$strTableRef}'  AS ftTableRef, '{$dtpTransDate}' AS fdTrans_Date, '{$strIndex}'  AS fnIndex,
                              '{$strItemCode}'   AS ftItem_Code,'{$strWarehouseFrom}' AS ftWarehouse_Code,'{$strBarcode}'  AS  ftBarcode,
                              '{$intUnique}'   AS fnUnique_Barcode,'{$strBatchCode}' AS ftBatch_Code,  '{$dblPrice}'    AS  fcNet_Price,
                              ROUND('{$dblQty}',2) AS fnQty,'{$dblQty}'   AS fnQty_Outstanding, '{$fnIdFIFO}'  AS fnIdFIFORef,
                              '1'   AS fnPriority, '1'  AS fnStatus,'{$_SESSION['username']}' AS ftCreated_User,NOW() AS fdCreated_Date,
                              '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date";

              mysql_query($ssql) or die($ssql);

        }

        Else If($dblQty < 0) {
            #'QTy < 0, berarti Record FIFO Out
            #'untuk record FIFO Out nilai fnQty, fnQty_Outstanding diisi minus, fnIdFIFORef diisi 0
            $ssql= "INSERT INTO txstockfifo
                         (fnIdFIFO, ftBranch_Code, ftDocument_No,
                             ftTableRef, fdTrans_Date, fnIndex,
                             ftItem_Code, ftWarehouse_Code, ftBarcode,
                             fnUnique_Barcode, ftBatch_Code, fcNet_Price,
                             fnQty, fnQty_Outstanding, fnIdFIFORef,
                             fnPriority, fnStatus, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date )
                     SELECT  '{$fnIdFIFO}' AS fnIdFIFO, '{$strBranchCode}' AS ftBranch_Code,'{$strDocumentNo}'   AS ftDocument_No,
                             '{$strTableRef}'  AS ftTableRef, '{$dtpTransDate}' AS fdTrans_Date, '{$strIndex}'  AS fnIndex,
                             '{$strItemCode}'   AS ftItem_Code,'{$strWarehouseFrom}' AS ftWarehouse_Code,'{$strBarcode}'  AS  ftBarcode,
                             '{$intUnique}'   AS fnUnique_Barcode,'{$strBatchCode}' AS ftBatch_Code, 0 AS  fcNet_Price,
                             ROUND('".-1*abs($dblQty)."',2) AS fnQty,'".-1*abs($dblQty)."' AS fnQty_Outstanding, '0'  AS fnIdFIFORef,
                             '0' AS fnPriority, '1'  AS fnStatus,'{$_SESSION['username']}' AS ftCreated_User,NOW() AS fdCreated_Date,
                             '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date";


            mysql_query($ssql) or die($ssql);

        }
        //pr($ssql);
        #Adjust FIFO
        FIFOAdj($strBranchCode, $strIndex, $strItemCode, $strWarehouseFrom, $strWarehouseTo, $strBarcode, $intUnique,$fnIdFIFO);
    }    
}
                          

#'Fungsi: FIFO ketika Retur Penjualan
Function ReturFIFO($strBranchCode, $strTableRef, $strDocumentNo, $strReturDocumentRef,
                        $dtpTransDate, $strIndex, $strItemCode, $dblQty, $strWarehouseFrom, $strItemReff = "") {

    $flagInv = RetRstField("SELECT ftitem_code,ftstock_category_code FROM tlstock_hdr WHERE ftstock_category_code = 'inv' and ftitem_code = '{$strItemCode}' ");
    if ($flagInv != '') {    
        $fnIdFIFO=0;
        $Sisa=0;

        $ssql="SELECT * FROM TXStockFIFO WHERE ftBranch_Code = '" . $strBranchCode . "' AND ftDocument_No = '" . $strReturDocumentRef . "' AND ftItem_Code = '" . $strItemCode . "' ORDER BY fnPriority, fnIdFIFO";
        $rsRef = mysql_query($ssql)  or die($ssql);

        $Sisa=$dblQty;
        while(($rRef=mysql_fetch_assoc($rsRef))&&($Sisa>0)) {
            $ssql="SELECT IFNULL(MAX(fnIdFIFO),0) + 1 FROM TXStockFIFO";
            $fnIdFIFO = RetRstField($ssql);
            //pr($rRef['fnIdFIFO']);
            If(abs($rRef["fnQty"]) >= $Sisa) {

                $ssql="INSERT INTO TXStockFIFO
                            ( ftBranch_Code, fnIdFIFO, ftDocument_No,
                                ftTableRef, fdTrans_Date, fnIndex,
                                ftItem_Code, ftWarehouse_Code, fnQty, fnQty_Outstanding,
                                fnStatus, fnPriority, fcNet_Price,
                                fnIdFIFORef, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date )
                        SELECT '{$strBranchCode}' AS ftBranch_Code,'{$fnIdFIFO}' AS  fnIdFIFO, '{$strDocumentNo}' AS ftDocument_No,
                            '{$strTableRef}' AS ftTableRef,'{$dtpTransDate}' AS  fdTrans_Date, '{$strIndex}' AS fnIndex,
                            '{$strItemCode}' AS  ftItem_Code,'{$strWarehouseFrom}' AS  ftWarehouse_Code,'{$Sisa}' AS  fnQty,'{$Sisa}' AS  fnQty_Outstanding,
                            '1' AS fnStatus,'1' AS fnPriority, '{$rRef['fcNet_Price']}' AS fcNet_Price,
                            {$rRef['fnIdFIFO']} AS fnIdFIFORef,'{$_SESSION['username']}' AS ftCreated_User,NOW() AS fdCreated_Date,
                            '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date";

                /*$ssql="INSERT INTO TXStockFIFO
                            ( ftBranch_Code, fnIdFIFO, ftDocument_No,
                                ftTableRef, fdTrans_Date, fnIndex,
                                ftItem_Code, ftWarehouse_Code, fnQty, fnQty_Outstanding,
                                fnStatus, fnPriority, fcNet_Price,
                                fnIdFIFORef, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date )
                        SELECT '{$strBranchCode}' AS ftBranch_Code,'{$fnIdFIFO}' AS  fnIdFIFO, '{$strDocumentNo}' AS ftDocument_No,
                            '{$strTableRef}' AS ftTableRef,'{$dtpTransDate}' AS  fdTrans_Date, '{$strIndex}' AS fnIndex,
                            '{$strItemCode}' AS  ftItem_Code,'{$strWarehouseFrom}' AS  ftWarehouse_Code,'{$Sisa}' AS  fnQty,'{$Sisa}' AS  fnQty_Outstanding,
                            '1' AS fnStatus,'1' AS fnPriority, '{$rRef['fcNet_Price']}' AS fcNet_Price,
                            '{$fnIdFIFO}' AS fnIdFIFORef,'{$_SESSION['username']}' AS ftCreated_User,NOW() AS fdCreated_Date,
                            '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date"; */
                mysql_query ($ssql)  or die($ssql);
            }
            else {

                $ssql="INSERT INTO TXStockFIFO
                            (ftBranch_Code, fnIdFIFO, ftDocument_No,
                                ftTableRef, fdTrans_Date, fnIndex,
                                ftItem_Code, ftWarehouse_Code, fnQty, fnQty_Outstanding,
                                fnStatus, fnPriority, fcNet_Price,
                                fnIdFifoRef, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date)
                        SELECT '{$strBranchCode}' AS ftBranch_Code,'{$fnIdFIFO}' AS  fnIdFIFO, '{$strDocumentNo}' AS  ftDocument_No,
                                '{$strTableRef}' AS  ftTableRef,'{$dtpTransDate}' AS  fdTrans_Date, '{$strIndex}' AS fnIndex,
                                '{$strItemCode}' AS  ftItem_Code, '{$strWarehouseFrom}' AS  ftWarehouse_Code, '".abs($rRef['fnQty'])."' AS fnQty, '".abs($rRef['fnQty'])."' AS  fnQty_Outstanding,
                                '1' AS  fnStatus, '1' AS  fnPriority, '{$rRef['fcNet_Price']}' AS  fcNet_Price,
                                {$rRef['fnIdFIFO']} AS   fnIdFIFORef,'{$_SESSION['username']}' AS  ftCreated_User, NOW() AS fdCreated_Date,
                                '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date";
                /*
                $ssql="INSERT INTO TXStockFIFO
                            (ftBranch_Code, fnIdFIFO, ftDocument_No,
                                ftTableRef, fdTrans_Date, fnIndex,
                                ftItem_Code, ftWarehouse_Code, fnQty, fnQty_Outstanding,
                                fnStatus, fnPriority, fcNet_Price,
                                fnIdFifoRef, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date)
                        SELECT '{$strBranchCode}' AS ftBranch_Code,'{$fnIdFIFO}' AS  fnIdFIFO, '{$strDocumentNo}' AS  ftDocument_No,
                                '{$strTableRef}' AS  ftTableRef,'{$dtpTransDate}' AS  fdTrans_Date, '{$strIndex}' AS fnIndex,
                                '{$strItemCode}' AS  ftItem_Code, '{$strWarehouseFrom}' AS  ftWarehouse_Code, '".abs($rRef['fnQty'])."' AS fnQty, '".abs($rRef['fnQty'])."' AS  fnQty_Outstanding,
                                '1' AS  fnStatus, '1' AS  fnPriority, '{$rRef['fcNet_Price']}' AS  fcNet_Price,
                                '{$fnIdFIFO}' AS   fnIdFIFORef,'{$_SESSION['username']}' AS  ftCreated_User, NOW() AS fdCreated_Date,
                                '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date"; */
                mysql_query ($ssql)  or die($ssql); 
            }
            // pr($ssql);
            $Sisa = $Sisa - Abs($rRef["fnQty"]);
            $LastPrice = $rRef['fcNet_Price'];

            #Adjust FIFO
            FIFOAdj($strBranchCode, $strIndex, $strItemCode, $strWarehouseFrom, $strWarehouseTo, $strBarcode, $intUnique,$fnIdFIFO);
        
        }
        
        // Bila masih ada sisa qty sedangkan referensi fifo sudah habis. (bisa disebabkan karena validasi qty salah atau error program)
        If ($Sisa > 0) {
            $ssql="SELECT IFNULL(MAX(fnIdFIFO),0) + 1 FROM TXStockFIFO";
            $fnIdFIFO = RetRstField($ssql);
            
            $ssql="INSERT INTO TXStockFIFO
                            (ftBranch_Code, fnIdFIFO, ftDocument_No,
                                ftTableRef, fdTrans_Date, fnIndex,
                                ftItem_Code, ftWarehouse_Code, fnQty, fnQty_Outstanding,
                                fnStatus, fnPriority, fcNet_Price,
                                fnIdFifoRef, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date)
                        SELECT '{$strBranchCode}' AS ftBranch_Code,'{$fnIdFIFO}' AS  fnIdFIFO, '{$strDocumentNo}' AS  ftDocument_No,
                                '{$strTableRef}' AS  ftTableRef,'{$dtpTransDate}' AS  fdTrans_Date, '{$strIndex}' AS fnIndex,
                                '{$strItemCode}' AS  ftItem_Code, '{$strWarehouseFrom}' AS  ftWarehouse_Code, '{$Sisa}' AS fnQty, '{$Sisa}' AS  fnQty_Outstanding,
                                '1' AS  fnStatus, '1' AS  fnPriority, '{$LastPrice}' AS  fcNet_Price,
                                {$fnIdFIFO} AS fnIdFIFORef,'{$_SESSION['username']}' AS  ftCreated_User, NOW() AS fdCreated_Date,
                                '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date";
                                
             mysql_query ($ssql)  or die($ssql); 
        
            #Adjust FIFO
            FIFOAdj($strBranchCode, $strIndex, $strItemCode, $strWarehouseFrom, $strWarehouseTo, $strBarcode, $intUnique,$fnIdFIFO);
        
        }
   
    }    
}


#'Fungsi: FIFO ketika Retur Pembelian
Function ReturPembelianFIFO($strBranchCode, $strTableRef, $strDocumentNo, $strReturDocumentRef,
                          $dtpTransDate, $strIndex, $strItemCode, $dblQty, $strWarehouseFrom, $strItemReff = "") {

    $flagInv = RetRstField("SELECT ftitem_code,ftstock_category_code FROM tlstock_hdr WHERE ftstock_category_code = 'inv' and ftitem_code = '{$strItemCode}' ");
    if ($flagInv != '') {    
        
        $fnIdFIFO=0;
        $Sisa=0;

        if($strItemReff == "")  {
            $ssql="SELECT * FROM TXStockFIFO WHERE ftBranch_Code = '" . $strBranchCode . "' AND ftDocument_No = '" . $strReturDocumentRef . "' AND ftItem_Code = '" . $strItemCode . "' ORDER BY fnPriority, fnIdFIFO";
            $rsRef = mysql_query($ssql)  or die($ssql);
        }
        //pr($ssql);
        $Sisa=abs($dblQty);

        $ssql="SELECT IFNULL(MAX(fnIdFIFO),0) FROM TXStockFIFO";
        $fnIdFIFO = RetRstField($ssql);

        while(($rRef=mysql_fetch_assoc($rsRef))&&($Sisa>0)) {
            $fnIdFIFO = $fnIdFIFO + 1;

            If($rRef["fnQty_Outstanding"] >= $Sisa) {
                $ssql="INSERT INTO TXStockFIFO
                              (
                                  ftBranch_Code, fnIdFIFO, ftDocument_No,
                                  ftTableRef, fdTrans_Date, fnIndex,
                                  ftItem_Code, ftWarehouse_Code, fnQty, fnQty_Outstanding,
                                  fnStatus, fnPriority, fcNet_Price,
                                  fnIdFifoRef, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date
                              )
                              SELECT '{$strBranchCode}' AS ftBranch_Code,'{$fnIdFIFO}' AS  fnIdFIFO, '{$strDocumentNo}' AS ftDocument_No,
                                  '{$strTableRef}' AS ftTableRef,'{$dtpTransDate}' AS  fdTrans_Date, '{$strIndex}' AS fnIndex,
                                  '{$strItemCode}' AS  ftItem_Code,'{$strWarehouseFrom}' AS  ftWarehouse_Code,'".-1*$Sisa."' AS  fnQty, '0' AS fnQty_Outstanding,
                                  '1' AS fnStatus,'0' AS fnPriority, '{$rRef['fcNet_Price']}' AS fcNet_Price,
                                  {$rRef['fnIdFIFO']} AS fnIdFifoRef,'{$_SESSION['username']}' AS ftCreated_User,NOW() AS fdCreated_Date,
                                  '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date";
                mysql_query ($ssql)  or die($ssql);

                $ssql=" UPDATE TXStockFIFO
                        SET fnQty_Outstanding = fnQty_Outstanding - " . $Sisa . ",
                            ftModified_User='{$_SESSION['username']}',
                            fdModified_Date=Now()
                        WHERE ftBranch_Code = '" . $strBranchCode . "' AND fnIdFIFO = '" . $rRef["fnIdFIFO"]."'";
                mysql_query($ssql) or die($ssql);
            }
            else {
                $ssql="INSERT INTO TXStockFIFO
                            (ftBranch_Code, fnIdFIFO, ftDocument_No,
                                ftTableRef, fdTrans_Date, fnIndex,
                                ftItem_Code, ftWarehouse_Code, fnQty, fnQty_Outstanding,
                                fnStatus, fnPriority, fcNet_Price,
                                fnIdFifoRef, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date)
                        SELECT '{$strBranchCode}' AS ftBranch_Code,'{$fnIdFIFO}' AS  fnIdFIFO, '{$strDocumentNo}' AS  ftDocument_No,
                                '{$strTableRef}' AS  ftTableRef,'{$dtpTransDate}' AS  fdTrans_Date, '{$strIndex}' AS fnIndex,
                                '{$strItemCode}' AS  ftItem_Code,'{$strWarehouseFrom}' AS  ftWarehouse_Code, '".-1*$rRef["fnQty_Outstanding"]."' AS fnQty, '0' AS  fnQty_Outstanding,
                                '1' AS  fnStatus, '0' AS  fnPriority, '{$rRef['fcNet_Price']}' AS fcNet_Price,
                                {$rRef['fnIdFIFO']} AS   fnIdFifoRef,'{$_SESSION['username']}' AS ftCreated_User, NOW() AS fdCreated_Date,
                                '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date";
                mysql_query ($ssql)  or die($ssql);

                $ssql="UPDATE TXStockFIFO
                        SET fnQty_Outstanding = 0,
                            ftModified_User='{$_SESSION['username']}',
                            fdModified_Date=Now()
                        WHERE ftBranch_Code = '" . $strBranchCode . "' AND fnIdFIFO = '" . $rRef["fnIdFIFO"]."'";
                mysql_query($ssql) or die($ssql);

                // Sisa qty yang tidak tercukupi dibuat stock fifo out
                $Sisa = $Sisa - Abs($rRef["fnQty_Outstanding"]);
                SaveFIFO($strBranchCode,$strTableRef,$strDocumentNo,$dtpTransDate,$strIndex,$strItemCode, -1*$Sisa,0,$strWarehouseFrom,"","","");
            }    
        }
    }    
}


#'Fungsi: -untuk Mengurangi nilai Pada Record FIFO In dengan nilai pada Record FIFO Out
#'        -untuk mengupdate nilai pada Record FIFO Out yang link fnIdFIFORef-nya masih '0'
function FIFOAdj($strBranchCode, $strIndex, $strItemCode, $strWarehouseFrom="", $strWarehouseTo="",$strBarcode="", $intUnique="", $fnIdFIFO="") {
   
    $Flag=false;
    $strSQL="";
    $fnIdFIFO=0;
    $Sisa1=0;
    $Sisa2=0;
    $Flag = False;

    if ($fnIdFIFO == "") {
        $fnIdFIFO = RetRstField("SELECT MAX(fnIdFIFO)+1 FROM TXStockFIFO");
    } else {
        $fnIdFIFO = $fnIdFIFO + 1;
    }
    #'Cari Record FIFO In
    If($strBarcode != "") {
        #'Jika Menggunakan Barcode
        $strSQL = "SELECT * FROM TXStockFIFO WHERE ftBranch_Code = '" . $strBranchCode . "' AND ftItem_Code = '" . $strItemCode . "' AND ftBarcode = '" . $strBarcode . "' AND fnQty_Outstanding > 0 AND ftWarehouse_Code='" . $strWarehouseFrom . "' AND fnStatus = 1 ORDER BY fnIdFIFO, fnPriority";
    }
    else {
        #'Jika tidak menggunakan Barcode
        $strSQL = "SELECT * FROM TXStockFIFO WHERE ftBranch_Code = '" . $strBranchCode . "' AND ftItem_Code = '" . $strItemCode . "' AND fnQty_Outstanding > 0 AND ftWarehouse_Code='" . $strWarehouseFrom . "' AND fnStatus = 1 ORDER BY fnIdFIFO, fnPriority";
    }
    // pr($strSQL);

    $rsFIFOIn=mysql_query($strSQL)  or die($strSQL);

    if(mysql_num_rows($rsFIFOIn)>0) {
        $rFIFOIn=mysql_fetch_assoc($rsFIFOIn);
        #'Cari Record FIFO Out yang link fnIdFIFORef-nya belum ada
        If($strBarcode != "") {
          $strSQL = "SELECT * FROM TXStockFIFO WHERE ftBranch_Code = '" . $strBranchCode . "' AND ftItem_Code = '" . $strItemCode . "' AND ftBarcode = '" . $strBarcode . "' AND fnIdFIFORef = 0 AND ftWarehouse_Code='" . $strWarehouseFrom . "' AND fnStatus = 1 AND fnQty_Outstanding < 0 ORDER BY fnIdFIFO";
        }
        Else {
          $strSQL = "SELECT * FROM TXStockFIFO WHERE ftBranch_Code = '" . $strBranchCode . "' AND ftItem_Code = '" . $strItemCode . "' AND fnIdFIFORef = 0 AND ftWarehouse_Code='" . $strWarehouseFrom . "' AND fnStatus = 1 AND fnQty_Outstanding < 0 ORDER BY fnIdFIFO";
        }

        // pr($strSQL);

        $rsFIFOOut=mysql_query($strSQL)  or die($strSQL);

        if(mysql_num_rows($rsFIFOOut)>0) {

            #'Ambil nilai sisa dari Record FIFO In untuk dikurangi dengan nilai pada Record FIFO Out
            $Sisa1 = $rFIFOIn["fnQty_Outstanding"];
            while($rFIFOOut=mysql_fetch_assoc($rsFIFOOut)) {
                $Sisa2 = $Sisa1;
                $Sisa1 = round($Sisa1 - abs($rFIFOOut["fnQty"]),2);

                If($Sisa1 >= 0){ 
                    #'Jika nilai sisa pada Record FIFO In setelah dikurangi dengan nilai pada Record FIFO Out >-1
                    $rFIFOOut["fcNet_Price"] = $rFIFOIn["fcNet_Price"];
                    $rFIFOOut["fnIdFIFORef"] = $rFIFOIn["fnIdFIFO"];
                    $rFIFOOut["fnQty_Outstanding"] = 0;
                    $rFIFOOut["ftModified_User"] = $_SESSION['username']; 

                    // update FIFO Out
                    $ssql="UPDATE TXStockFIFO SET 
                              fcNet_Price='{$rFIFOIn['fcNet_Price']}',
                              fnIdFIFORef='{$rFIFOIn['fnIdFIFO']}',
                              fnQty_Outstanding='0',
                              ftModified_User='{$_SESSION['username']}',
                              fdModified_Date=Now()
                            WHERE fnid='{$rFIFOOut['fnId']}'";
                    mysql_query($ssql)   or die($ssql);
                    // pr($strSQL);

                    UpdateLink($strBranchCode, $rFIFOOut["fnIdFIFO"], $rFIFOIn["fnIdFIFO"], $rFIFOIn["fcNet_Price"]);

                    // update outstanding FIFO In
                    $ssql=" UPDATE TXStockFIFO
                            SET fnQty_Outstanding = '" . $Sisa1 . "',
                                ftModified_User='{$_SESSION['username']}',
                                fdModified_Date=Now()
                            WHERE ftBranch_Code = '" . $strBranchCode . "' AND fnIdFIFO = '" . $rFIFOIn["fnIdFIFO"]."'";
                    mysql_query($ssql) or die($ssql); 

                    If(substr($rFIFOOut["ftTableRef"],0,20) == "txstock_mutation_det") {
                        #'Generate ID FIFO untuk persiapan penyisipan record baru
                        $ssql=" INSERT INTO TXStockFIFO
                                        (ftBranch_Code, fnIdFIFO, fnIdFIFORef,
                                        ftDocument_No, ftTableRef, fdTrans_Date,
                                        fnIndex, ftItem_Code, ftWarehouse_Code,
                                        fnQty, fnQty_Outstanding, fnStatus,
                                        fnPriority, fcNet_Price, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date)
                                SELECT
                                   '{$strBranchCode}' AS  ftBranch_Code,  '{$fnIdFIFO}' AS  fnIdFIFO, '{$fnIdFIFO}' AS   fnIdFIFORef,
                                   '{$rFIFOOut['ftDocument_No']}' AS   ftDocument_No,  '{$rFIFOOut['ftTableRef']}' AS  ftTableRef,  '{$rFIFOOut['fdTrans_Date']}'  AS  fdTrans_Date,
                                    '{$rFIFOOut['fnIndex']}' AS   fnIndex,    '{$rFIFOOut['ftitem_code']}' AS  ftItem_Code, '{$strWarehouseTo}' AS   ftWarehouse_Code,
                                    ROUND('" . Abs($rFIFOOut['fnQty']) . "',2) AS fnQty,  '" . Abs($rFIFOOut['fnQty']) . "' AS   fnQty_Outstanding,  '1' AS  fnStatus,
                                   '0' AS   fnPriority,  '{$rFIFOIn['fcNet_Price']}'  AS  fcNet_Price,  '{$_SESSION['username']}' AS  ftCreated_User, NOW() AS fdCreated_Date,
                                   '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date";
                        mysql_query ($ssql) or die($ssql);
                        $fnIdFIFO = $fnIdFIFO + 1;
                        // pr($ssql);
                       
                        #'dikarenakan terjadi penyisipan Record Baru (Break Down) maka panggil Procedure FIFOAjd untuk melakukan Adjustment Kembali
                        FIFOAdj($strBranchCode, $strIndex, $strItemCode, $strWarehouseFrom, $strWarehouseTo, $strBarcode, $intUnique,$fnIdFIFO);
    
                    }
                    
                } 
                Else {
                    #'Jika nilai sisa pada Record FIFO In setelah dikurangi dengan nilai pada Record FIFO Out < -1

                    $rFIFOOut["fnQty"] = -$Sisa2;
                    $rFIFOOut["fcNet_Price"] = $rFIFOIn["fcNet_Price"];
                    $rFIFOOut["fnQty_Outstanding"] = 0;
                    $rFIFOOut["fnIdFIFORef"] = $rFIFOIn['fnIdFIFO'];
                    $rFIFOOut["ftModified_User"] = $_SESSION['username'];
                    
                    // Update outstanding FIFO Out
                    $ssql=" UPDATE TXStockFIFO 
                            SET fnQty=ROUND('". -$Sisa2. "',2),
                                fcNet_Price='{$rFIFOIn['fcNet_Price']}',
                                fnQty_Outstanding='0',
                                fnIdFIFORef='{$rFIFOIn['fnIdFIFO']}' , 
                                ftModified_User='{$_SESSION['username']}',
                                fdModified_Date=Now()
                            WHERE fnid='{$rFIFOOut['fnId']}'";

                    mysql_query($ssql)  or die($ssql); 
                    // pr($ssql);

                    #'Update Qty Record FIFO In menjadi 0
                    $ssql=" UPDATE TXStockFIFO
                            SET fnQty_Outstanding = 0, ftModified_User='{$_SESSION['username']}', fdModified_Date=Now()
                            WHERE ftBranch_Code = '" . $strBranchCode . "' AND fnIdFIFO = " . $rFIFOIn["fnIdFIFO"]. " And fnStatus = 1 ";
                    mysql_query($ssql)  or die($ssql); 

                    #'Generate FIFO in mutasi
                    If(substr($rFIFOOut["ftTableRef"],0,20) == "txstock_mutation_det") {
                        
                        $ssql="INSERT INTO TXStockFIFO
                                    (ftBranch_Code, fnIdFIFO, fnIdFIFORef,
                                        ftDocument_No, ftTableRef, fdTrans_Date,
                                        fnIndex, ftItem_Code, ftWarehouse_Code,
                                        fnQty, fnQty_Outstanding, fnStatus,
                                        fnPriority, fcNet_Price, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date)
                                SELECT '{$strBranchCode}' AS ftBranch_Code,'{$fnIdFIFO}'   AS fnIdFIFO, '{$fnIdFIFO}'  AS fnIdFIFORef,
                                        '" . $rFIFOOut["ftDocument_No"] . "'  AS  ftDocument_No, '" . $rFIFOOut["ftTableRef"] . "'  AS  ftTableRef,'" . $rFIFOOut["fdTrans_Date"] . "'  AS  fdTrans_Date,
                                        '" . $rFIFOOut["fnIndex"] . "'  AS  fnIndex,'" . $rFIFOOut["ftitem_code"] . "' AS ftItem_Code, '" . $strWarehouseTo . "' AS ftWarehouse_Code,
                                        ROUND('" . Abs($rFIFOOut["fnQty"]) . "',2) AS fnQty, '" . Abs($rFIFOOut["fnQty"]) . "'  AS fnQty_Outstanding,'1'   AS fnStatus,
                                        '0'   AS fnPriority," . $rFIFOOut["fcNet_Price"] . " AS  fcNet_Price, '{$_SESSION['username']}' AS ftCreated_User, NOW() AS fdCreated_Date,
                                        '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date";

                        mysql_query($ssql)  or die($ssql);
                        $fnIdFIFO = $fnIdFIFO + 1;
                        // pr($ssql);
                        
                        #'dikarenakan terjadi penyisipan Record Baru (Break Down) maka panggil Procedure FIFOAjd untuk melakukan Adjustment Kembali
                        FIFOAdj($strBranchCode, $strIndex, $strItemCode, $strWarehouseFrom, $strWarehouseTo, $strBarcode, $intUnique,$fnIdFIFO);
    
                    }

                    #'Generate ID FIFO untuk persiapan penyisipan record baru
                    //$fnIdFIFO = RetRstField("SELECT MAX(fnIdFIFO)+1 FROM TXStockFIFO");

                    if ($Sisa1 != 0) {
                        #'Insert Record baru Karena ada Proses Break Down Record yang berasal dari Record FIFO Out
                        #'Isi nilai Record baru dengan hasil sisa dari Record In Dikurangi Record Out
                        $ssql="INSERT INTO TXStockFIFO
                                      (ftBranch_Code, fnIdFIFO, fnIdFIFORef,
                                      ftDocument_No, ftTableRef, fdTrans_Date,
                                      fnIndex, ftItem_Code, ftWarehouse_Code,
                                      fnQty, fnQty_Outstanding, fnStatus,
                                      fnPriority, fcNet_Price, ftCreated_User, fdCreated_Date, ftModified_User,fdModified_Date)
                                SELECT '{$strBranchCode}' AS ftBranch_Code, '{$fnIdFIFO}' AS fnIdFIFO, '0' AS fnIdFIFORef,
                                          '" . $rFIFOOut["ftDocument_No"] . "' AS ftDocument_No, '" . $rFIFOOut["ftTableRef"] . "' AS ftTableRef, '" . $rFIFOOut["fdTrans_Date"] . "' AS fdTrans_Date,
                                          '" . $rFIFOOut["fnIndex"] . "' AS fnIndex, '" . $rFIFOOut["ftitem_code"] . "' AS ftItem_Code, '" . $strWarehouseFrom . "' AS ftWarehouse_Code,
                                          ROUND('" . $Sisa1 . "',2) AS fnQty,  " . $Sisa1 . " AS fnQty_Outstanding, '1' AS fnStatus,
                                          0 AS fnPriority,'" . $rFIFOOut["fcNet_Price"] ."' AS fcNet_Price, '{$_SESSION['username']}' AS ftCreated_User, NOW() AS fdCreated_Date,
                                          '{$_SESSION['username']}' AS ftModified_User,NOW() AS fdModified_Date";
                        mysql_query($ssql) or die($ssql);
                        $fnIdFIFO = $fnIdFIFO + 1;
                        // pr($ssql);

                        #'Set Flag = True untuk dilakukan Adjustment
                        $Flag = True;
                    }    
                    break;
                }
            }
        }
    }
 
    If($Flag)  {
      #'dikarenakan terjadi penyisipan Record Baru (Break Down) maka panggil Procedure FIFOAjd untuk melakukan Adjustment Kembali
      FIFOAdj($strBranchCode, $strIndex, $strItemCode, $strWarehouseFrom, $strWarehouseTo, $strBarcode, $intUnique,$fnIdFIFO);
    }
 
}

Function UpdateLink($strBranchCode, $IdLink, $CompLink, $HrgNet) {
  
    $Updt = False;
    $strSQL = "SELECT * FROM TXStockFIFO WHERE ftBranch_Code = '" . $strBranchCode . "' AND fnIdFIFORef = " . $IdLink;

    $rsUp=mysql_query($strSQL)   or die($strSQL);
    If (mysql_num_rows($rsUp)>0)  {
        $rUp=mysql_fetch_assoc($rsUp);
        If($CompLink != $rUp["fnIdFIFO"]) {
            $Updt = True;
        }
    }
    Else {
        $Updt = False ;
        return "";
    }

    $strSQL = "SELECT * FROM TXStockFIFO WHERE ftBranch_Code = '" . $strBranchCode . "' AND fnIdFIFORef = " . $IdLink;

    $rsUp=mysql_query($strSQL)   or die($strSQL);

    while(($rUp=mysql_fetch_assoc($rsUp))&&($Updt)){
    
        // die(" mmm :". $rUp['fnId'] ."#");
        $rUp["fcNet_Price"] = $HrgNet;

        $ssql=" UPDATE TXStockFIFO 
                SET fcNet_Price='{$HrgNet}', ftModified_User='{$_SESSION['username']}', fdModified_Date=Now()
                WHERE fnid='{$rUp['fnId']}'";
        mysql_query($ssql)   or die($ssql);

        UpdateLink($strBranchCode, $rUp["fnIdFIFO"], $rUp["fnIdFIFORef"], $HrgNet); 
    }
}


#'Fungsi Batalkan FIFO
Function CancelFIFO($strBranchCode, $strTableRef, $strDocumentNo) { 
    #'Set Flag Sementara Sebagai Tanda Bahwa Record FIFO Akan dibatalkan
    $ssql="UPDATE TXStockFIFO
            SET fnStatus = 2, ftModified_User='{$_SESSION['username']}', fdModified_Date=Now()
            WHERE ftBranch_Code = '" . $strBranchCode . "' AND ftTableRef = '" . $strTableRef . "' AND ftDocument_No = '" . $strDocumentNo . "' AND fnStatus = 1";
    mysql_query($ssql)   or die($ssql);
    //pr($ssql);
    
    #'Ambil Data Record FIFO yang sudah diberi tanda
    $ssql="SELECT * FROM TXStockFIFO WHERE ftBranch_Code = '" . $strBranchCode . "' AND ftTableRef = '" . $strTableRef . "' AND ftDocument_No = '" . $strDocumentNo . "' AND fnStatus = 2";
    $rsChk= mysql_query($ssql)   or die($ssql);
    //pr($ssql);

    while($rChk=mysql_fetch_assoc($rsChk)) {
        //pr($rChk["fnIdFIFO"]."-".$rChk["fnQty"]);
        If ($rChk["fnQty"] > 0) {
            #'Jika Qty > 0, Berarti Record yang datanya diambil diatas adalah Record FIFO In
            #'Ambil Record yang fnIdFIFORef-nya merujuk ke Record FIFO In Diatas
            $strSQL ="SELECT * FROM TXStockFIFO
                        WHERE ftBranch_Code = '" . $strBranchCode . "' AND
                                ftTableRef <> '" . $strTableRef . "' AND
                                fnStatus = 1 AND fnIdFIFORef = " . $rChk["fnIdFIFO"];
            //pr("+:".$strSQL);
            $rsAdd=mysql_query($strSQL)   or die($strSQL);
      
            If(mysql_num_rows($rsAdd)) {
                $rAdd=mysql_fetch_assoc($rsAdd);
                $Sisa = $rAdd["fnQty_Outstanding"] - $rChk["fnQty"];
                $rsAdd=mysql_query($strSQL)   or die($strSQL);

                while($rAdd=mysql_fetch_assoc($rsAdd)) {
                    If(abs($rAdd["fnQty"]) > abs($Sisa))  {
                        $rAdd["fnQty_OutStanding"] = $rAdd["fnQty_OutStanding"] - $rChk["fnQty"];
                    }
                    Else {
                        $rAdd["fnQty_Outstanding"] = $rAdd["fnQty"];
                        $Sisa = $Sisa - $rAdd["fnQty"];
                    }
                    $rAdd["fnIdFIFORef"] = 0;

                    $ssql="UPDATE TXStockFIFO
                            SET fnQty_OutStanding='{$rAdd["fnQty_Outstanding"]}', fnIdFIFORef=0,
                                ftModified_User='{$_SESSION['username']}', fdModified_Date=Now()
                            WHERE fnid='{$rAdd['fnId']}'";
                    mysql_query($ssql)   or die($ssql);
                    //pr("+:".$ssql);
                    #'Adjust FIFO untuk mengalihkan Referensi fnIdFIFORef, dari fnIdFIFORef yang lama ke yang baru
                    FIFOAdj($rAdd["ftBranch_Code"], $rAdd["fnIndex"], $rAdd["ftItem_Code"], $rAdd["ftWarehouse_Code"], $rAdd["ftWarehouse_Code"], $rAdd["ftBarcode"], $rAdd["fnUnique_Barcode"],"");

                }
            }

        } Else {
            #'Jika Qty <= 0, Berarti Record yang datanya diambil diatas adalah Record FIFO Out
            //pr("-fiforef:".$rChk["fnIdFIFORef"]);
            If($rChk["fnIdFIFORef"]!= 0) {
                #'Ambil Record yang menjadi Referensi Record FIFO Out, agar nilainya dikembalikan seperti semula
                $strSQL = "SELECT * FROM TXStockFIFO WHERE ftBranch_Code = '" . $strBranchCode . "' AND fnIdFIFO = " . $rChk["fnIdFIFORef"];
                //pr("-:".$strSQL);
                $rsAdd= mysql_query($strSQL);
                #'Update Nilai Field fnQty_OutStanding Record yang menjadi Referensi Record FIFO Out Diatas
                $rAdd=mysql_fetch_assoc($rsAdd);
                $rAdd["fnQty_Outstanding"] = $rAdd["fnQty_Outstanding"] + Abs($rChk["fnQty"]);
                $ssql="UPDATE TXStockFIFO
                        SET fnQty_OutStanding='{$rAdd["fnQty_Outstanding"]}',
                            ftModified_User='{$_SESSION['username']}', fdModified_Date=Now()
                        WHERE fnid='{$rAdd['fnId']}'";
                //pr("-:".$ssql);
                mysql_query($ssql)   or die($ssql);
            }
        }

        #'Set Flag Batal pada Record FIFO
        $ssql="UPDATE TXStockFIFO
                SET fnStatus = 9, fnQty_Outstanding = 0, ftModified_User='{$_SESSION['username']}', fdModified_Date=Now()
                WHERE ftBranch_Code = '" . $strBranchCode . "' AND fnIdFIFO = " . $rChk["fnIdFIFO"];
        mysql_query($ssql)   or die($ssql);

    }
}

#'Function: to Get Total COGS value from one transaction
Function GetFIFOValue($strBranchCode, $strDocumentNo, $strItemCode = "", $strTableRef = "", $strItemIndex = "") {
    // Jika table mutasi ke barang jadi, hanya perlu pilih qty > 0
    if (($strTableRef == "txstock_mutation_det_bbtobj") || ($strTableRef == "txstock_mutation_det_sptobj")) {
        $where = " AND fnqty > 0 ";
    }  
    
    if ($strItemIndex != "") {
        $where = $where . " AND fnindex = $strItemIndex ";
    }  
    
    If ($strItemCode == "")  {
        #'Jika Item Code Kosong -> Summary Berdasarkan No. Dokumen
        pr("SELECT IFNULL(SUM(ABS(fnQty)*fcNet_Price),0) AS fcCOGS FROM TXStockFIFO WHERE fnstatus <> 9 " . $where . " AND ftDocument_No = '" . $strDocumentNo . "' AND ftBranch_Code = '" . $strBranchCode . "'");
        $GetFIFOValue = RetRstField("SELECT IFNULL(SUM(ABS(fnQty)*fcNet_Price),0) AS fcCOGS FROM TXStockFIFO WHERE fnstatus <> 9 " . $where . " AND ftDocument_No = '" . $strDocumentNo . "' AND ftBranch_Code = '" . $strBranchCode . "'");
    }
    ElseIf ($strItemCode != "") {
        #'Jika Item Code tidak kosong -> Summary Berdasarkan Item Code
        pr("SELECT IFNULL(SUM(ABS(fnQty)*fcNet_Price),0) AS fcCOGS FROM TXStockFIFO WHERE fnstatus <> 9 " . $where . " AND ftDocument_No = '" . $strDocumentNo . "' AND ftItem_Code = '" . $strItemCode . "' AND ftBranch_Code = '" . $strBranchCode . "'");
        $GetFIFOValue = RetRstField("SELECT IFNULL(SUM(ABS(fnQty)*fcNet_Price),0) AS fcCOGS FROM TXStockFIFO WHERE fnstatus <> 9 " . $where . " AND ftDocument_No = '" . $strDocumentNo . "' AND ftItem_Code = '" . $strItemCode . "' AND ftBranch_Code = '" . $strBranchCode . "'");
    }
    
    return $GetFIFOValue;
}


#'Function: to Get Price/COGS value
Function GetFIFOPrice($strBranchCode, $strItemCode, $strWarehouseCode, $strBatchCode = "") {
    if ($strBranchCode == "") {
        $strBranchCode = "PUSAT";
    }  
    
    if ($strBatchCode != "") {
        $whereBatchCode = " AND ftbatch_code = '{$strBatchCode}' ";
    }  
      
    // pr("SELECT IFNULL(fcNet_Price,0) AS fcCOGS FROM TXStockFIFO WHERE fnstatus <> 9 " . $where . " AND ftDocument_No = '" . $strDocumentNo . "' AND ftItem_Code = '" . $strItemCode . "' AND ftBranch_Code = '" . $strBranchCode . "'");  AND CASE WHEN (psupplier='SELURUH') THEN 1=1 ELSE a.ftstock_in_company = psupplier END 
    $GetFIFOPrice = RetRstField("SELECT IFNULL(fcNet_Price,0) AS fcCOGS FROM TXStockFIFO WHERE fnstatus <> 9 AND ftwarehouse_code = '" . $strWarehouseCode . "' AND ftItem_Code = '" . $strItemCode . "' AND ftBranch_Code = '" . $strBranchCode . "'" . $whereBatchCode . " AND fnqty_outstanding > 0 ORDER BY fnidfifo ");
    
    if ($GetFIFOPrice == "") {
        $GetFIFOPrice = 0;
    }  
    
    return $GetFIFOPrice;
}

#'Function: to Get Price/COGS value from one item
Function GetFIFOPriceValue($strBranchCode, $strDocumentNo, $strItemCode, $strTableRef = "") {
    // Jika table mutasi ke barang jadi, hanya perlu pilih qty > 0
    if (($strTableRef == "txstock_mutation_det_bbtobj") || ($strTableRef == "txstock_mutation_det_sptobj")) {
        $where = " AND fnqty > 0 ";
    }  
    
    // pr("SELECT IFNULL(fcNet_Price,0) AS fcCOGS FROM TXStockFIFO WHERE fnstatus <> 9 " . $where . " AND ftDocument_No = '" . $strDocumentNo . "' AND ftItem_Code = '" . $strItemCode . "' AND ftBranch_Code = '" . $strBranchCode . "'");
    $GetFIFOPriceValue = RetRstField("SELECT IFNULL(fcNet_Price,0) AS fcCOGS FROM TXStockFIFO WHERE fnstatus <> 9 " . $where . " AND ftDocument_No = '" . $strDocumentNo . "' AND ftItem_Code = '" . $strItemCode . "' AND ftBranch_Code = '" . $strBranchCode . "'");
    
    if ($GetFIFOPriceValue == '') { $GetFIFOPriceValue=0; }
    
    return $GetFIFOPriceValue;
}

#'Function: to Get Last Price/COGS value from one item
Function GetLastPriceValue($strBranchCode, $strItemCode) {
    
    // pr("SELECT IFNULL(fcNet_Price,0) AS fcCOGS FROM TXStockFIFO WHERE fnstatus != 9 AND fnqty > 0 AND fcnet_price != 0 AND ftItem_Code = '" . $strItemCode . "' AND ftBranch_Code = '" . $strBranchCode . "' ORDER BY fnidfifo DESC ");
    $GetLastPriceValue = RetRstField("SELECT IFNULL(fcNet_Price,0) AS fcCOGS FROM TXStockFIFO WHERE fnstatus <> 9 AND fnqty > 0 AND fcnet_price != 0 AND ftItem_Code = '" . $strItemCode . "' AND ftBranch_Code = '" . $strBranchCode . "' ORDER BY fnidfifo DESC ");
    
    if ($GetLastPriceValue == '') { $GetLastPriceValue=0; }
    return $GetLastPriceValue;
}



