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

//-------------------------------------------------------------------------------------------------------------
include_once($path_to_root . "/inventory/includes/db/material_requisitions_db.inc");
include_once($path_to_root . "/includes/common_functions.inc");

function add_petty_cash_item_issue($type, $source_type_id, $source_trans_no, $source_detail_id,
                                    $reference, $location, $project_id, $tran_date_,  
                                    $company_code, $employee_code, $comment)
{
	global $loc_notification, $path_to_root, $Refs, $systypes_array;

        $date_ = sql2date(date('Y/m/d'));
        $tran_date = date2sql($tran_date_);
        $user_id = $_SESSION['wa_current_user']->user;

	begin_transaction();

        $trans_no = get_next_trans_no($type);
    
        $h_id = add_petty_cash_item_issue_header($type, $trans_no, $reference, 
                                                $location, $project_id, 
                                                $tran_date, $source_detail_id, 
                                                $company_code, $employee_code, 
                                                $comment, $user_id);

        if(!$h_id > 0)
        {
            cancel_transaction();
            return array("passed" => false, "tran_no" => $trans_no, "message" => "Could not create ".$systypes_array[$type]);
        }

        if ($loc_notification == 1){
            include_once($path_to_root . "/inventory/includes/inventory_db.inc");
            $st_ids = array();
            $st_names = array();
            $st_num = array();
            $st_reorder = array();
        }
     
        
        $result = view_petty_cash_item_receive_items_by_source($source_type_id, $source_detail_id);
	while ($myrow = db_fetch($result)){
            $prefix = $myrow["id"];
            if (isset($_POST[$prefix.'_check_mr_item']) && $_POST[$prefix.'_check_mr_item'] == true){
                if ($loc_notification == 1){
                    $loc = calculate_reorder_level($location, $line_item, $st_ids, $st_names, $st_num, $st_reorder); 
                }

                $tran_qty = input_num($prefix.'_issuing_tran_unit_qty');
                if($tran_qty > 0){
                    $item_info = get_item_edit_info($myrow["stock_id"]);
                    $standard_cost = $item_info['standard_cost'];
                    $source_line_id = $myrow['id'];
                    $stock_id = $myrow['stock_id'];                    
                    $item_description = $_POST[$prefix.'_item_description'];
                    
                    $tran_unit = $_POST[$prefix.'_tran_unit'];                    
                    $conversion_factor = 1;
                    get_convertion_factor2($stock_id, $tran_unit, $conversion_factor);
                    $qty = $tran_qty * $conversion_factor;
                    $task_id = 0;
                    $site_id = 0;
                    add_petty_cash_item_issue_item($type, $trans_no,
                                    $source_line_id, $stock_id, $item_description, 
                                    $qty, $standard_cost, 
                                    $tran_unit, $tran_qty, $conversion_factor, 
                                    $task_id, $site_id);

                    if(is_inventory_item($stock_id)){
                        add_stock_adjustment_item($trans_no, $stock_id, $location, $tran_date_, 
                                        $reference, -$qty, $standard_cost, "", 
                                        $tran_unit, -$tran_qty, $conversion_factor, $type, 
                                        $task_id, $site_id, $source_line_id);
                    }


//                    $ailqdm_msg =  add_item_line_quantity_detail_movements($type, $trans_no, $location, 
//                                                                            $date, $line_item, false, '');
//                    if($ailqdm_msg['success'] !== true){
//                        cancel_transaction();
//                        return array("success" => $ailqdm_msg['success'], "tran_no" => $im_no, "message" => $ailqdm_msg['message']);
//                    }

                    $issued_qty_total = get_petty_cash_item_total_issued_qty($source_line_id);
                    $n = update_petty_cash_item_issued_qty($source_line_id, $issued_qty_total);
                    
                    if($n != 1)
                    {
                        cancel_transaction();
                        return array("success" => false, "tran_no" => $trans_no, "message" => "Could not create total issued quantity of item ".$stock_id);
                    }

                }
            }
        }
        
        $total_value = get_petty_cash_item_issue_total_value($type, $trans_no);
        update_petty_cash_item_issue_total_value($type, $trans_no, $total_value);

        $Refs->save($type, $trans_no, $reference);
        add_audit_trail($type, $trans_no, $date_);
	
//	if ($loc_notification == 1 && count($st_ids) > 0)
//		send_reorder_email($loc, $st_ids, $st_names, $st_num, $st_reorder);  
        

    
        commit_transaction();

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

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

function add_petty_cash_item_issue_header($type, $trans_no, $reference, 
                        $location, $project_id, 
                        $tran_date, $source_detail_id, 
                        $company_code, $employee_code, 
                        $comment, $user_id)
{
	//$mr_date = date2sql($date_);
        $created_on = date('Y-m-d H:i:s');

	$sql = "INSERT INTO ".TB_PREF."petty_cash_item_issues(
                        type, trans_no, reference, 
                        location, project_id, 
                        tran_date, source_detail_id, 
                        company_code, employee_code, 
                        comment, 
                        created_by, created_on) "
                
                . "VALUES (".db_escape($type).", ".db_escape($trans_no).", ".db_escape($reference).", "
                        .db_escape($location).", ".db_escape($project_id).", "
                        .db_escape($tran_date).", ".db_escape($source_detail_id).", "
                        .db_escape($company_code).", ".db_escape($employee_code).", "
                        .db_escape($comment).", "
                        .db_escape($user_id).", ".db_escape($created_on).")";

		$error_msg = "add_petty_cash_item_issue_header";

	db_query($sql, $error_msg);

	return db_insert_id();
}
//--------------------------------------------------------------------------------------------------

function add_petty_cash_item_issue_item($type, $trans_no,
                        $source_line_id, $stock_id, $item_description,
                        $qty, $unit_cost, 
                        $tran_unit, $tran_qty, $conversion_factor, 
                        $task_id, $site_id)
{
    $sql = "INSERT INTO ".TB_PREF."petty_cash_item_issue_details(
                        type, trans_no,
                        source_line_id, stock_id, item_description,
                        qty, unit_cost, 
                        tran_unit, tran_qty, conversion_factor, 
                        task_id, site_id) 
            VALUES (".db_escape($type).", ".db_escape($trans_no).", "
                        .db_escape($source_line_id).", ".db_escape($stock_id).", ".db_escape($item_description).", " 
                        .db_escape($qty).", ".db_escape($unit_cost).", "
                        .db_escape($tran_unit).", ".db_escape($tran_qty).", ".db_escape($conversion_factor).", "
                        .db_escape($task_id).", ".db_escape($site_id).")";
    
    db_query($sql, "add_petty_cash_item_issue_item");
}


function get_petty_cash_item_total_issued_qty($source_line_id)
{
    $sql = "SELECT SUM(qty) issued_qty_total 
            FROM ".TB_PREF."petty_cash_item_issue_details 
            WHERE source_line_id = ".db_escape($source_line_id);
    
    $result = db_query($sql, "get_petty_cash_item_total_issued_qty");
    
    return db_result_value($result, "issued_qty_total");
}

function update_petty_cash_item_issued_qty($row_id, $issued_qty_total)
{

	$sql = "UPDATE ".TB_PREF."petty_cash_stock_item_receipt_details  
                SET     issued_qty = ".$issued_qty_total." 
                WHERE   id = ".db_escape($row_id)." 
                        AND qty >= ".db_escape($issued_qty_total);

        $error_msg = "update_petty_cash_item_issued_qty";

	db_query($sql, $error_msg);

	return db_num_affected_rows();
}

function update_petty_cash_item_issue_total_value($type, $trans_no, $total_value)
{

	$sql = "UPDATE ".TB_PREF."petty_cash_item_issues   
                SET total = ".$total_value." 
                WHERE type = ".db_escape($type)." 
                        AND trans_no >= ".db_escape($trans_no);

        $error_msg = "update_petty_cash_item_issue_total_value";

	db_query($sql, $error_msg);

}




function get_petty_cash_item_issue_total_value($type, $trans_no)
{
    $sql = "SELECT SUM(qty * unit_cost) total_value 
            FROM ".TB_PREF."petty_cash_item_issue_details 
            WHERE type = ".db_escape($type)." 
                    AND trans_no = ".db_escape($trans_no);
    
    $result = db_query($sql, "get_petty_cash_item_issue_total_value");
    
    return db_result_value($result, "total_value");
}