<?php
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("");
        }
    }
}

switch($_REQUEST[mode]) {
    case "simpan":
        // Validasi Outstanding amount tidak mencukupi -- case kelebihan retur / debit memo belum dibuatkan
        $fcoutstanding_amount = RetRstField("SELECT fcoutstanding_amount FROM txpurchase_invoice_hdr a WHERE a.ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}' ");
        $fcoutstanding_amount = $fcoutstanding_amount - CCur($_REQUEST['fcamount']);
        if($fcoutstanding_amount<0) {
            echo "<script>
                    alert('Sudah ada pembayaran untuk Purchase Invoice ini. Harap dicek kembali. ');
                    window.location='{$url}?form={$form}&mode=edit&id={$_REQUEST['id']}';
                  </script>";
            die("");
        }
       
        break;
        
}

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

    switch($_REQUEST[mode]) {
        case "simpan":

            //update qty retur di pi
            for($j=1; $j<count($_REQUEST['fnindexD0']); $j++) {
                $strSQL['Update qty retur txpurchase_invoice_det'][]=
                           "UPDATE txpurchase_invoice_det
                            SET fnqty_return=IFNULL(fnqty_return,0)+".CCur($_REQUEST['fnqtyD0'][$j])."
                            WHERE ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}' AND
                                    ftitem_code='{$_REQUEST['ftitem_codeD0'][$j]}'";
            }

            $strSQL['Update qty retur txpurchase_invoice_hdr'][]=
                           "UPDATE txpurchase_invoice_hdr
                            SET fcreturn_amount= IFNULL(fcreturn_amount,0) + ".CCur($_REQUEST['fcamount']).",
                                fcoutstanding_amount = IFNULL(fcoutstanding_amount,0) - ".CCur($_REQUEST['fcamount'])."
                            WHERE ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}'";

            // insert transaksi stock keluar
            $ftstock_out_no=getAutoNumber($_SESSION['strbranch'],'TN002','txstock_out_hdr','ftstock_out_no',$_REQUEST['fdtrans_date']);
            $dt=getDateYmd($_REQUEST['fdtrans_date']);
            $strSQL['Insert txstock_out'][]="
                      INSERT INTO txstock_out_hdr
                          (ftbranch_code, ftstock_out_no, ftcategory_code,
                          ftstock_out_company, ftdocument_no, fdtrans_date,
                          fntotal_qty, ftnotes, fnstatus, ftcreated_user,
                          fdcreated_date, ftmodified_user, fdmodified_date, ftstock_type_code)
                      SELECT
                     '{$_SESSION['strbranch']}' AS ftbranch_code, '{$ftstock_out_no}' AS ftstock_out_no, '0' AS ftcategory_code,
                         '{$_REQUEST['ftsupplier_code']}' AS  ftstock_out_company, '{$_REQUEST['ftpurchase_return_no']}' AS ftdocument_no,'{$dt}' AS  fdtrans_date,
                          '".CCur($_REQUEST['fftotal_qty'])."' AS fntotal_qty,'{$_REQUEST['ftnotes']}' AS  ftnotes, '1' AS fnstatus,  '{$_SESSION['username']}' AS ftcreated_user,
                          now() AS fdcreated_date,  '{$_SESSION['username']}' AS ftmodified_user, now() AS fdmodified_date, 'inv' as ftstock_type_code";

            for($j=1; $j<count($_REQUEST['fnindexD0']); $j++) {              
                if((float)CCur($_REQUEST['fnqtyD0'][$j])>0){
                    $strSQL['Insert Stock Out Det'][]="
                        INSERT INTO txstock_out_det
                             (ftbranch_code,ftstock_out_no, fnindex, ftitem_code,
                             ftwarehouse_code, ftlocation_code, fnqty_available,
                             fnqty, ftuom_code, fnqty_base,ffformula, 
                             ftcreated_user, fdcreated_date, ftmodified_user, fdmodified_date)
                        SELECT 
                            '{$_SESSION['strbranch']}' AS ftbranch_code,'{$ftstock_out_no}' AS ftstock_out_no, '{$j}' AS fnindex, '{$_REQUEST['ftitem_codeD0'][$j]}' AS ftitem_code,
                            '{$_REQUEST['ftwarehouse_codeD0'][$j]}' AS ftwarehouse_code, '{$_REQUEST['ftlocation_codeD0'][$j]}' AS ftlocation_code, '".CCur($_REQUEST['fnqty_availableD0'][$j])."' AS fnqty_available,
                            '".CCur($_REQUEST['fnqtyD0'][$j])."' AS fnqty, '{$_REQUEST['ftuom_codeD0'][$j]}' AS ftuom_code, '".CCur($_REQUEST['fnqty_baseD0'][$j])."' AS fnqty_base, '".CCur($_REQUEST['ffformulaD0'][$j])."' AS ffformula, 
                            '{$_SESSION['username']}' AS ftcreated_user, now() AS fdcreated_date,  '{$_SESSION['username']}' AS ftmodified_user, now() AS fdmodified_date ";

                    $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);
                }
            }

            $strSQL['Insert Stock Out Det'][]= "UPDATE  txstock_out_hdr
                                                SET fntotal_qty=(SELECT SUM(fnqty) AS fnqty FROM txstock_out_det WHERE ftstock_out_no='{$ftstock_out_no}')
                                                WHERE ftstock_out_no='{$ftstock_out_no}'";

            break;
        }
    return $strSQL;

}
 

function SaveDataLast() {
    global $objAxpDB;
    $objAxpDB->Allow_Save(true);
    $strSQL=array();
    switch($_REQUEST[mode]) {
        case "simpan":
            $strSQL["Update Stock Name"][]="UPDATE txpurchase_return_det a, tlstock_hdr b SET a.ftitem_name=b.ftitem_name WHERE a.ftitem_code = b.ftitem_code AND a.ftpurchase_return_no='{$_REQUEST['ftpurchase_return_no']}'";

        break;
    }
    return $strSQL;

}

function SaveDataAfter() {
    global $objAxpDB;
    $strSQL=array();
    switch($_REQUEST[mode]) {
        case "simpan":

            $ssql="DELETE FROM txpurchase_return_det WHERE fnqty=0 AND ftpurchase_return_no='{$_REQUEST['ftpurchase_return_no']}' ";
            $strSQL['txpurchase_return_det Index'][]= $ssql;
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
            }

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

            $strSQL['txpurchase_return_det Index'][]= $ssql;
            if($_REQUEST['DIRECT_EXECUTE_SQL']==1) {
                mysql_query($ssql) or die("SQL ERROR :{$ssql}");
            } 
            
            // Set outstanding = 0 when there is retur after payment
            $strSQL['Update qty retur txpurchase_invoice_hdr'][]=
                           "UPDATE txpurchase_invoice_hdr
                            SET fcoutstanding_amount = 0
                            WHERE fcoutstanding_amount < 0 AND ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}'";


        break;
    }
    return $strSQL;

}

function UpdateData() {
    global $objAxpDB;
    $objAxpDB->Allow_Update(false);
    switch($_REQUEST[mode]) {
        case "update":
            break;
    }
    
    return $strSQL;
}

function CancelData() {

    global $objAxpDB;
    // $objAxpDB->Allow_Cancel(false);
    $strSQL=array();
    switch($_REQUEST[mode]) {
        case "batal":
            $strSQL["Batal txpurchase_return_hdr"][] =
                   "UPDATE txpurchase_return_hdr
                    SET ftmodified_user='{$_SESSION['username']}',fdmodified_date=now(), fnstatus=9
                    WHERE ftpurchase_return_no='{$_REQUEST['ftpurchase_return_no']}'";

            $strSQL['Batal txstock_out_hdr'][]=
                   "UPDATE txstock_out_hdr 
                    SET ftmodified_user='{$_SESSION['username']}',fdmodified_date=now(), fnstatus=9
                    WHERE ftdocument_no='{$_REQUEST['ftpurchase_return_no']}'";

            //update qty retur di pi
            for($j=1; $j<count($_REQUEST['fnindexD0']); $j++) {
                $strSQL['Update qty retur txpurchase_invoice_det'][]=
                   "UPDATE txpurchase_invoice_det
                    SET fnqty_return=IFNULL(fnqty_return,0)-".CCur($_REQUEST['fnqtyD0'][$j])."
                    WHERE ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}' 
                            AND ftitem_code='{$_REQUEST['ftitem_codeD0'][$j]}'";
                            
                $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);      
                
            }

            $strSQL['Update qty retur txpurchase_invoice_hdr'][]=
                   "UPDATE txpurchase_invoice_hdr
                    SET fcreturn_amount= IFNULL(fcreturn_amount,0) - ".CCur($_REQUEST['fcamount']).",
                        fcoutstanding_amount = IFNULL(fcoutstanding_amount,0) + ".CCur($_REQUEST['fcamount'])."
                    WHERE ftpurchase_invoice_no='{$_REQUEST['ftpurchase_invoice_no']}'";

            break;
        }

    return $strSQL;
}
