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

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

function add_mio_to_cart(&$order, $new_item, $new_item_qty, $required_date, $line_comment)
{
    if ($order->find_cart_item($new_item))
    {
        display_error(_("For Part :") . $new_item . " " . "This item is already on this material requisition.  You can change the quantity requested of the existing line if necessary.");
    }
    else
    {
        $order->add_to_cart(count($order->line_items), $new_item, $new_item_qty, null, null, $required_date, $line_comment);
    }
}

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

function display_petty_cash_item_receive_source($stype, $sdid)
{
        $sd_res = view_petty_cash_item_receive_items_by_source($stype, $sdid);
        $sd = db_fetch($sd_res);
        $batch = view_petty_cash_item_receive_header($sd['type'], $sd['trans_no']);

        start_table(TABLESTYLE2, "width=60%");

        start_row();
            label_cells(_("Location"), $batch['location_name'], "class='tableheader2'");
            label_cells(_("Project"), $batch['project_description'], "class='tableheader2'");
            
        end_row();
        start_row();
            label_cells(_("Date"), sql2date($batch['tran_date']), "class='tableheader2'");            
            label_cells(_("Budget"), $batch['task_description'], "class='tableheader2'");
        end_row();
        start_row();
            label_cells(_("Invoice No"), $batch['bill_no'], "class='tableheader2'");
            label_cells(_("Batch No."), get_petty_cash_trans_view_str(ST_I_OWE_YOU_BATCH, $batch['iou_batch_no']), "class='tableheader2'");
        end_row();
        start_row();
            label_cells(_("Description"), $batch['expence_description'], "class='tableheader2'");
            label_cells(_("Amount"), $batch['expense_amount'], "class='tableheader2'");
        end_row();     
        start_row();
            label_cells(_("Expense Type"), $batch['expense_type_name'], "class='tableheader2'");
            
        end_row();
        
        end_table();
        
//        $_POST['stype'];
//$sdid = $_POST['sdid'];

        hidden('stype',$stype);
        hidden('sdid',$sdid);
        
        return $batch["source_detail_id"];
}

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

function display_petty_cash_item_issue_header($stype, $sdid)
{
    global $Ajax, $Refs;
    
    $Ajax->activate('group_company_employee_code');
    
    $h = get_petty_cash_item_receive_header_by_source($stype, $sdid);
    
    if(!isset_string_post('location')){
        $_POST['location'] = $h['location'];
    }

    start_outer_table(TABLESTYLE2, "width=65%"); // outer table
    table_section(1, "45%");
    ref_row(_("Reference:"), 'reference', '', $Refs->get_next(ST_PETTY_CASH_ITEM_ISSUE));
    locations_list_row(_("Issuing Location:"), 'location', null, false, false);
    
    table_section(2, "30%");
    date_row("Date:", "tran_date");

    table_section(3, "35%");
    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, '');
    
//    table_section(3, "30%");
    
//    yesno_list_row("Make Requisition Complete", "mr_complete");
    
    end_outer_table(1); // outer table
}


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

function display_petty_cash_item_issue_items($stype, $sdid)
{
	global $path_to_root, $Ajax;

        $Ajax->activate('items_table');
        
        div_start('items_table');
	start_table(TABLESTYLE, "width=98%");
    $th = array( _("Tran. #"), _("Location"), _("Date"), _("Itemcode"),_("Description") ,
                _("Unit"), _("Qty. Received"), _("Qty. Issued"), "Issuing Unit","Issuing Qty", "Comment", "");
    table_header($th);
        
//    $expense_category_res = get_petty_cash_expense_category_invoices(EC_STOCK_ITEM_RECEIPT, $trans_no);
//    while ($invoice = db_fetch($expense_category_res))
//	{
    
//        $row = get_petty_cash_item_receive_record($trans_type, $trans_no);
        
        $result = view_petty_cash_item_receive_items_by_source($stype, $sdid);


	$k = 0;
        $j = "";
        $total_cost = 0;                  
       
                
	while ($myrow = db_fetch($result))
	{   
            $prefix = $myrow["id"];
            
            alt_table_row_color($k);            

            label_cell($myrow["trans_no"], "align=center");
            label_cell($myrow["location_name"]);
            label_cell(sql2date($myrow["tran_date"]), "align=center");
            label_cell($myrow["stock_id"]);
            
            $_POST[$prefix.'_item_description'] = $myrow["item_description"];
            if($myrow["editable"]){
                text_cells(null, $prefix.'_item_description', null, 50, 500);
            }else{    
                label_cell($myrow["item_description"]);
                hidden($prefix.'_item_description', $myrow["item_description"]);
            }
            label_cell($myrow["tran_unit"]);
            
            $tran_unit_received_qty = $myrow["tran_qty"];
            label_cell(number_format($tran_unit_received_qty, 2), "align=right");   
            
            $tran_unit_issued_qty = $myrow["issued_qty"] / $myrow["conversion_factor"];
            label_cell(number_format($tran_unit_issued_qty, 2), "align=right");              
            
            units_list_cells(null, $prefix.'_tran_unit', $myrow["stock_id"], null, false, true);
            
            $issuing_unit = $_POST[$prefix.'_tran_unit'];
            $issuing_convesion_factor = 1;
            get_convertion_factor2($myrow["stock_id"], $issuing_unit, $issuing_convesion_factor);
            $suggested_qty = ($myrow["qty"] - $myrow["issued_qty"]) / $issuing_convesion_factor;
            
            set_post_not_set_numeric($prefix.'_issuing_tran_unit_qty', $suggested_qty);
//            $_POST[$prefix.'_issuing_tran_unit_qty'] = $suggested_qty;
            
            qty_cells(null,$prefix.'_issuing_tran_unit_qty', null, null, null, 3);

            label_cell($myrow["comment"]);    
            
            check_cells(null, $prefix.'_check_mr_item');

            end_row();          

            $j++;

//            $total_cost += $line_total ;                
	} 
        
        start_row();
            label_cell(text_bold("Total :"), "colspan=8 align=right");
            amount_cell($total_cost, true);
            label_cell("", "colspan=2");
        end_row();
                                                 
        
        end_table(2);
	div_end();
}

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

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

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

	  end_table(1);
}


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

//function view_requisition_transfer_header($mrt_no, $suppress_view_link=false)
//{
//    $myrow = get_material_issue_header($mrt_no);
//
//    if (strlen($myrow[0]) == 0)
//    {
//    	display_note(_("The material requisition transfer sent is not valid."));
//    	exit;
//    }
//
//   	start_table(TABLESTYLE, "width=80%");
//
//	$th = array(_("#"), _("Reference"), _("Issuing Location"), _("Receiving Location"),
//			_("Source MR No"), _("Date"), _("Issued By"));
//
//	table_header($th);
//	start_row();
//	if ($suppress_view_link)
//		label_cell($myrow["mrt_no"]);
//	else
//		//label_cell(get_trans_view_str(ST_MATERIAL_ISSUE, $myrow["mrt_no"]));
//            label_cell(get_inventory_trans_view_str(ST_MATERIAL_ISSUE, $myrow["mrt_no"]), "class='tableheader2'");
//        
//	label_cell($myrow["reference"]);
//	label_cell($myrow["issuing_location_name"]);
//	//view_stock_status_cell($myrow["stock_id"], $myrow["StockItemName"]);
//	label_cell($myrow["receiving_location_name"]);
//        label_cell(get_trans_view_str(ST_MATERIAL_REQ, $myrow["source_mtr_no"]));
//	label_cell(sql2date($myrow["created_on"]));
//        label_cell($myrow["created_user_name"]);
//
//	end_row();
//
//	comments_display_row(ST_MATERIAL_ISSUE, $mrt_no);
//
//	end_table();
//
//}
//
////---------------------------------------------------------------------------------
//
//function view_material_requisition_transfer_details($mrt_no, $suppress_view_link=false)
//{
//    $result = get_material_issue_details($mrt_no, ST_REQTRANSFER);
//
//   	start_table(TABLESTYLE, "width=80%");
//
//	$th = array(_("Itemcode"), _("Item Description"), _("Qualtity"));
//
//	table_header($th);
//        
//        while ($myrow = db_fetch($result)){
//            if($myrow["qty"] > 0){
//                start_row();
//
//                label_cell($myrow["stock_id"]);
//                view_stock_status_cell($myrow["stock_id"], $myrow["description"]);
//
//                $quantity = $myrow["qty"];
//
//                $dec = get_qty_dec($myrow["stock_id"]);
//                qty_cell($quantity, false, $dec);
//
//
//                end_row();
//            }
//        }
//
//
//	end_table();
//
//}
//

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



function can_process_petty_cash_item_issue($type, $source_type_id, $source_detail_id)
{
    global $Refs, $approval_statuses;

        
    if (strlen($_POST['reference']) == 0){
        display_error( _("You must enter a reference."));
        set_focus('reference');
        return false;
    }

    $ref_msg = reference_exists($_POST['reference'], $type);
    if ($ref_msg) 
    {
        display_error( _($ref_msg));
        set_focus('reference');
        return false;
    }
    
    
    if(!is_date($_POST['tran_date'])){ 
        display_error(_("Date entered is invalid."));
        set_focus('tran_date');
        return false;
    }
    
    if(!(strlen($_POST['group_company_employee_code']) > 1)){ 
        display_error(_("Please select an employee."));
        set_focus('group_company_employee_code');
        return false;
    }
    
    
    $total_qty = 0;


    $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($myrow["editable"]){
                        if(!(strlen($_POST[$prefix.'_item_description']) > 0)){
                            display_error(_("Item - ".$myrow["stock_id"]." : Description can not be empty."));
                            set_focus($prefix.'_item_description');
                            return false;
                        }
                    }
                    
                    if (!check_num($prefix.'_issuing_tran_unit_qty',0))
                    {
                        display_error(_("Item - ".$myrow["stock_id"]." : Quantity entered is negative or invalid."));
                        set_focus($prefix.'_tran_qty');
                        return false;
                    }

                    $tran_qty = input_num($prefix.'_issuing_tran_unit_qty');
                    $issued_qty = $myrow["issued_qty"];
                    $tran_unit =  $_POST[$prefix.'_tran_unit'];
                    $convesion_factor = 1;
                    get_convertion_factor2($myrow["stock_id"], $tran_unit, $convesion_factor);
                    $total_issue_tran_qty = $tran_qty + ($issued_qty/$convesion_factor);
                    if($total_issue_tran_qty > $myrow["tran_qty"]){
                        $this_issue_max = $total_issue_tran_qty - $myrow["tran_qty"];                    
                        display_error(_("Item - ".$myrow["stock_id"]." : Quantity entered will create a total issue of ".number_format($total_issue_tran_qty,2).". Maximum allowed quantity for this issue is ".number_format($this_issue_max,2)));
                        set_focus($prefix.'_tran_qty');
                        return false;
                    }

                    $total_qty += $tran_qty;
            }
    }     

    if($total_qty == 0){ 
        display_error(_("No lines with valid quantities selected."));
        set_focus($line_item->row_id."_tran_qty");
        return false;
    }
    

/*
    foreach ($_SESSION['im_items']->line_items as $line_item) {		
	            		
        if($_POST[$line_item->row_id.'_tran_qty'] > $line_item->requested_qty + $line_item->issued_qty)		
        {		
            display_error(_("Issuing quantity can not be greater than the sum of requested quantity and issued quantity."));		
            set_focus($line_item->row_id.'_tran_qty');		
            return false;		
        }		
	}
*/    
    
//    $vtqd_msg = validate_transaction_quantity_details($_SESSION['im_items']);		
//    if ($vtqd_msg['success'] !== true) 		
//    {
//        display_error($vtqd_msg['message']);
//        return false;
//    }

        
    return true;
}


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

function create_petty_cash_item_issue($close_mr = false)
{
    $stype = $_POST['stype'];
    $sdid = $_POST['sdid'];
    $type = ST_PETTY_CASH_ITEM_ISSUE;
    
    if(!can_process_petty_cash_item_issue($type, $stype, $sdid)){
        return;
    }

    $h = get_petty_cash_item_receive_header_by_source($_POST['stype'], $_POST['sdid']);
    
    $aim_msg = add_petty_cash_item_issue($type, $stype, $h['source_trans_no'], $sdid,
                                    $_POST['reference'], $_POST['location'], $h['project_id'], $_POST['tran_date'],  
                                    $_POST['group_company_code'], $_POST['group_company_employee_code'], $_POST['memo_']);  
    

                
    if($aim_msg['success'] !== true){
        display_error($aim_msg['message'] );
        return;
    }
    
    $trans_no = $aim_msg['trans_no']; 
    meta_forward($_SERVER['PHP_SELF'], "Added_ID=$trans_no&Type_ID=$type"); 
          
    
}




function check_petty_cash_item_data()
{
	if (!check_num('tran_qty',0.01))
	{
		display_error(_("The quantity entered is negative or invalid."));
		set_focus('tran_qty');
		return false;
	}
   	return true;
}

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

function close_petty_cash_item_receipt($mr_no){
    
        if(!can_close_material_requisition()){
            return;
        }
        $cmr_msg = close_mr($mr_no, AS_CLOSED);
        if($cmr_msg['success'] !== true){
            display_error($cmr_msg['message']);
        }
        else{
            set_session_variable('im_messages', "Material requisition ".$mr_no." has been closed");
            end_processing($mr_no); 
        }
}


function can_close_material_requisition()
{

    if(!($_SESSION['im_items']->approval_status == AS_APPROVED || $_SESSION['im_items']->approval_status == AS_ISSUED))
    {
        display_error("Status of this Material Requisition does not allow closing it.");
        return false;
    }
        
    return true;
}


