<?php

include_once($path_to_root . "/includes/common_functions.inc");

function add_material_transfer_receipt($items, $reference, $issuing_location, $receiving_location, $requesting_project_id, $memo_, $source_mtr_no, 
                                       $mtr_row_state, $company_code, $employee_code, $tran_date) {
    global $Refs;
    
    $type = ST_MATERIAL_TRANSFER_RECEIPT;
    $date = sql2date(date('Y/m/d'));

    $created_by = $_SESSION['wa_current_user']->user;

    begin_transaction();
    $args = func_get_args();
    $args = (object) array_combine(array('items', 'reference', 'issuing_location', 'receiving_location', 'project_id', '$memo_', 'source_mtr_no', 
                                         'mtr_row_state', 'company_code', 'employee_code', 'tran_date'), $args);
    $args->trans_no = 0;
    hook_db_prewrite($args, $type);

    if ($reference == '' || $reference == null) {
        $reference = get_next_trans_no($type);
    }

    $mt_rct_no = add_material_transfer_receipt_header($reference, $issuing_location, $receiving_location, $requesting_project_id, $memo_, $source_mtr_no, 
                                                      $created_by, $type, $company_code, $employee_code, $tran_date);

    if (!$mt_rct_no > 0) {
        cancel_transaction();
        return array("passed" => false, "message" => "Could not add material transfer receipt");
    }

    foreach ($items as $line_item) {
        if (isset($_POST[$line_item->row_id."_check"]) && $_POST[$line_item->row_id."_check"] == 1) {
        
            if ($line_item->tran_qty > 0) {
                
                $standard_cost = get_standard_cost($line_item->stock_id);
                 
                $qty = $line_item->tran_qty * $line_item->convertion_factor;

                $rcpt_row_id = add_material_transfer_receipt_details(ST_MATERIAL_TRANSFER_RECEIPT, $line_item->stock_id, $mt_rct_no, $issuing_location, 
                                                    $date, $reference, $qty, $standard_cost, 0, 0, $line_item->tran_unit, $line_item->tran_qty, 
                                                    $line_item->convertion_factor, $line_item->task_id, $line_item->project_site_id, $line_item->row_id);
                
                if (! ($rcpt_row_id > 0)) {
                    cancel_transaction();
                    return array("success" => false, "tran_no" => $mt_rct_no, "message" => 'Could not be add Material transfer receipt details.');
                }
                
                $mrt_line_row = get_mrt_deatails_record_by_id($line_item->row_id);
                // issue (transfer)
                add_stock_move(ST_MATERIAL_TRANSFER_RECEIPT, $line_item->stock_id, $mt_rct_no, $issuing_location, $date, $reference, 
                               -$line_item->tran_qty * $line_item->convertion_factor, $standard_cost, 0, 1, 0, 0, '', $line_item->tran_unit, -$line_item->tran_qty, 
                               $line_item->convertion_factor, $mrt_line_row['task_id'], $mrt_line_row['project_site_id'], $rcpt_row_id, $requesting_project_id);

                // receipt 
                add_stock_move(ST_MATERIAL_TRANSFER_RECEIPT, $line_item->stock_id, $mt_rct_no, $receiving_location, $date, $reference, 
                               $line_item->tran_qty * $line_item->convertion_factor, $standard_cost, 0, 1, 0, 0, '', $line_item->tran_unit, $line_item->tran_qty, 
                               $line_item->convertion_factor, $line_item->task_id, $line_item->project_site_id, $rcpt_row_id, $requesting_project_id);

                update_mrt_item_issued_qty($line_item->row_id);
                update_mtr_item_received_qty($line_item->row_id); // write on step 1 db table
            }
        }
    }

    $Refs->save(ST_MATERIAL_TRANSFER_RECEIPT, $mt_rct_no, $reference);
    add_audit_trail(ST_MATERIAL_TRANSFER_RECEIPT, $mt_rct_no, $date);


    
    //budget update 1 >> remove costs from issuing project budgets (2nd step selected budgets)
    //source transaction is the transfer
    
//    $mrt_details_array = array();
//    
//    $mrt_details = get_mrt_details_with_mr_receipt_details_by_mt_receipt_no($mt_rct_no);
//        while ($myrow = db_fetch($mrt_details)) {
//            $a['row_id'] = $myrow['trans_id'];
//            $a['stock_id'] = $myrow['stock_id'];
//            $a['task_id'] = $myrow['task_id'];
//            $a['requested_qty'] = 0;
//            $a['high_value_item'] = 0;
//            $a['reference_cost'] = $myrow['standard_cost'];
//            $a['standard_cost'] = $myrow['standard_cost'];
//            $a['total_issued_qty'] = 0;
//            $a['qty'] = $myrow['receipt_qty'];
//            
//            $mrt_details_array[] = $a;
//        }
    
    
//    $tasks_summary = calculate_task_remaining_totals($mrt_details_array);
//    
//    $mtrcp_msg = remove_costs_from_tasks(ST_MATERIAL_TRANSFER_RECEIPT, $mt_rct_no, $tasks_summary, $created_by);
//        if ($mtrcp_msg['success'] !== true) {
//            cancel_transaction();
//            return array("success" => $mtrcp_msg['success'], "tran_no" => $mt_rct_no, "message" => $mtrcp_msg['message']);
//        }

        
        
    $mtr_no = get_mtr_trans_no_by_mt_receipt_no($mt_rct_no);
        if (! ($mtr_no > 0)) {
            cancel_transaction();
            return array("success" => false, "tran_no" => $mt_rct_no, "message" => 'Unable to get MTR no.');
        }
        
    // budget update 2 >> Reallocate (allocate the balance qty costs to the requested project (step 1) budgets
//        
//        $mtr_header = get_mtr_header_record_by_id($mtr_no);
//        $mtr_details_array = array();
//        
//        $mtr_details = get_mtr_details($mtr_no);// read step 1 table
//
//            while ($myrow = db_fetch($mtr_details)) {
//                $a['row_id'] = $myrow['id'];
//                $a['stock_id'] = $myrow['stock_id'];
//                $a['task_id'] = $myrow['task_id'];
//                if ($mtr_header['approval_status'] == AS_CLOSED) {
//                    $a['requested_qty'] = $myrow['issued_qty']; // step 1 base unit qty
//                } else {
//                    $a['requested_qty'] = $myrow['requested_qty']; // step 1 base unit qty
//                }
//                
//                $a['high_value_item'] = $myrow['high_value_item'];
//                $a['reference_cost'] = $myrow['standard_cost'];
//                $a['standard_cost'] = $myrow['standard_cost'];
//                $a['total_issued_qty'] = $myrow['received_qty']; // step 1 total received qty
//                $a['qty'] = 0; 
//
//                $mtr_details_array[] = $a;
//            }

                
//    $mr_tasks_summary = calculate_task_remaining_totals($mtr_details_array);
//    
//    $ralo_msg = reallocate_to_tasks(ST_TRANSFERREQ, $mtr_no, $mr_tasks_summary, $created_by);// step 1 table trans no
//        if($ralo_msg['success'] !== true) {
//            cancel_transaction();
//            return array("success" => $ralo_msg['success'], "tran_no" => $mtr_no, "message" => $ralo_msg['message']);
//        }
    
    
    
    // budget update 3 >> add costs to receiving (requested) project (step 1) budgets
    // read receipt
//    $mi_details_array = array();
//    foreach ($items as &$line_item){
//        if (isset($_POST[$line_item->row_id."_check"]) && $_POST[$line_item->row_id."_check"] == 1) {
////        if($line_item->check_issue_item == true){
//            if($line_item->tran_qty > 0){
//                $qty = $line_item->tran_qty * $line_item->convertion_factor;
//                $b['row_id'] = $line_item->row_id;
//                $b['stock_id'] = $line_item->stock_id;
//                $b['task_id'] = $line_item->task_id;
//                $b['requested_qty'] = $qty;
//                $b['high_value_item'] = 0;
//                $standard_cost = get_standard_cost($line_item->stock_id);
//                $b['reference_cost'] = $standard_cost; 
//                $b['standard_cost'] = $standard_cost;
//                $b['total_issued_qty'] = $qty;
//                $b['qty'] = $qty;
//
//                $mi_details_array[] = $b;
//            }
//        }
//    }
//    
//    $mi_tasks_summary = calculate_task_remaining_totals($mi_details_array);
    
//    $mtrec_msg = charge_cost_to_tasks(ST_MATERIAL_TRANSFER_RECEIPT, $mt_rct_no, $mi_tasks_summary, $created_by);
//        if($mtrec_msg['success'] !== true) {
//            cancel_transaction();
//            return array("success" => $mtrec_msg['success'], "tran_no" => $mt_rct_no, "message" => $mtrec_msg['message']);
//        }

        
    $args->trans_no = $mt_rct_no;
    hook_db_postwrite($args, $type);
    
    $urs_msg = update_mtr_row_state($mtr_no, $mtr_row_state);
        if($urs_msg['success'] !== true) {
            cancel_transaction();
            return array("passed" => false, "tran_no" => $mtr_no, "message" => $urs_msg['message']);
        }

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

function add_material_transfer_receipt_header($reference, $issuing_location, $receiving_location, $project_id, $memo_, $source_mtr_no, $created_by, 
                                              $type, $company_code, $employee_code, $tran_date_) {
    $created_on = date('Y-m-d H:i:s');
    $tran_date = date2sql($tran_date_);

    $sql = "INSERT INTO " . TB_PREF . "material_requisition_transfers(reference,
                        issuing_location, receiving_location,
                        project_id, comments,
                        source_mtr_no, type, 
                        company_code, employee_code, 
                        created_by, created_on, tran_date) 
            VALUES (" . db_escape($reference) . ", "
            . db_escape($issuing_location) . ", " . db_escape($receiving_location) . ", "
            . db_escape($project_id) . ", " . db_escape($memo_) . ", "
            . db_escape($source_mtr_no) . ", ". db_escape($type) . ", "
            . db_escape($company_code) . ", ". db_escape($employee_code) . ", "
            . db_escape($created_by) . ", " . db_escape($created_on) . ", " . db_escape($tran_date) . ")";

    db_query($sql, 'add_material_transfer_receipt_header');
    return db_insert_id();
}

function get_mt_receipt_total_received_qty_by_ref_line_id($ref_line_id) {
    $sql = "SELECT SUM(qty) total_issued_qty 
            FROM ".TB_PREF."material_transfer_receipt_details   
            WHERE ref_line_id = ".db_escape($ref_line_id);

    $result = db_query($sql, 'get_mt_receipt_total_received_qty_by_ref_line_id');
    return db_result_value($result, 'total_issued_qty');
}

function add_material_transfer_receipt_details($type, $stock_id, $trans_no, $location, $date_, $reference, $quantity, $std_cost, $person_id=0, 
                                               $price=0, $tran_unit="", $tran_qty=0, $convertion_factor=1, $task_id=0, $project_site_id=0, 
                                               $reference_line_id=0) {
    $date = date2sql($date_);

	$sql = "INSERT INTO ".TB_PREF."material_transfer_receipt_details (stock_id, trans_no, 
                    type, loc_code,
                    tran_date, person_id, 
                    reference, qty, 
                    standard_cost, price,  
                    tran_unit, tran_qty, 
                    convertion_factor, task_id,
                    project_site_id, ref_line_id) 
            VALUES (".db_escape($stock_id).", ".db_escape($trans_no).", "
                    .db_escape($type).", ".db_escape($location).", "
                    .db_escape($date).", ".db_escape($person_id).", "
                    .db_escape($reference).", ".db_escape($quantity).", "
                    .db_escape($std_cost).", ".db_escape($price).", "
                    .db_escape($tran_unit).", ".db_escape($tran_qty).","
                    .db_escape($convertion_factor).", ".db_escape($task_id).", "
                    .db_escape($project_site_id).", ".db_escape($reference_line_id).")";

	db_query($sql, 'add_material_transfer_receipt_details');
	return db_insert_id();
}

function get_material_transfer_receipt_details($mt_rct_no) {
    $sql = "SELECT mtrcd.*, 
                sm.units,
                sm.description,
                pt.description task_description,
                sm.high_value_item,
                sm.sample_item,
                sm.reference_cost, 
                sm.material_cost + sm.labour_cost + sm.overhead_cost AS standard_cost, 
                sm.stock_control_method,
                ps.description project_site_description 
                
            FROM ".TB_PREF."material_transfer_receipt_details mtrcd 
                INNER JOIN ".TB_PREF."stock_master sm 
                    ON mtrcd.stock_id = sm.stock_id 
                LEFT JOIN ".TB_PREF."project_sites ps 
                    ON mtrcd.project_site_id = ps.id 
                LEFT JOIN ".TB_PREF."project_tasks pt 
                    ON mtrcd.task_id = pt.task_id 
            WHERE mtrcd.trans_no = ".db_escape($mt_rct_no)." 
            ORDER BY mtrcd.id";
    
        return db_query($sql, "get_material_transfer_receipt_details");
}

function get_mrt_details_with_mr_receipt_details_by_mt_receipt_no($mt_rct_no) {
    $sql = "SELECT mrtd.*,
                    mtrd.qty receipt_qty, 
                    sm.material_cost + sm.labour_cost + sm.overhead_cost AS standard_cost 
            FROM ".TB_PREF."material_requisition_transfer_details mrtd  
                JOIN ".TB_PREF."material_transfer_receipt_details mtrd    
                    ON mrtd.trans_id = mtrd.ref_line_id 
                JOIN ".TB_PREF."stock_master sm   
                    ON mrtd.stock_id = sm.stock_id
            WHERE mtrd.trans_no = ".db_escape($mt_rct_no);
    
    return db_query($sql, 'get_mrt_details_with_mr_receipt_details_by_mt_receipt_no');
}

function get_mtr_trans_no_by_mt_receipt_no($mt_rct_no) {
    $sql = "SELECT mtr.mtr_no 
            FROM ".TB_PREF."material_requisition_transfers rcp 
                JOIN ".TB_PREF."material_requisition_transfers mrt  
                    ON rcp.source_mtr_no = mrt.mrt_no 
                JOIN ".TB_PREF."material_transfer_requisitions mtr   
                    ON mrt.source_mtr_no = mtr.mtr_no 
            WHERE rcp.mrt_no = ".db_escape($mt_rct_no);
    
        $result = db_query($sql, 'get_mtr_trans_no_by_mt_receipt_no');
        return db_result_value($result, 'mtr_no');
}

function get_mtr_line_no_by_mt_receipt_line_no($mt_rct_line_no) {
    $sql = "SELECT mtr.id 
            FROM ".TB_PREF."material_transfer_receipt_details rcp 
                JOIN ".TB_PREF."material_requisition_transfer_details mrt  
                    ON rcp.ref_line_id = mrt.trans_id  
                JOIN ".TB_PREF."material_transfer_requisition_details mtr   
                    ON mrt.ref_line_id = mtr.id  
            WHERE rcp.id = ".db_escape($mt_rct_line_no);
    
        $result = db_query($sql, 'get_mtr_line_no_by_mt_receipt_line_no');
        return db_result_value($result, 'id');
}

function get_mt_receipt_total_received_qty_by_mtr_line_id($mtr_line_id) {
    $sql = "SELECT SUM(rcp.qty) total_received_qty 
            FROM ".TB_PREF."material_transfer_requisition_details mtr   
                JOIN ".TB_PREF."material_requisition_transfer_details mrt  
                    ON mtr.id = mrt.ref_line_id   
                JOIN ".TB_PREF."material_transfer_receipt_details rcp 
                    ON mrt.trans_id = rcp.ref_line_id  
            WHERE mtr.id = ".db_escape($mtr_line_id);

    $result = db_query($sql, 'get_mt_receipt_total_received_qty_by_mtr_line_id');
    return db_result_value($result, 'total_received_qty');
}

function get_mt_receipt_total_received_qty_by_mrt_line_id($mrt_line_id) {
    $sql = "SELECT SUM(rcp.qty) total_received_qty 
            FROM ".TB_PREF."material_requisition_transfer_details mrt  
                JOIN ".TB_PREF."material_transfer_receipt_details rcp 
                    ON mrt.trans_id = rcp.ref_line_id  
            WHERE mrt.trans_id = ".db_escape($mrt_line_id);

    $result = db_query($sql, 'get_mt_receipt_total_received_qty_by_mrt_line_id');
    return db_result_value($result, 'total_received_qty');
}

function check_all_mrt_lines_issued($mt_rqt_no) {
    $sql = "SELECT SUM(IF(qty - issued_qty > 0, 1, 0)) outstanding_line_count  
            FROM ".TB_PREF."material_requisition_transfer_details  
            WHERE trans_no = ".db_escape($mt_rqt_no);
    
    $result = db_query($sql, 'check_all_mrt_lines_issued');
    $line_count = db_result_value($result, 'outstanding_line_count');
    
        if ($line_count > 0) {
            return false;
        } else {
            return true;
        }
}

function get_material_transfers_receipt_headers_by_mt_req_no($mt_req_no) {
    $sql = "SELECT mtrc.*, u.real_name user_name,
                il.location_name issuing_location_name,
                rl.location_name receiving_location_name  
            FROM ".TB_PREF."material_requisition_transfers mrt 
                JOIN ".TB_PREF."material_requisition_transfers mtrc 
                    ON mrt.mrt_no = mtrc.source_mtr_no 
                    AND mtrc.type = ".db_escape(ST_MATERIAL_TRANSFER_RECEIPT)." 
                JOIN ".TB_PREF."users u  
                    ON mtrc.created_by = u.id 
                JOIN ".TB_PREF."locations il
                    ON mtrc.issuing_location = il.loc_code 
                JOIN ".TB_PREF."locations rl 
                    ON mtrc.receiving_location = rl.loc_code 
            WHERE mrt.type = ".db_escape(ST_REQTRANSFER)." 
                AND mrt.source_mtr_no = ".db_escape($mt_req_no)." 
            ORDER BY mtrc.source_mtr_no"; 
    
        return db_query($sql, "get_material_transfers_receipt_headers_by_mt_req_no");
}

function get_material_transfers_receipt_headers_by_mrt_no($mrt_no) {
    $sql = "SELECT mrt.*, u.real_name user_name,
                il.location_name issuing_location_name,
                rl.location_name receiving_location_name   
            FROM ".TB_PREF."material_requisition_transfers mrt 
                JOIN ".TB_PREF."users u  
                    ON mrt.created_by = u.id 
                JOIN ".TB_PREF."locations il
                    ON mrt.issuing_location = il.loc_code 
                JOIN ".TB_PREF."locations rl 
                    ON mrt.receiving_location = rl.loc_code 
            WHERE mrt.type = ".db_escape(ST_MATERIAL_TRANSFER_RECEIPT)." 
                AND mrt.source_mtr_no = ".db_escape($mrt_no);
    
        return db_query($sql, "get_material_transfers_receipt_headers_by_mrt_no");
}

function get_mtr_header_by_mt_receipt_no($mt_rct_no) {
    $sql = "SELECT mtr.*  
            FROM ".TB_PREF."material_requisition_transfers rcp 
                JOIN ".TB_PREF."material_requisition_transfers mrt  
                    ON rcp.source_mtr_no = mrt.mrt_no 
                JOIN ".TB_PREF."material_transfer_requisitions mtr   
                    ON mrt.source_mtr_no = mtr.mtr_no 
            WHERE rcp.mrt_no = ".db_escape($mt_rct_no);
    
        $result = db_query($sql, 'get_mtr_header_by_mt_receipt_no');
        return db_fetch($result);
}

?>