<?php
/**********************************************************************
***********************************************************************/

function write_sales_payment_return(&$delivery,$bo_policy){
    global $Refs;

//    $trans_no = $delivery->trans_no;
    $trans_no = 0;
    if(is_array($trans_no)){
        $trans_no = key($trans_no);
    }

    begin_transaction();
        $delivery->bo_policy = $bo_policy;
        hook_db_prewrite($delivery, ST_CUSTOMER_PAYMENT_RETURN);

        $msg_so = update_sales_order_row_state($delivery->sales_order_no, $delivery->row_state);
        if($msg_so["success"] !== true){
            cancel_transaction();
            return array("success" => false, "tran_no" => 0, "message" => $msg_so["message"]);
        }

        $customer = get_customer($delivery->customer_id);

        add_new_exchange_rate($customer['curr_code'], $delivery->document_date, $delivery->ex_rate);

        $payeent_return_items_total = $delivery->get_items_total_dispatch();
        $freight_tax = $delivery->get_shipping_tax();

    // mark sales order for concurrency conflicts check
        update_sales_order_version($delivery->src_docs);

        $tax_total = 0;
        $ov_gst = $ov_stax = 0;
        $taxes = $delivery->get_all_taxes(); // all taxes with freight_tax

//        foreach($taxes as $taxitem){
//            $taxitem['Value'] =  round2($taxitem['Value'], user_price_dec());
//            $tax_total +=  $taxitem['Value'];
//        }
        
        foreach ($taxes as $taxitem) {
		$taxitem['Value'] =  round2($taxitem['Value'], user_price_dec());
                if($taxitem['suspended'] == 0){
                    $ov_gst +=  $taxitem['Value'];
                }
                else{
                    $ov_stax +=  $taxitem['Value'];
                }
	}

        if($delivery->tax_included==0) {
	    $items_added_tax = $ov_gst - (($freight_tax * $ov_gst) / ($ov_gst + $ov_stax));
	    $items_added_stax = $ov_stax - (($freight_tax * $ov_stax) / ($ov_gst + $ov_stax));
	    $freight_added_tax = $freight_tax;
	} else {
	    $items_added_tax = 0;
            $items_added_stax = 0;
	    $freight_added_tax = 0;
	}
        
            /* Insert/update the debtor_trans */
        $delivery_no = write_customer_trans(ST_CUSTOMER_PAYMENT_RETURN, $trans_no, $delivery->customer_id,
                                            $delivery->Branch, $delivery->document_date, $delivery->reference,
                                            $payeent_return_items_total, 0,
                                            //$delivery->tax_included ? 0 : $tax_total-$freight_tax,
                                            $items_added_tax,
                                            $delivery->freight_cost,
                                            //$delivery->tax_included ? 0 : $freight_tax,
                                            $freight_added_tax,
                                            $delivery->sales_type, $delivery->invoice_id,
                                            $delivery->ship_via, $delivery->due_date, 0, 0, $delivery->dimension_id, 
                                            $delivery->dimension2_id, $delivery->payment, 
                                            $delivery->project_id, $delivery->tax_group_id, $items_added_stax);

        add_order_category_transaction(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no, $delivery->order_category_id);    
        
	if($trans_no == 0) {
            $delivery->trans_no = array($delivery_no=>0);
	}else{
            void_gl_trans(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no, true);
            void_stock_move(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no);
            void_trans_tax_details(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no);
            delete_comments(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no);
	}

	foreach($delivery->line_items as $line_no=>$delivery_line){
            
            if($delivery_line->qty_dispatched == 0){
                continue;
            }
            
//            $returned_quantity = get_debtor_trans_detail_total_qty_for_source_line_id(ST_CUSTOMER_PAYMENT_RETURN, $delivery_line->id);
            $can_return_qty = $delivery_line->quantity - (($delivery_line->qty_done));
            if($delivery_line->qty_dispatched > $can_return_qty){
                if(str_replace(',', '', $delivery_line->qty_dispatched) > $can_return_qty){
                    $tran_unit_can_return_qty = $can_return_qty / $delivery_line->disp_unit_convertion_factor;
                    return array("success" => false, "tran_no" => $delivery_no, 
                                 "message" => "Line Id $delivery_line->id: Returning quantity can not be higher than ".number_format($tran_unit_can_return_qty, user_qty_dec()));
                }
            }
            
            $base_unit_price = $delivery_line->line_price();
            $base_unit_taxfree_price = get_tax_free_price_for_item($delivery_line->stock_id, $delivery_line->price, 0, $delivery->tax_included, $delivery->tax_group_array);
            $base_unit_full_price = get_full_price_for_item($delivery_line->stock_id, $delivery_line->price, 0, $delivery->tax_included, $delivery->tax_group_array);
            
            $base_unit_tax = $base_unit_full_price - $base_unit_taxfree_price;
            $tran_unit_price = $base_unit_price * $delivery_line->disp_unit_convertion_factor;

            //if ($trans_no != 0) // Inserted 2008-09-25 Joe Hunt. This condition is removed after experience by Chaitanya
            $delivery_line->standard_cost = get_standard_cost($delivery_line->stock_id);

            /* add delivery details for all lines */
            write_customer_trans_detail_item(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no, $delivery_line->stock_id,
                                             $delivery_line->item_description, $delivery_line->qty_dispatched, $base_unit_price, 
                                             $base_unit_tax, $delivery_line->discount_percent, $delivery_line->standard_cost, 
                                             $delivery_line->src_id, 0, $delivery_line->disp_unit,
                                             $delivery_line->disp_unit_disp_qty, $delivery_line->disp_unit_convertion_factor, $tran_unit_price);

            // Now update invoice details for the quantity returned
//            if($delivery_line->qty_old != $delivery_line->qty_dispatched)
            
            update_parent_line(ST_CUSTOMER_PAYMENT_RETURN, $delivery_line->src_id, $delivery_line->qty_dispatched);
            

//            if($delivery_line->qty_dispatched != 0){
//                add_stock_move_customer(ST_CUSTOMER_PAYMENT_RETURN, $delivery_line->stock_id, $delivery_no,
//                                        $delivery->Location, $delivery->document_date, $delivery->reference,
//                                        -$delivery_line->qty_dispatched, $delivery_line->standard_cost,1,
//                                        $line_price, $delivery_line->discount_percent,
//                                        $delivery_line->disp_unit, -$delivery_line->disp_unit_disp_qty, $delivery_line->disp_unit_convertion_factor);
//
//                $stock_gl_code = get_stock_gl_code($delivery_line->stock_id);
//
//                    /* insert gl_trans to credit stock and debit cost of sales at standard cost*/
//                    if(is_inventory_item($delivery_line->stock_id) && $delivery_line->standard_cost != 0){
//
//                        /*first the cost of sales entry*/
//                        // 2008-08-01. If there is a Customer Dimension, then override with this,
//                        // else take the Item Dimension (if any)
//                        $dim = ($delivery->dimension_id != $customer['dimension_id'] ? $delivery->dimension_id : 
//                                ($customer['dimension_id'] != 0 ? $customer["dimension_id"] : $stock_gl_code["dimension_id"]));
//                        $dim2 = ($delivery->dimension2_id != $customer['dimension2_id'] ? $delivery->dimension2_id : 
//                                 ($customer['dimension2_id'] != 0 ? $customer["dimension2_id"] : $stock_gl_code["dimension2_id"]));
//
//                        add_gl_trans_std_cost(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no,
//                                              $delivery->document_date, $stock_gl_code["cogs_account"], $dim, $dim2, "",
//                                              $delivery_line->standard_cost * $delivery_line->qty_dispatched * $delivery_line->disp_unit_convertion_factor,
//                                              PT_CUSTOMER, $delivery->customer_id,
//                                              "The cost of sales GL posting could not be inserted");
//
//                        /*now the stock entry*/
//
//                        add_gl_trans_std_cost(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no, $delivery->document_date,
//                                              $stock_gl_code["inventory_account"], 0, 0, "",
//                                              (-$delivery_line->standard_cost * $delivery_line->qty_dispatched * $delivery_line->disp_unit_convertion_factor),
//                                              PT_CUSTOMER, $delivery->customer_id,
//                                              "The stock side of the cost of sales GL posting could not be inserted");
//
//                    } /* end of if GL and stock integrated and standard cost !=0 */
//
//            } /*quantity dispatched is more than 0 */
//	
            
            
                    } /*end of order_line loop */
        
        foreach($delivery->line_items as $line_no => $delivery_line){
            $msg = update_sales_order_line_totals($delivery_line->sales_order_line_id);
            if($msg['success'] !== true){
                return $msg;
            }
        }

//	if($bo_policy == 0){
//            // if cancelling any remaining quantities
//            close_sales_order($delivery->order_no);
//	}

	// taxes - this is for printing purposes
	foreach($taxes as $taxitem){
            if($taxitem['Net'] != 0){
                $ex_rate = get_exchange_rate_from_home_currency(get_customer_currency($delivery->customer_id), $delivery->document_date);
                add_trans_tax_details(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no, $taxitem['tax_type_id'],
                                      $taxitem['rate'], $delivery->tax_included, $taxitem['Value'],
                                      $taxitem['Net'], $ex_rate, $delivery->document_date, $delivery->reference, $taxitem['suspended']);
            }
	}

	add_comments(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no, $delivery->document_date, $delivery->Comments);

	if($trans_no == 0){
            $Refs->save(ST_CUSTOMER_PAYMENT_RETURN, $delivery_no, $delivery->reference);
	}

	hook_db_postwrite($delivery, ST_CUSTOMER_PAYMENT_RETURN);
        
    commit_transaction();

	//return $delivery_no;
    return array("success" => true, "tran_no" => $delivery_no, "message" => "Customer Payment Return $delivery_no added.");
}


?>