<?php

function crete_purchase_requisition_return($prr_trans, $reference, $date_, $receiving_location, $company_code, $employee_code, $comment) {
    
    global $systypes_array, $Refs;
    
    $batch_no = uniqid();
    
    $type = ST_PR_RETURN;
    
    $prr_date = date2sql($date_);
    
    $pri_row = get_pri_record_by_id($prr_trans->order_id);
        $pr_no = $pri_row['source_pr_no'];
    
    $prr_no = add_pr_return_header($batch_no, $reference, $receiving_location, $prr_date, $prr_trans->project_id, $prr_trans->order_id, $pr_no, 
                                   $company_code, $employee_code, $comment);
    if(!($prr_no > 0)){
        return array("success" => false, "tran_no" => -1, "message" => "Could not create ".$systypes_array[$type]);
    }
    
    foreach ($prr_trans->line_items as $prr_item) {
        if (isset($_POST[$prr_item->row_id.'_check_ppr_item']) && $_POST[$prr_item->row_id.'_check_ppr_item'] == 1) {
            $row_id = $prr_item->row_id;
            
            $total_issued_qty = $prr_item->qty;
            
            $total_returned_qty = get_prr_total_returned_qty_by_pri_line_id($row_id);
            
            $this_return_qty = $prr_item->convertion_factor * $prr_item->tran_qty;
            
            if (($total_returned_qty + $this_return_qty) > $total_issued_qty) {
                return array("success" => false, "tran_no" => $prr_no, "message" => "Line #$row_id : Process terminated. Trying to create an over return.");
            }
           
            $prrd_msg = crete_pr_return_detail($prr_item, $batch_no, $type, $prr_no, $reference, $date_, $receiving_location, $prr_trans->project_id);
            if($prrd_msg['success'] !== true){
                return $prrd_msg;
            }
        }
    }
    
    $prr_total = get_prr_lines_header_total($prr_no);
    update_pr_return_header_total($prr_no, $prr_total);
    
    $Refs->save($type, $prr_no, $reference);

    $msg = release_budgets_of_purchase_requisition_return($prr_no);
    if($msg['success'] !== true){
        cancel_transaction();
        return array("success" => $msg['success'], "tran_no" => $prr_no, "message" => $msg['message']);
    }

    return array("success" => true, "message" => $systypes_array[$type]." #".$prr_no." has been created.", "tran_no" => $prr_no);
}



function release_budgets_of_purchase_requisition_return($prr_no) {
    $pr_details_array = array();
    
    $prrh = get_pr_return_record($prr_no);
    $pr_no = $prrh['pr_no'];
    $pr_details = get_pr_details_for_prr_cost_charging($pr_no, $prr_no);
    
    while ($myrow = db_fetch($pr_details)) {
        $a['row_id'] = $myrow['id'];
        $a['stock_id'] = $myrow['item_code'];
        $a['task_id'] = $myrow['task_id'];
        $a['requested_qty'] = $myrow['requested_unit_qty'] * $myrow['req_unit_conv_factor'];
        $a['high_value_item'] = 0;
        
        $item_cost = $myrow['estimate_price'] / $myrow['req_unit_conv_factor'] ;
        $a['reference_cost'] = $item_cost;
        $a['standard_cost'] = $item_cost;
        
        $a['total_issued_qty'] = $myrow['issued_qty'] - $myrow['returned_qty'];
        
        $prrd_qty = 0;
        if(isset($myrow['prrd_line_id']) && $myrow['prrd_line_id'] > 0){
            $prrd_qty = $myrow['prrd_qty'];
        }
        $a['qty'] = $prrd_qty;
        
        $charging_cost = 0;
        if(isset($myrow['prrd_line_id']) && $myrow['prrd_line_id'] > 0){
            $charging_cost = $myrow['prrd_unit_cost'];
        }
        $a['charging_cost'] = $charging_cost;
        
        $pr_details_array[] = $a;
        
    }
    
    $created_by = $_SESSION['wa_current_user']->user;
    
    $tasks_summary = calculate_task_remaining_totals($pr_details_array);
    
//    $apc_msg = allocate_to_tasks(ST_PURCH_REQ, $pr_no, 
//                                $tasks_summary, $created_by);
//    if($apc_msg['success'] !== true)
//    {
//        cancel_transaction();
//        return array("success" => $apc_msg['success'], "tran_no" => $pr_no, "message" => $apc_msg['message']);
//    }
    
    $cct_msg = remove_costs_from_tasks(ST_PR_RETURN, $prr_no, 
                                $tasks_summary, $created_by);
    
    if($cct_msg['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $cct_msg['success'], "tran_no" => $prr_no, "message" => $cct_msg['message']);
    }
    

//    $pr_h = get_purchase_requitition_header_record($pr_no);
//    reopen_pr($pr_no, AS_ISSUED, $pr_h['row_state']);
        
    return array("success" => true, "tran_no" => $prr_no, "message" => "");

}

//function update_all_prr_header_totals($prr_ids_array) {
//    foreach ($prr_ids_array as $prr_no) {
//        update_each_prr_header_total($prr_no);
//    }
//}

//function update_each_prr_header_total($prr_no) {
//    $prr_total = get_prr_lines_header_total($prr_no);
//
//    update_pr_return_header_total($prr_no, $prr_total);
//}

function crete_pr_return_detail($prr_item, $batch_no, $type, $prr_no, $reference, $date_, $location, $project_id) {
    
    global $systypes_array;
    
    $prr_date = date2sql($date_);
    
    $item_code = $prr_item->stock_id;
    $description =  $prr_item->item_description;
    
    $conversion_factor = $prr_item->convertion_factor; 
    
    $tran_qty = $prr_item->tran_qty;
    $qty = $tran_qty * $conversion_factor;
    
    $tran_unit = $prr_item->tran_unit;
    
    $pri_line_id = $prr_item->row_id;
    $task_id = $prr_item->task_id;
    $project_site_id = $prr_item->project_site_id;
    
    $grn_item_id = 0;
    $cn_line_id = 0;
    $cost_source = "";
    
    $pri_line = get_pri_deatails_record_by_id($prr_item->row_id);
        $pr_line_id = $pri_line['pr_line_id'];
        $unit_price = $pri_line['unit_cost'];
    
    $prr_detail_id = add_pr_return_item($prr_no, $item_code, $description, $qty, $unit_price, $tran_unit, $tran_qty, $conversion_factor, $pr_line_id, 
                                        $task_id, $project_site_id, $grn_item_id, $cn_line_id, $cost_source, $pri_line_id);
    
    $stock_item = get_stock_item_edit_info($prr_item->stock_id);
        if(in_array($stock_item['mb_flag'], array('B', 'M'))){
            $std_cost = $stock_item['standard_cost'];
            $person_id = 0;
            $discount_percent = $price = 0;
            $memo_ = "";
            add_stock_adjustment_item($prr_no, $item_code, $location, $date_, $reference, 
                                        $qty, $std_cost, $memo_, $tran_unit, $tran_qty, 
                                        $conversion_factor, $type, $task_id, $project_site_id);
//            add_stock_move($type, $item_code, $prr_no, $location, $date_, $reference, $qty, $std_cost, 
//                    $person_id, 0, $price, $discount_percent, '', 
//                    $tran_unit, $tran_qty, $conversion_factor, $task_id, $project_site_id, $prr_detail_id, $project_id);
        }else{
            add_non_stock_move($type, $item_code, $prr_no, $location, $date_, $reference, $qty, $unit_price, 
                    0, 1, $unit_price, 0, $tran_unit, $tran_qty, $conversion_factor, $task_id, $project_site_id, $prr_detail_id, $description, $project_id);
        }

    
    
    
    $pri_returned_qty = get_prr_total_returned_qty_by_pri_line_id($pri_line_id);
    $n2 = update_pri_detail_line_returned_qty($pri_line_id, $pri_returned_qty);
    if($n2 !== 1)
    {
        $message = "Trying create an over return for ".$systypes_array[ST_PR_ISSUE]." line #".$pri_line_id;
        return array("success" => false, "tran_no" => $prr_no, "message" => $message);
    }
    
    $total_returned_qty = get_pr_item_total_returned_qty($pr_line_id);    
    $n1 = update_pr_item_returned_qty($pr_line_id, $total_returned_qty);
    if($n1 !== 1)
    {
        $message = "Trying create an over return for ".$systypes_array[ST_PURCH_REQ]." line #".$pr_line_id;
        return array("success" => false, "tran_no" => $prr_no, "message" => $message);
    }
    
    return array("success" => true, "tran_no" => $prr_no, "message" => "");
}

function line_start_focus() {
  global $Ajax;

  $Ajax->activate('items_table');
  set_focus('_stock_id_edit');
}

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

function handle_new_prr_order() {
    if (isset($_SESSION['prr_items'])) {
        $_SESSION['prr_items']->clear_items();
        unset($_SESSION['prr_items']);
    }

        $_SESSION['prr_items'] = new items_cart(ST_PR_ISSUE);
        
        populate_prr_cart_from_database();
}

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

function add_lot_details() {
    if(!isset($_SESSION['lot_info#'.ST_PR_ISSUE])){
        return;
    }
    
    $lot_info_array =  $_SESSION['lot_info#'.ST_PR_ISSUE];

    foreach ($_SESSION['prr_items']->line_items as $line_item) {
       	if($line_item->stock_control_method != SKCM_NORMAL){
            $line_item->lot_details = $lot_info_array[$line_item->stock_id] ;
        } 
    }    
}   

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

function update_cart() {
    foreach ($_SESSION['prr_items']->line_items as $line_item) {

        $tran_unit = $_POST[$line_item->row_id."_tran_unit"];
        $stock_id = $line_item->stock_id; 
        $tran_unit_convertion_factor = 1;
        
        get_convertion_factor2($stock_id, $tran_unit, $tran_unit_convertion_factor);
        
        $line_item->convertion_factor = $tran_unit_convertion_factor;
        
        $line_item->tran_qty = input_num($line_item->row_id."_tran_qty");
        $line_item->tran_unit = $tran_unit;
        
        $lot_details = get_selected_lot_serial_info('guid', $line_item);
        $line_item->lot_details = $lot_details;    
        
        
        if($_POST[$line_item->row_id."_project_site_id"] > 0){
            $line_item->project_site_id = $_POST[$line_item->row_id."_project_site_id"];
        }
        else{
             $line_item->project_site_id = 0;
        }
    }
}

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

function end_processing($trans_no, $type = ST_PR_ISSUE) {
    $_SESSION['prr_items']->clear_items();
    unset($_SESSION['prr_items']);        
    unset($_SESSION[ST_PR_ISSUE]);   
    
    if($type == ST_PR_ISSUE){
        meta_forward($_SERVER['PHP_SELF'], "Added_MI_ID=$trans_no");
    }
    elseif($type == ST_PR_RETURN){
        meta_forward($_SERVER['PHP_SELF'], "Added_PRR_ID=$trans_no");
    }
}

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

function close_material_requisition($pr_no){
        $cmr_msg = close_mr($pr_no);
        if($cmr_msg['success'] !== true){
            display_error($cmr_msg['message']);
        }
        else{
            set_session_variable('prr_messages', "Purchase requisition return ".$pr_no." has been added.");
            end_processing($pr_no); 
        }
}

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

function create_prr_return() {
    update_cart();
    
    $result = can_process_prr();
    
    if ($result == true) {
        begin_transaction();
        $msg = crete_purchase_requisition_return($_SESSION['prr_items'], $_POST['prr_reference'], $_POST['prr_date'], $_POST['receiving_location'], 
                                                 $_POST['group_company_code'], $_POST['group_company_employee_code'], $_POST['memo_']);
                
        if($msg['success'] !== true){
            cancel_transaction();
            display_error($msg['message']);
        }
        else{
            $pri_no = $_SESSION['prr_items']->order_id;
            $pri_complete_result = check_all_pr_issue_lines_returned($pri_no);
            if($pri_complete_result === true){
                update_pr_issue_fully_returned($pri_no);
            }  
            commit_transaction();
            set_session_variable('prr_messages', $msg['message']);
            end_processing($msg['tran_no'], ST_PR_RETURN);
        }      
    }
}

function populate_prr_cart_from_database() {
    $myrow = get_pr_issue_pri_no($_GET['pri_no']); //get_pr_issued
        
        $pr_cart = $_SESSION['prr_items'];

        $pr_cart->order_id = $myrow["pri_no"];
        $pr_cart->reference = $myrow["reference"];
        $pr_cart->issuing_location = $myrow["issuing_location"];
        $pr_cart->issuing_location_name = $myrow["location_name"];
        $pr_cart->receiving_location = '';
        $pr_cart->receiving_location_name = '';
        $pr_cart->required_date = $myrow["pri_date"];
        $user = get_user($myrow["created_by"]);
        $pr_cart->person_id = $user['real_name'];
        $pr_cart->created_on = $myrow["created_on"];
        $pr_cart->project_description = $myrow["project_description"];
        $pr_cart->mr_complete = '';
        $pr_cart->project_id = $myrow["project_id"];
        $pr_cart->original_amount = $myrow["total"];
        $pr_cart->approval_status = '';
        $pr_cart->pr_no = $myrow["source_pr_no"];
        $pr_cart->row_state = '';
        $pr_cart->movement_type = $myrow["movement_type"];
        $pr_cart->linked_field_type = $myrow["linked_field_type"];
        $pr_cart->linked_field_id = $myrow["linked_field_id"];
  
        $im_details = get_pr_issue_details($pr_cart->order_id);
            $element_no = 0;
            
            while ($imtd_row = db_fetch($im_details)) {
                $im_line = new line_item($imtd_row["item_code"], 0, $imtd_row["standard_cost"], $imtd_row["description"], '', '', '',
                                        $imtd_row["id"], $imtd_row["tran_qty"], $imtd_row["qty_issued"], 0, $imtd_row["unit_cost"], null, 0, 
                                        null, null, null, null, null, null, null, null);

                $im_line->row_id = $imtd_row["id"];
                $im_line->stock_control_method = null;
                $im_line->pr_line_id = $imtd_row["pr_line_id"];
                $im_line->task_id = $imtd_row["task_id"];
                $im_line->task_description = $imtd_row["task_description"];
                $im_line->project_site_id = $imtd_row["project_site_id"];
                $im_line->project_site_description = $imtd_row["site_name"];
                $im_line->returned_qty = $imtd_row["returned_qty"];
                $im_line->alternate_unit_name = $imtd_row["tran_unit"];
                $im_line->line_ref = $im_line->row_id;

                $pr_cart->line_items[$element_no] = $im_line;
                
                $element_no++;
            }

}

function display_purchase_requisition_return_header(&$order) {
    global $Refs, $Ajax;

    start_outer_table(TABLESTYLE2, "width=65%");

        table_section(1, "30%");
            label_row(_("Issued Location"), $order->issuing_location_name, "class='tableheader2'");
            label_row(_("Project"), $order->project_description, "class='tableheader2'");
            label_row(_("Reference"), $order->reference, "class='tableheader2'");

        table_section(2, "30%");
            label_row(_("PR Issue No"), get_supplier_trans_view_str(ST_PR_ISSUE, $order->order_id), "class='tableheader2'");
            label_row(_("Requisition Reference"), $order->reference, "class='tableheader2'");
            label_row(_("Required Date"), sql2date($order->required_date), "class='tableheader2'");

        table_section(3, "30%");
            label_row(_("Estimated Total"), $order->original_amount, "class='tableheader2'");
            
            $mv_tp = get_movement_type($order->movement_type);
            label_row(_("Movement Type"), $mv_tp['name'], "class='tableheader2'");

            global $inventory_movement_type_linked_fields;
            if ($order->linked_field_type != IMLF_NOT_LINKED) {
                $link_field = get_movement_type_linked_field_values($order->linked_field_type, $order->linked_field_id);
                label_row(_($inventory_movement_type_linked_fields[$order->linked_field_type]), $link_field['value'], "class='tableheader2'");
            }
    
    end_outer_table(1);

    $Ajax->activate('group_company_employee_code');

    set_post_not_set_string('receiving_location', $order->issuing_location);
    
    start_outer_table(TABLESTYLE2, "width=65%"); // outer table
        table_section(1, "40%");
            ref_row(_("Reference:"), 'prr_reference', '', $Refs->get_next(ST_PR_RETURN));
            locations_list_row(_("Receiving Location:"), 'receiving_location', null, false, false);

        table_section(2, "20%");
            date_row("Date:", 'prr_date');

        table_section(3, "40%");
            group_companies_list_row("Company: ", "group_company_code", null, false, true);
            group_company_employees_simple_list_row("Employee:", "group_company_employee_code", get_post('group_company_code'), null, '');

    end_outer_table(1); // outer table
}

function display_pr_return_items($title, &$order) {
    display_heading($title);
    
    div_start('items_table');
	start_table(TABLESTYLE, "width=100%");
            $th = array(_("Id"), _("Item Code"), _("Item Description"), _("Issued Unit") , _("Issued Unit Cost"), _("Qty Issued"), _("Qty Returned"), _("Return Unit"),
                        _("Return Qty"), _("Comment"), _("Site"), "", "");

            table_header($th);
            $total = 0;
            $k = 0;  //row colour counter

            $id = find_submit('Edit');
            foreach ($order->line_items as $line_no => $stock_item) {

                $total += ($stock_item->standard_cost * $stock_item->quantity);

		if ($id != $line_no) {
                    alt_table_row_color($k);

                        label_cell($stock_item->row_id, 'align=center');
                        view_stock_status_cell($stock_item->stock_id);
                        label_cell($stock_item->item_description);

                        label_cell($stock_item->alternate_unit_name);
                        $dec = get_qty_dec($stock_item->stock_id);
//                        qty_cell($stock_item->requested_qty/$stock_item->convertion_factor, false, $dec);

                        $prid = get_pri_deatails_record_by_id($stock_item->row_id);
                        $issued_unit_conversion_factor = $prid['conversion_factor'];
                        $issue_unit_cost = $stock_item->price * $issued_unit_conversion_factor;
                        amount_decimal_cell($issue_unit_cost);
                        
                        $tran_unit_issued_qty = $stock_item->issued_qty / $stock_item->convertion_factor;
//                        qty_cell($tran_unit_issued_qty, false, $dec);
                        qty_cell($stock_item->issued_qty, false, $dec);

                        $issued_unit_returned_qty = $stock_item->returned_qty / $issued_unit_conversion_factor;
                        qty_cell($issued_unit_returned_qty, false, $dec);

                        if(get_post($stock_item->row_id.'_tran_unit') != ''){
                            $current_tran_unit = get_post($stock_item->row_id.'_tran_unit');
                        }
                        else{
                            $current_tran_unit = $stock_item->tran_unit;
                        }


                        $alternate_unit = get_alternate_unit_info($stock_item->stock_id, $current_tran_unit);
                        if($alternate_unit){
                            $alternate_unit_convertion_factor = $alternate_unit['convertion_factor'];
                        }
                        else{
                            $alternate_unit_convertion_factor = 1;
                        }

                        if(!isset($_POST[$stock_item->row_id."_tran_qty"] )){
                            $_POST[$stock_item->row_id."_tran_qty"] = 0.00;
                        }
                        $suggested_return_qty = $_POST[$stock_item->row_id."_tran_qty"];

                        units_list_cells(null, $stock_item->row_id.'_tran_unit', $stock_item->stock_id, null, false, true);
                        $unit_of_parent = get_post($stock_item->row_id.'_tran_unit');

                        $item_info = get_item_edit_info($stock_item->stock_id);
                        $_POST['stock_control_method'] = $item_info["stock_control_method"];

                        display_quantity_cells(get_post('guid'), $order->trans_type, $stock_item->line_ref, $stock_item->stock_id, 
                                                $item_info["stock_control_method"], $stock_item->row_id.'_', $suggested_return_qty, $unit_of_parent, 
                                                $dec = 2, "items_table");

//                        label_cell($stock_item->required_date);
                        label_cell($stock_item->line_comment);

                        if(!isset($_POST[$stock_item->row_id.'_project_site_id'] )){
                            $_POST[$stock_item->row_id."_project_site_id"] = $stock_item->project_site_id;
                        }
                        project_sites_list_cells(null, $stock_item->row_id.'_project_site_id', $order->project_id, null,'');

                        if($_POST['stock_control_method'] == SKCM_LOTS || $_POST['stock_control_method'] == SKCM_SERIAL_NOS){
                            button_cell("UpdateItem", _("Update"), _('Confirm changes'), ICON_UPDATE);
                        }
                        else{
                            label_cell("");
                        }

                        check_cells(null, $stock_item->row_id.'_check_ppr_item');
                    
                    end_row();
		}
            }

        end_table(2);
    div_end();
}

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

function mrt_options_controls()
{
	  echo "<br>";
	  start_table();

	  textarea_row(_("Purchase Requisition Return Comment:"), 'memo_', null, 50, 3);

	  end_table(1);
}

function can_process_prr() {
    $total_qty = 0;

    if (! is_date($_POST['prr_date'])) {
        display_error( _("Date entered is invalid."));
        set_focus('prr_date');
        return false;
    }
    
    if (!is_date_in_fiscalyear($_POST['prr_date'])) {
        display_error(_("The entered invoice date is not in fiscal year."));
        set_focus('prr_date');
        return false;
    }
        
    $msg = is_accounting_period_open($_POST['prr_date']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']);
        set_focus('prr_date');
        return false;
    }
    
    foreach ($_SESSION['prr_items']->line_items as $line_item) {
        if (isset($_POST[$line_item->row_id.'_check_ppr_item']) && $_POST[$line_item->row_id.'_check_ppr_item'] == true) {
            
            $row_id = $line_item->row_id;
            
            if (! check_num($line_item->row_id.'_tran_qty',0)) {
                display_error(_("Record #$row_id : The quantity entered is negative or invalid."));
                set_focus($line_item->row_id."_tran_qty");
                return false;
            }
            
            if (! (isset($line_item->task_id) && $line_item->task_id > 0)) {
                display_error("Record #$row_id : No budget selected.");
                set_focus($line_item->row_id."_tran_qty");
                return false;
            }
            
            $line_item->check_issue_item = true;
            
            $total_qty += input_num($line_item->row_id."_tran_qty");
        } else {
            $line_item->check_issue_item = false;
        }
    }     

    if ($total_qty == 0) { 
        display_error(_("No lines with valid quantities selected."));
        set_focus($line_item->row_id."_tran_qty");
        return false;
    }
    
    if (strlen($_POST['prr_reference']) == 0) {
        display_error( _("You must enter a reference."));
        set_focus('prr_reference');
        return false;
    }

    $ref_msg = reference_exists($_POST['prr_reference'], ST_PR_RETURN);
    if (strlen($ref_msg) > 0) {
        display_error($ref_msg);
        set_focus('prr_reference');
        return false;
    }

    if (!(strlen($_POST['group_company_employee_code']) > 1)) { 
        display_error(_("Please select an employee."));
        set_focus('group_company_employee_code');
        return false;
    }
    
    foreach ($_SESSION['prr_items']->line_items as $line_item) {		
	            		
        $stock_id = $line_item->stock_id;     
        get_convertion_factor2($stock_id, $_POST[$line_item->row_id.'_tran_unit'], $convesion_factor);
        
        if (isset($_POST[$line_item->row_id.'_check_ppr_item']) && $_POST[$line_item->row_id.'_check_ppr_item'] == true) {

            $row_id = $line_item->row_id;
            $issued_qty = $line_item->qty; // issued qty converted to base qty
//            $issued_qty = $line_item->issued_qty;
            $returned_qty = $line_item->returned_qty;
            $base_qty = input_num($line_item->row_id.'_tran_qty') * $convesion_factor;
            
            $can_return_max_qty = ($issued_qty - $returned_qty);
                if ($can_return_max_qty > 0) {
                    if ($base_qty > $can_return_max_qty + 0.0000001) {
                        display_error(_("Record #$row_id : Entered returning quantity is hiegher than the maximum returnable quantity of ". number_format($can_return_max_qty/$convesion_factor, 2)."."));		
                        set_focus($line_item->row_id.'_tran_qty');		
                        return false;
                    }
                } else {
                    display_error(_("Record #$row_id : maximum returnable quantity is ". number_format($can_return_max_qty/$convesion_factor, 2)."."));	
                    set_focus($line_item->row_id.'_tran_qty');		
                    return false;
                }
        }
    }
    
    $vtqd_msg = validate_transaction_quantity_details($_SESSION['prr_items']);		
        if ($vtqd_msg['success'] !== true) {
            display_error($vtqd_msg['message']);
            return false;
        }

    return true;
}

?>