<?php
/**********************************************************************
***********************************************************************/
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/ui/items_cart.inc");

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


function crete_purchase_requisition_returns_for_credit_note($supp_trans, $cn_no, $date_)
{
    
    $batch_no = uniqid();
    $prr_ids_array = array();
    
    foreach ($supp_trans->grn_items as $cn_item)
    {
        $prd = get_pr_issue_details_for_return($cn_item->id);
        if(is_array($prd)){   
            $max_returnable_qty = $prd['issued_qty'] - $prd['returned_qty'];
            if(!($max_returnable_qty > 0)){
                continue;
            }
    
            $prr_no = crete_pr_return_detail($cn_item, $prd, $batch_no, $cn_no, $date_);
            $prr_ids_array[] = $prr_no;
        }
    }
    
    $prr_ids = array_unique($prr_ids_array);
    if(!(count($prr_ids) > 0)){
        //Returning supplier invoices of GRNs with NO PR Issues
        return array("success" => true, "message" => "");
    }
    
    update_all_prr_header_totals($prr_ids);
    
    $msg = charge_all_purchase_requisition_returns($prr_ids_array);
//    display_db_error("stop", null, true);
//		exit;
    

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

    return array("success" => true, "message" => "");
}


function charge_all_purchase_requisition_returns($prr_ids_array)
{
    foreach ($prr_ids_array as $prr_no) {
        $msg = charge_each_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" => $msg['success'], "message" => "");
}

function charge_each_purchase_requisition_return($prr_no)
{
//    $prr_total = get_prr_lines_header_total($prr_no);
//
//    update_pr_return_header_total($prr_no, $prr_total);
    
    $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($entered_grn, $prd, $batch_no, $cn_no, $date_)
{
    $type = ST_PR_RETURN;
    $pri_no = $prd['pri_no'];
    $pr_no = $prd['pr_no'];
    
    $prr_h = get_pr_return_record_by_batch_no($batch_no, $pri_no);
    if(is_array($prr_h)){
        $prr_no = $prr_h['prr_no'];
        $location = $prr_h['location'];
        $prr_date = $prr_h['prr_date'];
    }
    else{
        $reference = get_next_reference_for_auto_generation($type);
        $location = $prd['location'];
        $prr_date = date2sql($date_);
        $project_id = $prd['project_id'];
        $grn_no = $prd['grn_no'];
        $comment = "";
        $item_code = $entered_grn->item_code;
        $description =  $entered_grn->item_description;
//        $qty = $entered_grn->this_quantity_inv;
        
        $prr_no = add_pr_return_header($batch_no, $reference, $location, $prr_date, $project_id, 
                                        $pr_no, $pri_no, $grn_no, $cn_no, $comment);
        
    }
    

    $pri_line_id = $prd['id'];
    $item_code = $entered_grn->item_code;
    $description =  $entered_grn->item_description;
    $qty = abs($entered_grn->this_quantity_inv);
    
    $max_returnable_qty = $prd['issued_qty'] - $prd['returned_qty'];
    if($qty > $max_returnable_qty){
        $qty = $max_returnable_qty;
    }
    
//    $unit_cost = $entered_grn->taxfree_unit_price;
    $unit_price = $entered_grn->taxfree_unit_price;
    $tran_unit = $entered_grn->po_unit; 
    $tran_qty = abs($entered_grn->this_quantity_inv_po_unit);
    $conversion_factor = $entered_grn->po_unit_conv_factor; 
    $pr_line_id = $prd['pr_line_id'];
    $task_id = $prd['task_id'];
    $project_site_id = $prd['project_site_id'];
    $grn_item_id = $entered_grn->id;
    $cn_line_id = $entered_grn->invoice_line_id;
    $cost_source = "CN Line".$entered_grn->invoice_line_id;
    
    $prr_detail_id = add_pr_return_item($prr_no, $pri_line_id, $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);
    
    $stock_item = get_stock_item_edit_info($entered_grn->item_code);
    if(in_array($stock_item['mb_flag'], array('B', 'M'))){
        $std_cost = $stock_item['standard_cost'];
        $person_id = 0;
        $discount_percent = $entered_grn->chg_price_discount;
        
        add_stock_move($type, $item_code, $prr_no, $location, $date_, $reference, $qty, $std_cost, 
                $person_id, 0, $unit_price, $discount_percent, '', 
                $tran_unit, $tran_qty, $conversion_factor, $task_id, $project_site_id, $prr_detail_id);
    }
    
    $total_returned_qty = get_pr_item_total_returned_qty($pr_line_id);
    
    $n1 = update_pr_item_returned_qty($pr_line_id, $total_returned_qty);
    
    
    return $prr_no;
            
}