<?php
// Internal Setting
$PBAutoPI = RetRstField("SELECT ftvalue FROM tssys_setting WHERE ftsys_code = 'PUR01'");
$fnpo_type=RetRstField("select fnpo_type from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
    
switch($_REQUEST[mode]) {
    case "batal":
        if ($PBAutoPI && ($fnpo_type==0)) {
            /* Tidak digunakan karena PB dan PI satu set. Kalau batal PI Saja, tdk bisa auto create PI dari PB
            $ssql="select ftpurchase_invoice_no,ftstock_in_no
                    from txpurchase_invoice_hdr
                    where fnstatus=1 and ftstock_in_no='{$_REQUEST['ftstock_in_no']}'";
            $rs=mysql_query($ssql);
            $r=mysql_fetch_assoc($rs);
            if(RetRstField($ssql)) {
                    $id=RetRstField("select fnid from txstock_in_hdr where ftstock_in_no ='{$_REQUEST['ftstock_in_no']}'");
                    $url = $_SERVER["PHP_SELF"];
                    $form = $_REQUEST["form"];
                    echo "<script>
                            alert('No. Invoice : {$r['ftpurchase_invoice_no']} harus dibatalkan dulu ...');
                            window.location='{$url}?form={$form}&mode=edit&id=$id';
                        </script>";
                    die("");
            }
            */
            
            // validasi apakah sudah ada pembayaran invoice            
            $ssql="select a.ftcvs_no,b.ftpi_no
                    from txrecap_bank_voucher_hdr a, txrecap_bank_voucher_det b
                    where a.ftcvs_no=b.ftcvs_no and a.fnstatus<>9 and a.fnstatus<>3
                            and b.ftpi_no='{$_REQUEST['ftpurchase_invoice_no']}'";

            $rs=mysql_query($ssql);
            $str="No. Transaksi Pembayaran Hutang ini harus dibatal kan dahulu :";
            while($r=mysql_fetch_assoc($rs)) {
                $str.=$r['ftcvs_no'];
            }

            if(RetRstField($ssql)) {
                echo "<script> alert('$str'); window.history.back(); </script>";
                die("");
            }

            // validasi apakah sudah ada transaksi retur berkaitan dengan invoice ini            
            $ssql="select ftpurchase_return_no 
                    from txpurchase_return_hdr
                    where fnstatus<>9 and fnstatus<>3 AND ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}'";

            $rs=mysql_query($ssql) or die ("query error {$ssql}");
            while($r=mysql_fetch_assoc($rs)) {
               $ftpurchase_return_no.="- {$r['ftpurchase_return_no']}\\n";
            }
            
            if($ftpurchase_return_no!="") {
                $str="No. Transaksi Purchase Return ini harus dibatal kan dahulu : \\n";
                $str.=$ftpurchase_return_no;
                echo "<script>
                        alert('{$str}');
                        window.history.back();
                      </script>";
                die("");
            }           
        }
        break;
     
}

function ValCheckLocation() {
    for($j=1; $j<count($_REQUEST['fnindexD0']); $j++) {
        if ((CCur($_REQUEST['fnqty_baseD0'][$j]) > 0) && (CCur($_REQUEST['ftlocation_codeD0'][$j])=="")) {
            echo "<script>
                    alert('Lokasi harus diisi. ');
                    window.history.back();
                  </script>";
            die("");
        }
    }
}

function UpdateData() {
    global $objAxpDB;
    $objAxpDB->Allow_Update(false);
    ValCheckLocation();

    switch($_REQUEST[mode]) {
        case "update":
            for($j=1; $j<count($_REQUEST['fnindexD0']); $j++) {
                $ssql="UPDATE txstock_in_det
                        SET fnqty_reject = '".CCur($_REQUEST['fnqty_rejectD0'][$j])."',
                            ftmodified_user = '{$_SESSION['username']}',
                            fdmodified_date = NOW()
                        WHERE 
                            ftstock_in_no = '{$_REQUEST['ftstock_in_no']}' AND
                            ftitem_code = '{$_REQUEST['ftitem_codeD0'][$j]}'";

                $strSQL['UPDATE txstock_in_det'][]=$ssql;

                if($_REQUEST['DIRECT_EXECUTE_SQL']==1)
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
            }

        break;
    }

    return $strSQL;
}
    
function SaveData() {
    ValCheckLocation();
    global $objAxpDB;
    $objAxpDB->Allow_Save(false);
    // $objAxpDB->SetDirectExecuteSql(true);
    $strSQL=array();
    
    // Internal Setting
    $PBAutoPI = RetRstField("SELECT ftvalue FROM tssys_setting WHERE ftsys_code = 'PUR01'");
    
    $fnpo_type=RetRstField("select fnpo_type from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                
    switch($_REQUEST[mode]) {
        case "simpan":
            $ssql="INSERT INTO txstock_in_hdr
                        (
                            ftbranch_code,ftstock_in_no, ftstock_type_code, ftcategory_code,
                            fnpo_typelpb, ftstock_in_company,ftdocument_no,fdschedule_delivery_date,
                            fdtrans_date, ftreff_no, fttime_start, fttime_end,
                            ftcurrency_code,fcrate,
                            ftchecked_user, ftnotes,  fntotal_qty, fnstatus,ftcreated_user,
                            fdcreated_date,ftmodified_user,fdmodified_date
                        )
                            SELECT
                            '{$_SESSION['strbranch']}' AS ftbranch_code,'{$_REQUEST['ftstock_in_no']}' AS ftstock_in_no,'{$_REQUEST['ftstock_type_code']}' AS ftstock_type_code,'{$_REQUEST['ftcategory_code']}' AS ftcategory_code,
                            '{$_REQUEST['fnpo_typelpb']}' AS fnpo_typelpb,'{$_REQUEST['ftstock_in_company']}' AS ftstock_in_company,'{$_REQUEST['ftdocument_no']}' AS ftdocument_no,'".CDate($_REQUEST['fdschedule_delivery_date'])."' AS fdschedule_delivery_date,
                            '".CDate($_REQUEST['fdtrans_date'])."' AS fdtrans_date,'{$_REQUEST['ftreff_no']}' AS ftreff_no,'{$_REQUEST['fttime_start']}' AS fttime_start,'{$_REQUEST['fttime_end']}' AS fttime_end,
                            'IDR' AS ftcurrency_code,'1' AS fcrate,
                            '{$_REQUEST['ftchecked_user']}' AS ftchecked_user,'{$_REQUEST['ftnotes']}' AS ftnotes,'".CCur($_REQUEST['fntotal_qty'])."' AS fntotal_qty,'{$_REQUEST['fnstatus']}'  AS fnstatus,'{$_SESSION['username']}' AS ftcreated_user,
                            NOW() AS fdcreated_date,'{$_SESSION['username']}' AS ftmodified_user,NOW() AS fdmodified_date
                    ";
            $strSQL['INSERT txstock_in_hdr'][]=$ssql;
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
            }
            
            // auto insert purchase invoice for PO Local
            if ($PBAutoPI && ($fnpo_type==0)) {
                $ftpi_no=getAutoNumber($_SESSION['strbranch'],'TN113','txpurchase_invoice_hdr','ftpurchase_invoice_no',$_REQUEST['fdtrans_date']);
                $fnpo_type=RetRstField("select fnpo_type from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                $fntax_code=RetRstField("select fntax_code from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                $ftterm_payment=RetRstField("select ftterm_payment from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                $fddue_date=RetRstField("SELECT DATE_ADD('".CDate($_REQUEST['fdtrans_date'])."',INTERVAL {$ftterm_payment} DAY)");
                $ffvat=RetRstField("select ffvat from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                $ftsupplier_name=RetRstField("select ftsupplier_name from tlsupplier where ftsupplier_code='".$_REQUEST['ftstock_in_company']."'");

                $ssql="INSERT INTO txpurchase_invoice_hdr
                            (
                                ftbranch_code,ftpurchase_invoice_no, ftstock_in_no, ftpo_no, fnpo_type, 
                                ftsupplier_code,ftsupplier_name,fntax_code,
                                fdtrans_date, fddue_date, ftterm_payment, ftcurrency_code,fcrate,
                                ffvat, ftnotes, fnstatus,fnpayment_status,
                                ftcreated_user,fdcreated_date,ftmodified_user,fdmodified_date
                            )
                                SELECT
                                '{$_SESSION['strbranch']}' AS ftbranch_code,'{$ftpi_no}' AS ftpurchase_invoice_no,'{$_REQUEST['ftstock_in_no']}' AS ftstock_in_no,'{$_REQUEST['ftdocument_no']}' AS ftpo_no,'{$fnpo_type}' AS fnpo_type,
                                '{$_REQUEST['ftstock_in_company']}' AS ftsupplier_code,'{$ftsupplier_name}' AS ftsupplier_name,'{$fntax_code}' AS fntax_code,
                                '".CDate($_REQUEST['fdtrans_date'])."' AS fdtrans_date,'{$fddue_date}' AS fddue_date,'{$ftterm_payment}' AS ftterm_payment,'{$_REQUEST['ftcurrency_code']}' AS ftcurrency_code,'".CCur($_REQUEST['fcrate'])."' AS fcrate,
                                '{$ffvat}' AS ffvat,'{$_REQUEST['ftnotes']}' AS ftnotes,'{$_REQUEST['fnstatus']}'  AS fnstatus,'1' AS fnpayment_status,
                                '{$_SESSION['username']}' AS ftcreated_user,NOW() AS fdcreated_date,'{$_SESSION['username']}' AS ftmodified_user,NOW() AS fdmodified_date
                        ";

                $strSQL['INSERT txpurchase_invoice_hdr'][]=$ssql;
                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                }
            } 

            $jx=0;
            for($j=1; $j<count($_REQUEST['fnindexD0']); $j++) {
                $jx++;
                $ftitem_name=RetRstField("select ftitem_name from tlstock_hdr where ftitem_code='{$_REQUEST['ftitem_codeD0'][$j]}'");
                
                $ssql="INSERT INTO txstock_in_det
                            (
                                ftbranch_code,ftstock_in_no,fnindex, ftitem_code,ftitem_name,ftdescription,
                                ftwarehouse_code, ftlocation_code, fnqtypo,fnqtypo_base,fnqtysisapo,
                                fnqtysisapo_base, fnqty,fnqty_base, ftuom_code,ffformula,
                                fnindex_po,fnqty_reject,fcprice,fcselling_price,ftcreated_user,fdcreated_date,
                                ftmodified_user,fdmodified_date
                            )
                                SELECT  '{$_SESSION['strbranch']}' AS ftbranch_code,'{$_REQUEST['ftstock_in_no']}' AS ftstock_in_no,'{$jx}' AS fnindex,'{$_REQUEST['ftitem_codeD0'][$j]}' AS ftitem_code,'{$ftitem_name}' AS ftitem_name, '{$_REQUEST['ftdescriptionD0'][$j]}' AS ftdescription,
                                '{$_REQUEST['ftwarehouse_codeD0'][$j]}' AS ftwarehouse_code,'{$_REQUEST['ftlocation_codeD0'][$j]}' AS ftlocation_code,'".CCur($_REQUEST['fnqtypoD0'][$j])."' AS fnqtypo,'".CCur($_REQUEST['fnqtypo_baseD0'][$j])."' AS fnqtypo_base,'".CCur($_REQUEST['fnqtysisapoD0'][$j])."' AS fnqtysisapo,
                                '".CCur($_REQUEST['fnqtysisapo_baseD0'][$j])."' AS fnqtysisapo_base,'".CCur($_REQUEST['fnqtyD0'][$j])."' AS fnqty,'".CCur($_REQUEST['fnqty_baseD0'][$j])."' AS fnqty_base,'{$_REQUEST['ftuom_codeD0'][$j]}' AS ftuom_code,'".CCur($_REQUEST['ffformulaD0'][$j])."' AS ffformula,
                                '{$_REQUEST['fnindex_poD0'][$j]}' AS fnindex_po,'".CCur($_REQUEST['fnqty_rejectD0'][$j])."' AS fnqty_reject,'".CCur($_REQUEST['fcpriceD0'][$j])."' AS fcprice,'".CCur($_REQUEST['fcselling_priceD0'][$j])."' AS fcselling_price,'{$_SESSION['username']}' AS ftcreated_user,now() AS fdcreated_date,
                                '{$_SESSION['username']}' AS ftmodified_user,NOW() AS fdmodified_date";
                
                $strSQL['INSERT txstock_in_det'][]=$ssql;
               
                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                }
                
                // auto insert txpurchase_invoice_no
                if ($PBAutoPI && ($fnpo_type==0)) {
                    $fcprice=RetRstField("select fcprice from txpurchase_order_det where ftpo_no='".$_REQUEST['ftdocument_no']."' AND fnindex='{$jx}' AND ftitem_code='".$_REQUEST['ftitem_codeD0'][$j]."'");
                    $fcamount = CCur($_REQUEST['fnqtyD0'][$j]) * $fcprice;
                    $fcprice_cogs = $fcprice;

                    $ssql="INSERT INTO txpurchase_invoice_det
                                (
                                    ftbranch_code,ftpurchase_invoice_no,ftstock_in_no,fnindex, ftitem_code,ftitem_name,
                                    fnqty, fnqty_base, ftuom_code,ffformula,fcprice, 
                                    ffdiscount, fcdiscount, fcamount, fcprice_cogs,
                                    ftcreated_user,fdcreated_date,ftmodified_user,fdmodified_date
                                )
                                    SELECT  '{$_SESSION['strbranch']}' AS ftbranch_code,'{$ftpi_no}' AS ftpurchase_invoice_no,'{$_REQUEST['ftstock_in_no']}' AS ftstock_in_no,'{$jx}' AS fnindex,'{$_REQUEST['ftitem_codeD0'][$j]}' AS ftitem_code,'{$ftitem_name}' AS ftitem_name,
                                    '".CCur($_REQUEST['fnqtyD0'][$j])."' AS fnqty,'".CCur($_REQUEST['fnqty_baseD0'][$j])."' AS fnqty_base,'{$_REQUEST['ftuom_codeD0'][$j]}' AS ftuom_code,'".CCur($_REQUEST['ffformulaD0'][$j])."' AS ffformula,'{$fcprice}' AS fcprice,
                                    '".CCur($_REQUEST['ffdiscountD0'][$j])."' AS ffdiscount,'".CCur($_REQUEST['fcdiscountD0'][$j])."' AS fcdiscount,'{$fcamount}' AS fcamount,'{$fcprice_cogs}' AS fcprice_cogs,
                                    '{$_SESSION['username']}' AS ftcreated_user,now() AS fdcreated_date,'{$_SESSION['username']}' AS ftmodified_user,NOW() AS fdmodified_date";

                    $strSQL['INSERT txpurchase_invoice_det'][]=$ssql;

                    if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                        mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                    }
                }
                
                // Update Harga Jual           
                /*$ssql="UPDATE tlselling_price SET
                        fcold_selling_price=fcselling_price,
                        fcselling_price='".CCur($_REQUEST['fcselling_priceD0'][$j])."',
                        ftmodified_user='{$_SESSION['username']}',fdmodified_date=now()
                        WHERE ftitem_code='{$_REQUEST['ftitem_codeD0'][$j]}' AND
                        ftcurrency_code='IDR' AND
                        fcselling_price<>".CCur($_REQUEST['fcselling_priceD0'][$j])."";      
                $strSQL['UPDATE tlselling_price'][]=$ssql;
                
                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                } */
            }				

            for($j=1; $j<count($_REQUEST['ftitem_codeD0']); $j++) {
                if ($_REQUEST['ftstock_type_code'] == 'invbb') {
                    $m=SaveStock_bahan_baku('+',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j],'',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                } else if ($_REQUEST['ftstock_type_code'] == 'invsj') {
                    $m=SaveStock_setengah_jadi('+',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j],'',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                } else if ($_REQUEST['ftstock_type_code'] == 'invsp') {
                    $m=SaveStock_sparepart('+',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j],'',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                } else if ($_REQUEST['ftstock_type_code'] == 'inv') {
                    $m=SaveStock('+',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j], '',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                }

                $strSQL=array_merge_recursive($strSQL,$m);
                
            }
            
            $jj=0;
            if($_REQUEST['ftcategory_code']=='0') {
                for($j=1; $j<count($_REQUEST['ftitem_codeD0']); $j++) {
                    if(CCur($_REQUEST['fnqtyD0'][$j])>0){
                        $jj=$jj+1;
                        $ssql="UPDATE txpurchase_order_det
                                SET fnqty_accept_base=IFNULL(fnqty_accept_base,0)+ ".(double)CCur($_REQUEST['fnqty_baseD0'][$j]).",
                                    fnqty_accept= IFNULL(fnqty_accept,0)+ (".(double)CCur($_REQUEST['fnqty_baseD0'][$j])."/ffformula)
                                WHERE ftpo_no='{$_REQUEST['ftdocument_no']}' AND
                                    ftitem_code='{$_REQUEST['ftitem_codeD0'][$j]}' AND
                                    fnindex='{$_REQUEST['fnindex_poD0'][$j]}' ";
                        $strSQL['Update txpurchase_order_det'][]=$ssql;
                       
                        if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                        }
                    }
                }
            }

            break;
    }
    return $strSQL;
}

function SaveDataAfter() {
        
    global $objAxpDB;
    $objAxpDB->Allow_Save(true);
    $strSQL=array();

    // Internal Setting
    $PBAutoPI = RetRstField("SELECT ftvalue FROM tssys_setting WHERE ftsys_code = 'PUR01'");

    $fnpo_type=RetRstField("select fnpo_type from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
      
    switch($_REQUEST[mode]) {
        case "simpan":
            // delete item with qty 0
            $ssql="DELETE FROM txstock_in_det WHERE fnqty=0 AND ftstock_in_no='{$_REQUEST['ftstock_in_no']}' ";
            $strSQL['Stock Masuk Index'][]= $ssql;
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
            }

            // reindex item detail
            $ssql=" update txstock_in_det a,
                        (select c.fnid,(select ifnull(count(d.fnid),0)+1
                                        from txstock_in_det d
                                        where d.fnid < c.fnid and d.ftstock_in_no='{$_REQUEST['ftstock_in_no']}') as m
                                from  txstock_in_det c
                                where c.ftstock_in_no='{$_REQUEST['ftstock_in_no']}') b
                    set a.fnindex=b.m
                    where a.ftstock_in_no='{$_REQUEST['ftstock_in_no']}' and a.fnid=b.fnid";

            $strSQL['Stock Masuk Index'][]= $ssql;
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
            }
            
            mysql_query("UPDATE txpurchase_order_det SET fnstatus=5 WHERE ftpo_no='{$_REQUEST['ftdocument_no']}' AND fnqty_accept >= fnqty");
              
            // set status terkirim
            $ssql="UPDATE txpurchase_order_hdr a INNER JOIN ( 
                        SELECT b.ftpo_no, COUNT(a.fnid) AS total_item, COUNT(c.fnindex) AS total_item_closed, fnreceipt_status
                        FROM txpurchase_order_det a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no=b.ftpo_no
                        LEFT JOIN txpurchase_order_det c ON c.ftpo_no=a.ftpo_no AND c.fnindex=a.fnindex AND c.fnstatus = 5
                        WHERE b.fnstatus = 1 GROUP BY b.ftpo_no
                        HAVING total_item = total_item_closed AND fnreceipt_status != 3 ) b 
                    SET a.fnreceipt_status = 3 WHERE a.ftpo_no = b.ftpo_no; ";
            $strSQL["Update txpurchase_order_hdr Receipt1"][]=$ssql;
            
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                if($ssql2!="")
                   mysql_query($ssql2) or die("SQL ERROR :{$ssql}");
            }
            
            // set status sebagian
            $ssql="UPDATE txpurchase_order_hdr a INNER JOIN ( 
                        SELECT b.ftpo_no, COUNT(a.fnid) AS total_item, COUNT(c.fnindex) AS total_item_closed, fnreceipt_status
                        FROM txpurchase_order_det a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no=b.ftpo_no
                        LEFT JOIN txpurchase_order_det c ON c.ftpo_no=a.ftpo_no AND c.fnindex=a.fnindex AND c.fnstatus = 5
                        WHERE b.fnstatus = 1 GROUP BY b.ftpo_no
                        HAVING total_item != total_item_closed AND total_item_closed != 0 AND fnreceipt_status != 2 ) b
                    SET a.fnreceipt_status = 2 WHERE a.ftpo_no = b.ftpo_no; ";
            $strSQL["Update txpurchase_order_hdr Receipt2"][]=$ssql;
            
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                if($ssql2!="")
                   mysql_query($ssql2) or die("SQL ERROR :{$ssql}");
            }
            
            // set status belum dikirim
            $ssql="UPDATE txpurchase_order_hdr a INNER JOIN ( 
                        SELECT b.ftpo_no, COUNT(a.fnid) AS total_item, COUNT(c.fnindex) AS total_item_closed, fnreceipt_status
                        FROM txpurchase_order_det a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no=b.ftpo_no
                        LEFT JOIN txpurchase_order_det c ON c.ftpo_no=a.ftpo_no AND c.fnindex=a.fnindex AND c.fnstatus = 5
                        WHERE b.fnstatus = 1 GROUP BY b.ftpo_no
                        HAVING total_item_closed = 0 AND fnreceipt_status != 1 ) b
                SET a.fnreceipt_status = 1 WHERE a.ftpo_no = b.ftpo_no; ";
            $strSQL["Update txpurchase_order_hdr Receipt3"][]=$ssql;
            
            $ssql2="UPDATE txpurchase_order_schedule_delivery a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no = b.ftpo_no
                        SET a.fnlock = 1 WHERE a.fnlock != 1 AND b.fnreceipt_status = 3; ";
            $strSQL["Update txpurchase_order_hdr Receipt4"][]=$ssql2;
                
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                if($ssql2!="")
                   mysql_query($ssql2) or die("SQL ERROR :{$ssql}");
            }
      
            // Update Purchase Invoice Amount
            if ($PBAutoPI && ($fnpo_type==0)) {
                $fcsub_amount=RetRstField("SELECT IFNULL(SUM(a.fcamount),0) AS fcamount FROM txpurchase_invoice_det a, txpurchase_invoice_hdr b WHERE a.ftpurchase_invoice_no = b.ftpurchase_invoice_no AND b.ftstock_in_no = '{$_REQUEST['ftstock_in_no']}'");                 
                $ffvat=RetRstField("select ffvat from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                $fcvat = ($ffvat / 100) * $fcsub_amount;
                $fcamount = $fcsub_amount + $fcvat;

                $ssql="UPDATE txpurchase_invoice_hdr a 
                        SET a.fcsub_amount='{$fcsub_amount}', a.fcvat = '{$fcvat}', a.fcamount='{$fcamount}',
                                a.fcpayment_amount='0',a.fcoutstanding_amount='{$fcamount}', a.fcreturn_amount='0'  
                        WHERE a.ftstock_in_no='{$_REQUEST['ftstock_in_no']}'";
                $strSQL["Update Purchase Invoice Amount"][]=$ssql;

                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                }                                                
                break;
            }    
    }
    return $strSQL;
}


function CancelData() {
    // initialize variable for multiple tables
    $tablename = "";

    if($_REQUEST['ftstock_type_code'] == 'invbb') {
        $tablename = "_bahan_baku";
    } elseif ($_REQUEST['ftstock_type_code'] == 'invsj') {
        $tablename = "_setengah_jadi";
    } elseif ($_REQUEST['ftstock_type_code'] == 'invsp') {
        $tablename = "_sparepart";
    } elseif ($_REQUEST['ftstock_type_code'] == 'inv') {
        $tablename = "";
    }

    global $objAxpDB;
    //$objAxpDB->Allow_Cancel(false);
    // $objAxpDB->SetDirectExecuteSql(true);
    $strSQL=array();
    
    // Internal Setting
    $PBAutoPI = RetRstField("SELECT ftvalue FROM tssys_setting WHERE ftsys_code = 'PUR01'");

    $fnpo_type=RetRstField("select fnpo_type from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
    
    switch($_REQUEST[mode]) {
        case "batal":       

            for($j=1; $j<count($_REQUEST['ftitem_codeD0']); $j++) {
                if ($tablename == '_bahan_baku')
                   $m=SaveStock_bahan_baku('-',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j],'',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                else if ($tablename == '_setengah_jadi')
                    $m=SaveStock_setengah_jadi('-',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j],'',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                else if ($tablename == '_sparepart')
                    $m=SaveStock_sparepart('-',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j],'',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                else if ($tablename == '')
                    $m=SaveStock('-',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j],'',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));

                $strSQL=array_merge_recursive($strSQL,$m);
            }

            if($_REQUEST['ftcategory_code']=='0') {
                for($j=1; $j<count($_REQUEST['ftitem_codeD0']); $j++) {
                    $ssql="UPDATE txpurchase_order_det
                            SET fnqty_accept_base=IFNULL(fnqty_accept_base,0)- ".(double)CCur($_REQUEST['fnqty_baseD0'][$j])." ,
                                fnqty_accept=IFNULL(fnqty_accept,0)- (".(double)CCur($_REQUEST['fnqty_baseD0'][$j])."/ffformula) , fnstatus = 1
                            WHERE ftpo_no='{$_REQUEST['ftdocument_no']}'  AND ftitem_code='{$_REQUEST['ftitem_codeD0'][$j]}'  
                                AND fnindex='{$_REQUEST['fnindex_poD0'][$j]}' ";

                    $strSQL['Update txpurchase_order_det'][]=$ssql;
                    if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                        mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                    }
                }
            }
            
            // Cancel PI
            if ($PBAutoPI && ($fnpo_type==0)) {
                $ssql="UPDATE txpurchase_invoice_hdr a SET a.fnstatus = 9 WHERE a.ftstock_in_no='{$_REQUEST['ftstock_in_no']}'";
                $strSQL["Update Purchase Invoice Status"][]=$ssql;

                $strSQL["Update Jurnal Status"][]="UPDATE txgeneral_journal_hdr a INNER JOIN txpurchase_invoice_hdr b ON a.ftdocument_no=b.ftpurchase_invoice_no SET a.fnstatus = 9  WHERE b.ftstock_in_no='{$_REQUEST['ftstock_in_no']}'";               


                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                }                                                
            }    

            break;
    }

    return $strSQL;
}
    
function CancelDataLast() {
    // initialize variable for multiple tables
    $tablename = "";

    if($_REQUEST['fnpo_type3'] == '0') {
        $tablename = "_bahan_baku";
    } elseif ($_REQUEST['fnpo_type3'] == '1') {
        $tablename = "_setengah_jadi";
    } elseif ($_REQUEST['fnpo_type3'] == '2') {
        $tablename = "_sparepart";
    } elseif ($_REQUEST['fnpo_type3'] == '3') {
        $tablename = "";
    }

    global $objAxpDB;
    // $objAxpDB->Allow_Cancel(false);
    $strSQL=array();
    switch($_REQUEST[mode]) {
        case "batal":
           
            // set status terkirim
            $ssql="UPDATE txpurchase_order_hdr a INNER JOIN ( 
                        SELECT b.ftpo_no, COUNT(a.fnid) AS total_item, COUNT(c.fnindex) AS total_item_closed, fnreceipt_status
                        FROM txpurchase_order_det a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no=b.ftpo_no
                        LEFT JOIN txpurchase_order_det c ON c.ftpo_no=a.ftpo_no AND c.fnindex=a.fnindex AND c.fnstatus = 5
                        WHERE b.ftpo_no='{$_REQUEST['ftdocument_no']}' GROUP BY b.ftpo_no
                        HAVING total_item = total_item_closed AND fnreceipt_status != 3 ) b 
                    SET a.fnreceipt_status = 3, a.fnstatus = 1 WHERE a.ftpo_no = b.ftpo_no; ";
            $strSQL["Update txpurchase_order_hdr Receipt1"][]=$ssql;
            
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                if($ssql2!="")
                   mysql_query($ssql2) or die("SQL ERROR :{$ssql}");
            }
            
            // set status sebagian
            $ssql="UPDATE txpurchase_order_hdr a INNER JOIN ( 
                        SELECT b.ftpo_no, COUNT(a.fnid) AS total_item, COUNT(c.fnindex) AS total_item_closed, fnreceipt_status
                        FROM txpurchase_order_det a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no=b.ftpo_no
                        LEFT JOIN txpurchase_order_det c ON c.ftpo_no=a.ftpo_no AND c.fnindex=a.fnindex AND c.fnstatus = 5
                        WHERE b.ftpo_no='{$_REQUEST['ftdocument_no']}' GROUP BY b.ftpo_no
                        HAVING total_item != total_item_closed AND total_item_closed != 0 AND fnreceipt_status != 2 ) b
                    SET a.fnreceipt_status = 2, a.fnstatus = 1 WHERE a.ftpo_no = b.ftpo_no; ";
            $strSQL["Update txpurchase_order_hdr Receipt2"][]=$ssql;
            
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                if($ssql2!="")
                   mysql_query($ssql2) or die("SQL ERROR :{$ssql}");
            }
            
            // set status belum dikirim
            $ssql="UPDATE txpurchase_order_hdr a INNER JOIN ( 
                        SELECT b.ftpo_no, COUNT(a.fnid) AS total_item, COUNT(c.fnindex) AS total_item_closed, fnreceipt_status
                        FROM txpurchase_order_det a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no=b.ftpo_no
                        LEFT JOIN txpurchase_order_det c ON c.ftpo_no=a.ftpo_no AND c.fnindex=a.fnindex AND c.fnstatus = 5
                        WHERE b.ftpo_no='{$_REQUEST['ftdocument_no']}' GROUP BY b.ftpo_no
                        HAVING total_item_closed = 0 AND fnreceipt_status != 1 ) b
                    SET a.fnreceipt_status = 1, a.fnstatus = 1 WHERE a.ftpo_no = b.ftpo_no; ";
            $strSQL["Update txpurchase_order_hdr Receipt3"][]=$ssql;
            
            $ssql2="UPDATE txpurchase_order_schedule_delivery a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no = b.ftpo_no
                        SET a.fnlock = 0 WHERE a.fnlock != 0 AND b.fnreceipt_status != 3; ";
            $strSQL["Update txpurchase_order_hdr Receipt4"][]=$ssql2;

            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                if($ssql2!="")
                   mysql_query($ssql2) or die("SQL ERROR :{$ssql}");
            }
       
        break;
    }

    return $strSQL;
}

 function RevisiData() {
    global $objAxpDB;
    #$objAxpDB->Allow_Revisi(false);
    // $objAxpDB->SetDirectExecuteSql(true);
    $strSQL=array();
    ValCheckLocation();
    
    // Internal Setting
    $PBAutoPI = RetRstField("SELECT ftvalue FROM tssys_setting WHERE ftsys_code = 'PUR01'");

    $fnpo_type=RetRstField("select fnpo_type from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
    
    switch($_REQUEST[mode]) {
        case "simpan_revisi":
            // batal -%
            $ssql1="SELECT IFNULL(MAX(ftstock_in_no),'')  AS M
                      FROM txstock_in_hdr
                      WHERE ftstock_in_no LIKE '{$_REQUEST['ftstock_in_no']}-%'";
            $no=RetRstField($ssql1);
            
            if($no!="") {
                $no1=explode("-",$no);
                $i=count($no1)-1;
                $no=(int)$no1[$i]+1;
                $str1="-{$no}";
            
            } else {
                $str1="-1";
            }

            $ftstock_in_no_new="{$_REQUEST['ftstock_in_no']}{$str1}";
            
            $ssql="update txstock_in_hdr
                    set fnstatus= 9 ,ftmodified_user='{$_SESSION['username']}',
                         fdmodified_date=now(),ftstock_in_no='{$ftstock_in_no_new}'
                    where ftstock_in_no='{$_REQUEST['ftstock_in_no']}'";
            $strSQL["revisi"][]=$ssql;
            
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                 mysql_query($ssql) or die("SQL ERROR :{$ssql}");
            }
            
            $ssql="update txstock_in_det
                    set ftstock_in_no='{$ftstock_in_no_new}'
                    where ftstock_in_no='{$_REQUEST['ftstock_in_no']}'";
            $strSQL["revisi"][]=$ssql;
            
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                 mysql_query($ssql) or die("SQL ERROR :{$ssql}");
            }
            
            // Pengembalian Stock transaksi lama              
            $rs=mysql_query("SELECT * FROM txstock_in_det WHERE ftstock_in_no='{$ftstock_in_no_new}'");
            while($r=mysql_fetch_assoc($rs)) {
                $m=SaveStock('-',$r['ftitem_code'],'',$r['ftwarehouse_code'],$r['ftlocation_code'],'',$r['fnqty_base'],$r['fnqty_base']);
                $strSQL=array_merge_recursive($strSQL,$m);
            }
            
            // Revisi No PI
            if ($PBAutoPI && ($fnpo_type==0)) {
                // batal -%
                $ftpi_no=RetRstField("SELECT ftpurchase_invoice_no FROM txpurchase_invoice_hdr WHERE ftstock_in_no = '{$_REQUEST['ftstock_in_no']}' ");

                $ssql1="SELECT IFNULL(MAX(ftpurchase_invoice_no),'')  AS M
                          FROM txpurchase_invoice_hdr
                          WHERE ftpurchase_invoice_no LIKE '{$ftpi_no}-%'";
                $no=RetRstField($ssql1);

                if($no!="") {
                    $no1=explode("-",$no);
                    $i=count($no1)-1;
                    $no=(int)$no1[$i]+1;
                    $str1="-{$no}";
                } else {
                    $str1="-1";
                }

                $ftpi_no_new="{$ftpi_no}{$str1}";
                $fttrans_no_new = $ftpi_no_new;
                        
                $ssql="UPDATE txpurchase_invoice_hdr a 
                        SET a.fnstatus = 9, ftstock_in_no='{$ftstock_in_no_new}', ftpurchase_invoice_no='{$ftpi_no_new}', 
                            ftmodified_user='{$_SESSION['username']}', fdmodified_date=now()
                        WHERE a.ftpurchase_invoice_no='{$ftpi_no}'";
                $strSQL["revisi"][]=$ssql;

                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                }              
                
                $ssql="UPDATE txpurchase_invoice_det a 
                        SET ftpurchase_invoice_no='{$ftpi_no_new}', ftstock_in_no='{$ftstock_in_no_new}', ftmodified_user='{$_SESSION['username']}', fdmodified_date=now()
                        WHERE a.ftpurchase_invoice_no='{$ftpi_no}'";
                $strSQL["revisi"][]=$ssql;

                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                }     
                
                // insert PI header
                $fnpo_type=RetRstField("select fnpo_type from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                $fntax_code=RetRstField("select fntax_code from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                $ftterm_payment=RetRstField("select ftterm_payment from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                $fddue_date=RetRstField("SELECT DATE_ADD('".CDate($_REQUEST['fdtrans_date'])."',INTERVAL {$ftterm_payment} DAY)");
                $ffvat=RetRstField("select ffvat from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                $ftsupplier_name=RetRstField("select ftsupplier_name from tlsupplier where ftsupplier_code='".$_REQUEST['ftstock_in_company']."'");
                $fcrate=RetRstField("select fcrate from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");

                $ssql="INSERT INTO txpurchase_invoice_hdr
                            (
                                ftbranch_code,ftpurchase_invoice_no, ftstock_in_no, ftpo_no, fnpo_type, 
                                ftsupplier_code,ftsupplier_name,fntax_code,
                                fdtrans_date, fddue_date, ftterm_payment, ftcurrency_code,fcrate,
                                ffvat, ftnotes, fnstatus,fnpayment_status,
                                ftcreated_user,fdcreated_date,ftmodified_user,fdmodified_date
                            )
                                SELECT
                                '{$_SESSION['strbranch']}' AS ftbranch_code,'{$ftpi_no}' AS ftpurchase_invoice_no,'{$_REQUEST['ftstock_in_no']}' AS ftstock_in_no,'{$_REQUEST['ftdocument_no']}' AS ftpo_no,'{$fnpo_type}' AS fnpo_type,
                                '{$_REQUEST['ftstock_in_company']}' AS ftsupplier_code,'{$ftsupplier_name}' AS ftsupplier_name,'{$fntax_code}' AS fntax_code,
                                '".CDate($_REQUEST['fdtrans_date'])."' AS fdtrans_date,'{$fddue_date}' AS fddue_date,'{$ftterm_payment}' AS ftterm_payment,'{$_REQUEST['ftcurrency_code']}' AS ftcurrency_code,'{$fcrate}' AS fcrate,
                                '{$ffvat}' AS ffvat,'{$_REQUEST['ftnotes']}' AS ftnotes,'{$_REQUEST['fnstatus']}'  AS fnstatus,'1' AS fnpayment_status,
                                '{$_SESSION['username']}' AS ftcreated_user,NOW() AS fdcreated_date,'{$_SESSION['username']}' AS ftmodified_user,NOW() AS fdmodified_date
                        ";

                $strSQL['INSERT txpurchase_invoice_hdr'][]=$ssql;
                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                }
                
                $jx=0;
                for($j=1; $j<count($_REQUEST['fnindexD0']); $j++) {
                    $jx++;
                    $ftitem_name=RetRstField("select ftitem_name from tlstock_hdr where ftitem_code='{$_REQUEST['ftitem_codeD0'][$j]}'");

                    // auto insert txpurchase_invoice_det
                    $fcprice=RetRstField("select fcprice from txpurchase_order_det where ftpo_no='".$_REQUEST['ftdocument_no']."' AND fnindex='{$jx}' AND ftitem_code='".$_REQUEST['ftitem_codeD0'][$j]."'");
                    $fcamount = CCur($_REQUEST['fnqtyD0'][$j]) * $fcprice;
                    $fcprice_cogs = $fcprice;

                    $ssql="INSERT INTO txpurchase_invoice_det
                                (
                                    ftbranch_code,ftpurchase_invoice_no,ftstock_in_no,fnindex, ftitem_code,ftitem_name,
                                    fnqty, fnqty_base, ftuom_code,ffformula,fcprice, 
                                    ffdiscount, fcdiscount, fcamount, fcprice_cogs,
                                    ftcreated_user,fdcreated_date,ftmodified_user,fdmodified_date
                                )
                                    SELECT  '{$_SESSION['strbranch']}' AS ftbranch_code,'{$ftpi_no}' AS ftpurchase_invoice_no,'{$_REQUEST['ftstock_in_no']}' AS ftstock_in_no,'{$jx}' AS fnindex,'{$_REQUEST['ftitem_codeD0'][$j]}' AS ftitem_code,'{$ftitem_name}' AS ftitem_name,
                                    '".CCur($_REQUEST['fnqtyD0'][$j])."' AS fnqty,'".CCur($_REQUEST['fnqty_baseD0'][$j])."' AS fnqty_base,'{$_REQUEST['ftuom_codeD0'][$j]}' AS ftuom_code,'".CCur($_REQUEST['ffformulaD0'][$j])."' AS ffformula,'{$fcprice}' AS fcprice,
                                    '".CCur($_REQUEST['ffdiscountD0'][$j])."' AS ffdiscount,'".CCur($_REQUEST['fcdiscountD0'][$j])."' AS fcdiscount,'{$fcamount}' AS fcamount,'{$fcprice_cogs}' AS fcprice_cogs,
                                    '{$_SESSION['username']}' AS ftcreated_user,now() AS fdcreated_date,'{$_SESSION['username']}' AS ftmodified_user,NOW() AS fdmodified_date";

                    $strSQL['INSERT txpurchase_invoice_det'][]=$ssql;

                    if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                        mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                    }
                   
                }	
            }

            // Call Function Revisi General Ledger
            if(function_exists("RevisiGL")) {
                $m = RevisiGL($fttrans_no_new);
                if ($m != '') { $strSQL=array_merge_recursive($strSQL,$m); }
            }
            
            break;
    }

    return $strSQL;
 }
 
function RevisiDataLast() {
    global $objAxpDB;
    $strSQL=array();
    
    // Internal Setting
    $PBAutoPI = RetRstField("SELECT ftvalue FROM tssys_setting WHERE ftsys_code = 'PUR01'");

    $fnpo_type=RetRstField("select fnpo_type from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
    
    switch($_REQUEST[mode]) {
        case "simpan_revisi":
            if($_REQUEST['ftcategory_code']=='0') {
                for($j=1; $j<count($_REQUEST['ftitem_codeD0']); $j++) {
                    
                    // Update Harga Jual           
                    /* $ssql="UPDATE tlselling_price SET
                            fcold_selling_price=fcselling_price,
                            fcselling_price='".CCur($_REQUEST['fcselling_priceD0'][$j])."',
                            ftmodified_user='{$_SESSION['username']}',fdmodified_date=now()
                            WHERE ftitem_code='{$_REQUEST['ftitem_codeD0'][$j]}' AND
                            ftcurrency_code='IDR' AND
                            fcselling_price<>".CCur($_REQUEST['fcselling_priceD0'][$j])."";      
                    $strSQL['UPDATE tlselling_price'][]=$ssql;

                    if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                        mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                    }
                    */
                    
                }
                
            }
	
            break;
    }
	
    return $strSQL;

}

function RevisiDataAfter() {
    global $objAxpDB;
    $strSQL=array();
    
    // Internal Setting
    $PBAutoPI = RetRstField("SELECT ftvalue FROM tssys_setting WHERE ftsys_code = 'PUR01'");

    $fnpo_type=RetRstField("select fnpo_type from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
    
    switch($_REQUEST[mode]) {
        case "simpan_revisi":
            if($_REQUEST['ftcategory_code']=='0') {
                // Update Purchase Invoice Amount
                if ($PBAutoPI && ($fnpo_type==0)) {
                    $fcsub_amount=RetRstField("SELECT IFNULL(SUM(a.fcamount),0) AS fcamount FROM txpurchase_invoice_det a, txpurchase_invoice_hdr b WHERE a.ftpurchase_invoice_no = b.ftpurchase_invoice_no AND b.ftstock_in_no = '{$_REQUEST['ftstock_in_no']}'");                 
                    $ffvat=RetRstField("select ffvat from txpurchase_order_hdr where ftpo_no='".$_REQUEST['ftdocument_no']."'");
                    $fcvat = ($ffvat / 100) * $fcsub_amount;
                    $fcamount = $fcsub_amount + $fcvat;

                    $ssql="UPDATE txpurchase_invoice_hdr a 
                            SET a.fcsub_amount='{$fcsub_amount}', a.fcvat = '{$fcvat}', a.fcamount='{$fcamount}',
                                    a.fcpayment_amount='0',a.fcoutstanding_amount='{$fcamount}', a.fcreturn_amount='0'  
                            WHERE a.ftstock_in_no='{$_REQUEST['ftstock_in_no']}'";
                    $strSQL["Update Purchase Invoice Amount"][]=$ssql;

                    if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                        mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                    }                                                
                    break;
                }    

                for($j=1; $j<count($_REQUEST['ftitem_codeD0']); $j++) {
                    if ($_REQUEST['ftstock_type_code'] == 'invbb') {
                        $m=SaveStock_bahan_baku('+',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j],'',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                    } else if ($_REQUEST['ftstock_type_code'] == 'invsj') {
                        $m=SaveStock_setengah_jadi('+',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j],'',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                    } else if ($_REQUEST['ftstock_type_code'] == 'invsp') {
                        $m=SaveStock_sparepart('+',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j],'',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                    } else if ($_REQUEST['ftstock_type_code'] == 'inv') {
                        $m=SaveStock('+',$_REQUEST['ftitem_codeD0'][$j],'',$_REQUEST['ftwarehouse_codeD0'][$j],$_REQUEST['ftlocation_codeD0'][$j], '',CCur($_REQUEST['fnqty_baseD0'][$j]),CCur($_REQUEST['fnqty_baseD0'][$j]));
                    }

                    $strSQL=array_merge_recursive($strSQL,$m);
                    
                    $ssql="UPDATE txpurchase_order_det a
                            SET a.fnqty_accept = (SELECT SUM(c.fnqty) AS s FROM txstock_in_hdr b
                                                    INNER JOIN txstock_in_det c ON b.ftstock_in_no=c.ftstock_in_no
                                                    WHERE b.fnstatus ='1' AND b.ftdocument_no = a.ftpo_no AND c.ftitem_code = a.ftitem_code AND c.fnindex_po = a.fnindex ) ,
                                a.fnqty_accept_base = (SELECT SUM(c.fnqty_base) AS s FROM txstock_in_hdr b
                                                    INNER JOIN txstock_in_det c ON b.ftstock_in_no=c.ftstock_in_no
                                                    WHERE b.fnstatus ='1' AND b.ftdocument_no = a.ftpo_no AND c.ftitem_code = a.ftitem_code AND c.fnindex_po = a.fnindex ) 
                            WHERE a.ftpo_no='{$_REQUEST['ftdocument_no']}' AND a.ftitem_code='{$_REQUEST['ftitem_codeD0'][$j]}'   
                                    AND a.fnindex='{$_REQUEST['fnindex_poD0'][$j]}' ";
                    mysql_query($ssql);        
                    
                }

                mysql_query("UPDATE txpurchase_order_det SET fnstatus=5 WHERE ftpo_no='{$_REQUEST['ftdocument_no']}' AND fnqty_accept >= fnqty");
            
                // set status terkirim
                $ssql="UPDATE txpurchase_order_hdr a INNER JOIN ( 
                            SELECT b.ftpo_no, COUNT(a.fnid) AS total_item, COUNT(c.fnindex) AS total_item_closed, fnreceipt_status
                            FROM txpurchase_order_det a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no=b.ftpo_no
                            LEFT JOIN txpurchase_order_det c ON c.ftpo_no=a.ftpo_no AND c.fnindex=a.fnindex AND c.fnstatus = 5
                            WHERE b.ftpo_no='{$_REQUEST['ftdocument_no']}' GROUP BY b.ftpo_no
                            HAVING total_item = total_item_closed AND fnreceipt_status != 3 ) b 
                        SET a.fnreceipt_status = 3 WHERE a.ftpo_no = b.ftpo_no; ";
                $strSQL["Update txpurchase_order_hdr Receipt1"][]=$ssql;

                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                    if($ssql2!="")
                       mysql_query($ssql2) or die("SQL ERROR :{$ssql}");
                }

                // set status sebagian
                $ssql="UPDATE txpurchase_order_hdr a INNER JOIN ( 
                            SELECT b.ftpo_no, COUNT(a.fnid) AS total_item, COUNT(c.fnindex) AS total_item_closed, fnreceipt_status
                            FROM txpurchase_order_det a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no=b.ftpo_no
                            LEFT JOIN txpurchase_order_det c ON c.ftpo_no=a.ftpo_no AND c.fnindex=a.fnindex AND c.fnstatus = 5
                            WHERE b.ftpo_no='{$_REQUEST['ftdocument_no']}' GROUP BY b.ftpo_no
                            HAVING total_item != total_item_closed AND total_item_closed != 0 AND fnreceipt_status != 2 ) b
                        SET a.fnreceipt_status = 2 WHERE a.ftpo_no = b.ftpo_no; ";
                $strSQL["Update txpurchase_order_hdr Receipt2"][]=$ssql;

                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                    if($ssql2!="")
                       mysql_query($ssql2) or die("SQL ERROR :{$ssql}");
                }

                // set status belum dikirim
                $ssql="UPDATE txpurchase_order_hdr a INNER JOIN ( 
                            SELECT b.ftpo_no, COUNT(a.fnid) AS total_item, COUNT(c.fnindex) AS total_item_closed, fnreceipt_status
                            FROM txpurchase_order_det a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no=b.ftpo_no
                            LEFT JOIN txpurchase_order_det c ON c.ftpo_no=a.ftpo_no AND c.fnindex=a.fnindex AND c.fnstatus = 5
                            WHERE b.ftpo_no='{$_REQUEST['ftdocument_no']}' GROUP BY b.ftpo_no
                            HAVING total_item_closed = 0 AND fnreceipt_status != 1 ) b
                    SET a.fnreceipt_status = 1 WHERE a.ftpo_no = b.ftpo_no; ";
                $strSQL["Update txpurchase_order_hdr Receipt3"][]=$ssql;

                $ssql2="UPDATE txpurchase_order_schedule_delivery a INNER JOIN txpurchase_order_hdr b ON a.ftpo_no = b.ftpo_no
                            SET a.fnlock = 1 WHERE a.fnlock != 1 AND b.fnreceipt_status = 3; ";
                $strSQL["Update txpurchase_order_hdr Receipt4"][]=$ssql2;

                if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                    mysql_query($ssql) or die("SQL ERROR :{$ssql}");
                    if($ssql2!="")
                       mysql_query($ssql2) or die("SQL ERROR :{$ssql}");
                }
            }
	
            break;
    }
	
    return $strSQL;

}
