<?php
if(!function_exists(ValBatalPI)){
    function ValBatalPI() {
        $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("");
        }

        $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}");
        $ftpurchase_return_no="";
        while($r=mysql_fetch_assoc($rs)) {
           $ftpurchase_return_no.="- {$r['ftpurchase_return_no']}\\n";
           
        }
        if($ftpurchase_return_no!="") {
             $massage=" Purchase Return berikut harus dibatalkan terlebih dahulu \\n";
             $massage.="---------------------------------------------------------\\n";
             $massage.=$ftpurchase_return_no;
        }
        if($massage!="") {
            echo "<script>
                alert('{$massage}');
                window.history.back();
            </script>";
            die("");
        }
    }
}

switch($_REQUEST[mode]) {
    case "simpan":
    case "simpan_revisi":        
        // Validasi NO PI belum ada di Stock Masuk
        $ssql="SELECT fnid FROM txstock_in_hdr a WHERE ftdocument_no='{$_REQUEST['ftpurchase_invoice_no']}' AND fnstatus !=3 AND fnstatus != 9  ";
        $rs=mysql_query($ssql);

        if(RetRstField($ssql)) {
            echo "<script>
                    alert('No.Purchase Invoice sudah terpakai pada stock masuk.');
                    window.history.back();
                </script>";
            die("");
        }
        
        // Validasi outstanding qty PO
        for($j=1; $j<count($_REQUEST['fnindexD0']); $j++) {

            $ssql ="SELECT DISTINCT (ttlqtylimit-ttlqtyaccept) AS qty_remaining, ftpo_no, ftitem_code, ttlqtyaccept, ttlqtylimit 
                    FROM (SELECT a.ftpo_no, b.ftitem_code,d.fnindex,
                            COALESCE(SUM(d.fnqty_base),0) AS ttlqtyaccept, COALESCE(SUM(b.fnqty_base),0) AS ttlqtylimit 
                            FROM txpurchase_order_hdr a LEFT JOIN txpurchase_order_det b ON a.ftpo_no = b.ftpo_no 
                            LEFT JOIN txpurchase_invoice_hdr c ON c.ftpo_no = a.ftpo_no AND c.fnstatus != 3 AND c.fnstatus != 9 AND c.fnsaldo_awal = 0
                            LEFT JOIN txpurchase_invoice_det d ON c.ftpurchase_invoice_no = d.ftpurchase_invoice_no AND b.ftitem_code=d.ftitem_code 
                            WHERE a.fnstatus != 3 AND a.fnstatus != 9 AND a.fnpo_type=1 AND a.ftbranch_code='{$_SESSION['strbranch']}' 
                                    AND b.ftitem_code='{$_REQUEST['ftitem_codeD0'][$j]}' AND a.ftpo_no='{$_REQUEST['ftpo_no']}'
                            GROUP BY a.ftpo_no, b.ftitem_code, d.fnindex
                            HAVING  ttlqtyaccept < ttlqtylimit) X ";
            $qty_remaining = RetRstField($ssql);
            
            if (CCur($_REQUEST['fnqtyD0'][$j]) > $qty_remaining) {
                echo "<script>
                        alert('Qty {$_REQUEST['ftitem_codeD0'][$j]} tidak boleh lebih dari qty sisa PO. Qty Sisa PO : {$qty_remaining} ');
                        window.history.back();    
                      </script>";
                die("");
            }    
        }   
        
        break; 
}

function SaveData() {
    global $objAxpDB;
    // $objAxpDB->Allow_Save(false);
    $strSQL=array();
    switch($_REQUEST[mode]) {
        case "simpan":
           // Status PO Import Approved setelah Penerimaan Barang selesai 
           //  $strSQL["Update txpurchase_order_hdr"][] = "UPDATE txpurchase_order_hdr SET fnstatus=2 WHERE ftpo_no='{$_REQUEST['ftpo_no']}'";
      
            break;
    }
    return $strSQL;
}

function SaveDataLast() {
    global $objAxpDB;
    $strSQL=array();
    switch($_REQUEST[mode]) {
        case "simpan":
            $strSQL["Update Supplier Name"][]="UPDATE txpurchase_invoice_hdr a, tlsupplier b SET a.ftsupplier_name=b.ftsupplier_name WHERE a.ftsupplier_code = b.ftsupplier_code AND a.ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}'";

            break;
    }

    return $strSQL;
 }
    
function CancelData() {
    ValBatalPI();
    global $objAxpDB;
    // $objAxpDB->Allow_Cancel(false);
    $strSQL=array();
    switch($_REQUEST[mode]) {
        case "batal":
            $strSQL["Batal txpurchase_invoice_hdr"][] =
                "update txpurchase_invoice_hdr
                 set fnpayment_status=9
                 WHERE ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}'";

            $strSQL["Update txpurchase_order_hdr"][] = "UPDATE txpurchase_order_hdr SET fnstatus=1, fnreceipt_status = CASE WHEN (fnreceipt_status = 3 AND fnhdr_category=2) THEN 1 ELSE fnreceipt_status END WHERE ftpo_no='{$_REQUEST['ftpo_no']}'";
                 
            /*$ssql="SELECT fnid, ftdocument_no, ftstock_in_company, ftcategory_code FROM txstock_in_hdr
                    WHERE ftstock_in_no='{$_REQUEST['ftstock_in_no']}'";
            $rs=mysql_query($ssql) or die($ssql);
            $r=mysql_fetch_assoc($rs);

            if(isset($r["fnid"])):
                $strSQL["Update txstock_in_hdr"][] = "UPDATE txstock_in_hdr SET fnstatus=1 WHERE fnid='{$r["fnid"]}'";
            else:
                $strSQL["Update txpurchase_order_hdr"][] = "UPDATE txpurchase_order_hdr SET fnstatus=1, fnreceipt_status = CASE WHEN (fnreceipt_status = 3 AND fnhdr_category=2) THEN 1 ELSE fnreceipt_status END WHERE ftpo_no='{$_REQUEST['ftstock_in_no']}'";
            endif;  */

        break;
    }

    return $strSQL;
}

   
function RevisiData() {
    ValBatalPI();
    global $objAxpDB;
    $objAxpDB->Allow_Revisi(true);
    $strSQL=array();
    switch($_REQUEST[mode]) {
        case "simpan_revisi":
            // batal -%
            $ssql1="SELECT IFNULL(MAX(ftpurchase_invoice_no),'')  AS M
                          FROM txpurchase_invoice_hdr
                          WHERE ftpurchase_invoice_no LIKE '{$_REQUEST['ftpurchase_invoice_no']}-%'";
            $no=RetRstField($ssql1);
            if($no!="") {
                $no1=explode("-",$no);
                $no=(int)$no1[1]+1;
                $str1="-{$no}";
            }
            else {
                $str1="-1";
            }

            $ftpurchase_invoice_no_new="{$_REQUEST['ftpurchase_invoice_no']}{$str1}";

            $strSQL["batal"][]="update txpurchase_invoice_hdr
                                set fnstatus=3, ftpurchase_invoice_no='{$ftpurchase_invoice_no_new}',
                                    ftmodified_user='{$_SESSION['username']}',fdmodified_date=now()
                                where ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}'";

            $strSQL["batal"][]="update txpurchase_invoice_det
                                set ftpurchase_invoice_no='{$ftpurchase_invoice_no_new}',
                                    ftmodified_user='{$_SESSION['username']}',fdmodified_date=now()
                                where ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}'";

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

            break;
    }

    return $strSQL;
}

