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

function process_customer_payment_return(){
    $dn = &$_SESSION['Items'];

//    if($_POST['bo_policy']){
//        $bo_policy = 0;
//    }else{
//        $bo_policy = 1;
//    }
    
    $dn->trans_type = ST_CUSTOMER_PAYMENT_RETURN;
    $newdelivery = true;

    copy_to_customer_payment_return_cart();
    if($newdelivery){
        new_doc_date($dn->document_date);
    }

    $dn_msg = $_SESSION['Items']->write_sales_payment_return();
    if($dn_msg['success'] !== true){
        display_error($dn_msg['message']);
        cancel_transaction();
        return false;
    }

    $delivery_no = $dn_msg['tran_no'];
    if($delivery_no == -1){
        display_error(_("The entered reference is already in use."));
        set_focus('ref');
    }else{
        processing_end();
        if($newdelivery){
            meta_forward($_SERVER['PHP_SELF'], "AddedID=$delivery_no");
        }else{
            meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$delivery_no");
        }
    }	
}




function check_customer_payment_return_data(){
    global $Refs;

    if(!isset($_POST['DispatchDate']) || !is_date($_POST['DispatchDate'])){
        display_error(_("The entered date of delivery is invalid."));
        set_focus('DispatchDate');
        return false;
    }
    if(!is_date_in_fiscalyear($_POST['DispatchDate'])){
        display_error(_("The entered date of delivery is not in fiscal year."));
        set_focus('DispatchDate');
        return false;
    }
    
    $msg = is_accounting_period_open($_POST['DispatchDate']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']);
        set_focus('DispatchDate');
        return false;
    }    
    
    if(!isset($_POST['due_date']) || !is_date($_POST['due_date'])){
        display_error(_("The entered dead-line for invoice is invalid."));
        set_focus('due_date');
        return false;
    }
    if($_SESSION['Items']->trans_no==0){
        if(!$Refs->is_valid($_POST['ref'])){
            display_error(_("You must enter a reference."));
            set_focus('ref');
            return false;
        }
    }
    $ref_msg = reference_exists($_POST['ref'], ST_CUSTOMER_PAYMENT_RETURN);    
    if($ref_msg){
        display_error($ref_msg);
        set_focus('ref');
        return false;
    }
    if($_POST['ChargeFreightCost'] == ""){
        $_POST['ChargeFreightCost'] = price_format(0);
    }
    if(!check_num('ChargeFreightCost',0)){
        display_error(_("The entered shipping value is not numeric."));
        set_focus('ChargeFreightCost');
        return false;
    }
    
    
    $cq_msg = check_customer_payment_return_quantities();
    if($cq_msg != ""){
        display_error(_($cq_msg));
        return false;
    }

    if($_SESSION['Items']->has_items_dispatch() == 0){
        display_error(_("There are no item quantities on this payment return."));
        return false;
    }
    
    return true;
}

//------------------------------------------------------------------------------

function copy_to_customer_payment_return_cart(){
    $cart = &$_SESSION['Items'];
    $cart->reference = $_POST['ref'];
    $cart->ship_via = $_POST['ship_via'];
    $cart->freight_cost = input_num('ChargeFreightCost');
    $cart->document_date = $_POST['DispatchDate'];
    $cart->due_date =  $_POST['due_date'];
    $cart->Location = $_POST['Location'];
    $cart->Comments = $_POST['Comments'];
    $cart->dimension_id = $_POST['dimension_id'];
    $cart->dimension2_id = $_POST['dimension2_id'];
    $cart->project_id = $_POST['project_id'];
    if($cart->trans_no == 0){
        $cart->reference = $_POST['ref'];
    }
    $cart->order_category_id = $_POST['order_category_id'];
}
//------------------------------------------------------------------------------

function copy_from_cart(){
    $cart = &$_SESSION['Items'];
    $_POST['ship_via'] = $cart->ship_via;
    $_POST['ChargeFreightCost'] = price_format($cart->freight_cost);
    $_POST['DispatchDate'] = $cart->document_date;
    $_POST['due_date'] = $cart->due_date;
    $_POST['Location'] = $cart->Location;
    $_POST['Comments'] = $cart->Comments;
    $_POST['dimension_id'] = $cart->dimension_id;
    $_POST['dimension2_id'] = $cart->dimension2_id;
    $_POST['cart_id'] = $cart->cart_id;
    $_POST['ref'] = $cart->reference;
    $_POST['project_id'] = $cart->project_id;
}
//------------------------------------------------------------------------------

function check_customer_payment_return_quantities(){
    $error = "";
   // Update cart delivery quantities/descriptions
   foreach($_SESSION['Items']->line_items as $line=>$itm){
       $id = $itm->id;
       if(isset($_POST['Line'.$line.'disp_unit_disp_qty'])){
           
           $itm->disp_unit = $_POST['Line'.$line.'disp_unit'];            

//           $returned_quantity = get_debtor_trans_detail_total_qty_for_source_line_id(ST_CUSTOMER_PAYMENT_RETURN, $id);
           
           if($_SESSION['Items']->trans_no){
               $min = 0;
               $max = $itm->quantity - ($itm->qty_done);  
           }else{
               $min = 0;
               $max = $itm->quantity - ($itm->qty_done);                    
           }

           $max1 = ($max + 0.0000000001)/ $itm->disp_unit_convertion_factor;
           $min1 = $min - 0.0000000001;
           $disp_unit_disp_qty = input_num('Line'.$line.'disp_unit_disp_qty');

           if(check_num2($disp_unit_disp_qty, $min1, $max1)){
               $itm->disp_unit_disp_qty = $disp_unit_disp_qty;
               $_SESSION['Items']->line_items[$line]->qty_dispatched = $itm->disp_unit_disp_qty * $itm->disp_unit_convertion_factor;
           }
           else{
               $tran_unit_returnable_qty = $max / $itm->disp_unit_convertion_factor;
                set_focus('Line'.$line.'disp_unit_disp_qty');
                return "Line #$id: Returning quantity can not be higher than maximum returnable quantity of ".$tran_unit_returnable_qty;
            }
       }

       if(isset($_POST['Line'.$line.'Desc'])){
            $line_desc = $_POST['Line'.$line.'Desc'];
            if(strlen($line_desc) > 0){
                $_SESSION['Items']->line_items[$line]->item_description = $line_desc;
            }
       }
   }

    return $error;
}
//------------------------------------------------------------------------------

function check_customer_payment_return_qoh(){
    global $SysPrefs;
    $dn = &$_SESSION['Items'];
    $newdelivery = ($dn->trans_no == 0);
    
    if(!$SysPrefs->allow_negative_stock()){
        foreach($_SESSION['Items']->line_items as $itm){
            if($itm->qty_dispatched && has_stock_holding($itm->mb_flag)){
                $qoh_by_date = get_qoh_on_date($itm->stock_id, $_POST['Location'], $_POST['DispatchDate']);
                $qoh_abs = get_qoh_on_date($itm->stock_id, $_POST['Location'], null);
                //If editing current delivery delivered qty should be added 
                if(!$newdelivery){
                    $delivered = get_already_delivered($itm->stock_id, $_POST['Location'], key($dn->trans_no));
                    $qoh_abs = $qoh_abs - $delivered;
                    $qoh_by_date = $qoh_by_date - $delivered;
                }
                
                $qoh = ($qoh_by_date < $qoh_abs ? $qoh_by_date : $qoh_abs); 
                
                if($itm->qty_dispatched > $qoh){
                    display_error(_("The delivery cannot be processed because there is an insufficient quantity for item:")." ".$itm->stock_id." - ".$itm->item_description);
                    return false;
                }
            }
        }
    }
    return true;
}

function display_customer_payment_return_header(){
    
    start_outer_table(TABLESTYLE2, "width=80%", 5);

    table_section(1, "width=35%");
            if($_SESSION['Items']->trans_no == 0){
                    ref_row(_("Reference"), 'ref', '', null);
            }else{
                label_row(_("Reference"), $_SESSION['Items']->reference);
            }
            label_row(_("Customer"), $_SESSION['Items']->customer_name);
            label_row(_("Branch"), get_branch_name($_SESSION['Items']->Branch));
            label_row(_("Currency"), $_SESSION['Items']->customer_currency);
            label_row(_("Sales Invoice"), get_customer_trans_view_str(ST_SALESINVOICE, $_SESSION['Items']->invoice_id));

    table_section(2, "width=35%");
            label_row(_("Tax Group"), $_SESSION['Items']->tax_group_name);    
            
            if(!isset($_POST['Location'])){
                $_POST['Location'] = $_SESSION['Items']->Location;
            }
            locations_list_row("Delivery From", 'Location', null, false, true);
                

                label_row(_("Sales Type"), $_SESSION['Items']->sales_type_name);
            
            if(!isset($_POST['DispatchDate']) || !is_date($_POST['DispatchDate'])) {
                    $_POST['DispatchDate'] = new_doc_date();
                    if(!is_date_in_fiscalyear($_POST['DispatchDate'])){
                        $_POST['DispatchDate'] = end_fiscalyear();
                    }
            }
            
            date_row(_("Date"), 'DispatchDate', '', $_SESSION['Items']->trans_no==0, 0, 0, 0);


    table_section(3, "width=35%");
            if(isset($_POST['project_id'])){
                    $_SESSION['Items']->project_id  = $_POST["project_id"];
            }

            $project = get_project_record($_SESSION['Items']->project_id);
            label_row("Project", $project['description']);
            hidden('project_id', $_SESSION['Items']->project_id);


            if(!isset($_POST['ship_via'])){
                $_POST['ship_via'] = $_SESSION['Items']->ship_via;
            }

            shippers_list_row("Shipping Company", 'ship_via', $_POST['ship_via']);

            order_categories_list_row(_("Order Category:"), 'order_category_id', OCT_SALES, $_SESSION['Items']->order_category_id);



    table_section(3, "width=35%");
                


            echo "</td><td>";// outer table

        start_table(TABLESTYLE, "width=90%");

            if(!isset($_POST['due_date']) || !is_date($_POST['due_date'])) {
                $_POST['due_date'] = get_invoice_duedate($_SESSION['Items']->payment, $_POST['DispatchDate']);
            }

            customer_credit_row($_SESSION['Items']->customer_id, $_SESSION['Items']->credit);
            // 2010-09-03 Joe Hunt
            $dim = get_company_pref('use_dimension');
            if ($dim > 0) {
                start_row();
                    label_cell(_("Dimension").":");
                    dimensions_list_cells(null, 'dimension_id', null, true, ' ', false, 1, false);
                end_row();
            }		
            else
            hidden('dimension_id', 0);
            if($dim > 1){
                start_row();
                    label_cell(_("Dimension")." 2:");
                    dimensions_list_cells(null, 'dimension2_id', null, true, ' ', false, 2, false);
                end_row();
            }else
                    hidden('dimension2_id', 0);
            //---------
            start_row();
            date_row(_("Invoice Dead-line"), 'due_date', '', null, 0, 0, 0);
            end_row();
        end_table();

    end_outer_table(1); // outer table
}

function display_customer_payment_return_details(){
    global $Ajax;
   
    $row = get_customer_to_order($_SESSION['Items']->customer_id);

    if($row['dissallow_invoices'] == 1){
        display_error(_("The selected customer account is currently on hold. Please contact the credit control personnel to discuss."));
        end_form();
        end_page();
        exit();
    }	

    display_heading(_("Customer Payment Return Details"));
    div_start('Items');

        start_table(TABLESTYLE, "width=80%");

            $new = $_SESSION['Items']->trans_no == 0;
            $th = array(_("Id"), _("Item Code"), _("Item Description"), _("Inv. Unit"), _("Qry Invoiced"),  _("Qty Done"), 
                        _("Return Unit"), _("This Return"), _("Price"),  _("Discount"), _("Total"));

            table_header($th);
            $k = 0;
            $has_marked = false;

            foreach($_SESSION['Items']->line_items as $line=>$ln_itm) {

                if($ln_itm->quantity <= $ln_itm->qty_done){
                    continue; //this line is fully delivered
                }

                if(isset($_POST['_Location_update']) || isset($_POST['clear_quantity']) || isset($_POST['reset_quantity'])){
                        // reset quantity
//                    $ln_itm->qty_dispatched = $ln_itm->quantity-$ln_itm->qty_done;
                }
                // if it's a non-stock item (eg. service) don't show qoh
                $row_classes = null;
                if(has_stock_holding($ln_itm->mb_flag) && $ln_itm->qty_dispatched){
                        // It's a stock : call get_dispatchable_quantity hook  to get which quantity to preset in the
                        // quantity input box. This allows for example a hook to modify the default quantity to what's dispatchable
                        // (if there is not enough in hand), check at other location or other order people etc ...
                        // This hook also returns a 'reason' (css classes) which can be used to theme the row.

                    $qoh = get_qoh_on_date($ln_itm->stock_id, $_POST['Location'], $_POST['DispatchDate']);
                    $q_class =  hook_get_dispatchable_quantity($ln_itm, $_POST['Location'], $_POST['DispatchDate'], $qoh);
                    // Skip line if needed
                    if($q_class === 'skip') {
                        continue;
                    }
                    if(is_array($q_class)) {
                        list($ln_itm->qty_dispatched, $row_classes) = $q_class;
                        $has_marked = true;
                    }
                }

                alt_table_row_color($k, $row_classes);
                    label_cell($ln_itm->id, "align=center");
                    view_stock_status_cell($ln_itm->stock_id);

                    if($ln_itm->descr_editable){
                        text_cells(null, 'Line'.$line.'Desc', $ln_itm->item_description, 30, 50);
                    }else{
                        label_cell($ln_itm->item_description);
                    }

                    $dec = get_qty_dec($ln_itm->stock_id);

                    $order_unit_name = get_unit_descr($ln_itm->tran_unit);
                    label_cell($order_unit_name);

                    $order_unit_ordered_qty = $ln_itm->tran_qty;
                    qty_cell($order_unit_ordered_qty, false, $dec);
                    
//                    $returned_quantity = get_debtor_trans_detail_total_qty_for_source_line_id(ST_CUSTOMER_PAYMENT_RETURN, $ln_itm->id);
//                    $order_unit_returned_qty = $returned_quantity / $ln_itm->convertion_factor;
//                    qty_cell($order_unit_returned_qty, false, $dec);

                    $order_unit_qty_done =  $ln_itm->qty_done / $ln_itm->convertion_factor;
                    qty_cell($order_unit_qty_done, false, $dec);

                    if(isset($_POST['clear_quantity'])){
                        $ln_itm->qty_dispatched = 0;
                    }

                    if(!isset($_POST['Line'.$line.'disp_unit'])){
                        $_POST['Line'.$line.'disp_unit'] = $ln_itm->tran_unit;
                    }
                    
                    $disp_unit_disp_qty = $order_unit_ordered_qty - ($order_unit_qty_done);
                    
                    if($disp_unit_disp_qty <= 0){
                        $_POST['Line'.$line.'disp_unit'] = 0; 
                        label_cell("");
                    }else{
                        units_list_cells(null, 'Line'.$line.'disp_unit', $ln_itm->stock_id, 0, false, true);
                    }

                    $alternate_unit = get_convertion_factor(get_post('Line'.$line.'disp_unit'), $ln_itm->stock_id);
                    if($alternate_unit){
                        $ln_itm->disp_unit_convertion_factor = $alternate_unit['convertion_factor'];
                    }else{
                        $ln_itm->disp_unit_convertion_factor = 1;
                        $item_edit_info = get_item_edit_info($ln_itm->stock_id);
                        $_POST['Line'.$line.'disp_unit'] = $item_edit_info['units'];
                    }
                    
//                    $Ajax->activate('Qty_field');
//                        div_start('Qty_field');
                        if($disp_unit_disp_qty <= 0){
                            $_POST['Line'.$line.'disp_unit_disp_qty'] = 0;
                            qty_cell($disp_unit_disp_qty, false, $dec);
                        }else{
    //                        $_POST['Line'.$line.'disp_unit_disp_qty'] = $disp_unit_disp_qty; /// clear post so value displayed in the fiel is the 'new' quantity
                            small_qty_cells(null, 'Line'.$line.'disp_unit_disp_qty', qty_format(input_num('Line'.$line.'disp_unit_disp_qty'), $ln_itm->stock_id, $dec), null, null, $dec);
                        }

                        $ln_itm->qty_dispatched = $_POST['Line'.$line.'disp_unit_disp_qty'];
                    
//                    div_end();
                    
                    $display_discount_percent = percent_format($ln_itm->discount_percent*100) . "%";

                    $line_total = ($ln_itm->qty_dispatched * $ln_itm->price * (1 - $ln_itm->discount_percent) * $ln_itm->disp_unit_convertion_factor);

                    amount_cell($ln_itm->price * $ln_itm->disp_unit_convertion_factor);
//                    label_cell($ln_itm->tax_type_name);
                    label_cell($display_discount_percent, "nowrap align=right");
                    amount_cell($line_total);

                end_row();
            }

            $_POST['ChargeFreightCost'] =  get_post('ChargeFreightCost', 
            price_format($_SESSION['Items']->freight_cost));

            $colspan = 10;

            start_row();
                label_cell(_("Shipping Cost"), "colspan=$colspan align=right");
                small_amount_cells(null, 'ChargeFreightCost', $_SESSION['Items']->freight_cost);
            end_row();

            $inv_items_total = $_SESSION['Items']->get_items_total_dispatch();
            $display_sub_total = price_format($inv_items_total + input_num('ChargeFreightCost'));
            label_row(_("Sub-total"), $display_sub_total, "colspan=$colspan align=right","align=right");
            $all_taxes = $_SESSION['Items']->get_all_taxes(input_num('ChargeFreightCost'));
            $staxes_total = $_SESSION['Items']->get_staxes_total($all_taxes);
            
            $tax_total = display_edit_tax_items($all_taxes, $colspan, $_SESSION['Items']->tax_included);
            $display_total = price_format(($inv_items_total + input_num('ChargeFreightCost') + $tax_total - $staxes_total));

            label_row(_("Amount Total"), $display_total, "colspan=$colspan align=right","align=right");

        end_table(1);

            if($has_marked){
                display_note(_("Marked items have insufficient quantities in stock as on day of delivery."), 0, 1, "class='red'");
            }

            start_table(TABLESTYLE2);
//                policy_list_row(_("Action For Balance"), "bo_policy", null);
                textarea_row(_("Memo"), 'Comments', null, 50, 4);
            end_table(1);

    div_end();
}

?>