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



function check_stock_count_detail_data($selected_id, $stock_count_id)
{
    $sch = get_stock_count_header_record($stock_count_id);
    if ($sch['status_id'] != SC_COUNTING){
		display_error(_("Status of this stock count does not allow updating its details."));
		set_focus('tran_uni_good_qty_'.$selected_id);
		return false;
	}
    
    if(!(isset($_POST['stock_id_'.$selected_id]) && strlen($_POST['stock_id_'.$selected_id]) > 0)){
		display_error(_("Please select an item"));
		set_focus('stock_id_'.$selected_id);
		return false;
	}
    
    if(isset($_POST['AddItem'])){
        $sc_item = check_stock_count_item_exists($stock_count_id, $_POST['stock_id_'.$selected_id]);
        if(isset($sc_item['sheet_no'])){
            display_error(_("Selected item already entered in sheet number ".$sc_item['sheet_no']));
            set_focus('stock_id_'.$selected_id);
            return false;
        }
    }

    if (($_POST['tran_unit_'.$selected_id] ==-1 || strlen($_POST['tran_unit_'.$selected_id]) == 0)){
            display_error(_("Please transaction unit."));
            set_focus('tran_unit_'.$selected_id);
            return false;
    }
    
    if (!(input_num('line_sheet_no_'.$selected_id) > 0)){
            display_error(_("Sheet number has to a positive value."));
            set_focus('line_sheet_no_'.$selected_id);
            return false;
    }
    
    if (!(check_num('tran_unit_good_qty_'.$selected_id, 0))){
            display_error(_("Good qunatity entered should be zero or higher."));
            set_focus('tran_unit_good_qty_'.$selected_id);
            return false;
    }
    
    
    if (!(check_num('tran_unit_damaged_qty_'.$selected_id, 0))){
            display_error(_("Damaged qunatity entered should be zero or higher."));
            set_focus('tran_unit_damaged_qty_'.$selected_id);
            return false;
    }
    
//    if(!(input_num('good_qty') > 0 || input_num('damaged_qty') > 0)) 
//	{
//		display_error( _("Either good quantity or damaged quantity should be positive."));
//		set_focus('ref');
//		return false;
//	}
	
	return true;
}

function can_delete_stock_count_detail($selected_id, $stock_count_id)
{
    $sch = get_stock_count_header_record($stock_count_id);
    if ($sch['status_id'] != SC_COUNTING){
            display_error(_("Status of this stock count does not allow updating its details."));
//            set_focus('tran_uni_good_qty_'.$selected_id);
            return false;
    }
    
    $scd = get_stock_count_detail($selected_id);
    if (!(in_array($scd['status_id'], array(0, SC_NEW, SC_COUNTING)))){
            display_error(_("Status of this stock count detail item does not allow updating it."));
//            set_focus('tran_uni_good_qty_'.$selected_id);
            return false;
    }
    
    
//    if(!(input_num('good_qty') > 0 || input_num('damaged_qty') > 0)) 
//	{
//		display_error( _("Either good quantity or damaged quantity should be positive."));
//		set_focus('ref');
//		return false;
//	}
	
	return true;
}



function validate_counting_header($stock_count_id)
{
    $ref = check_stock_count_reference($stock_count_id, $_POST['reference']);
    if(!$ref){
        return true;
    }
    else{
        return false;
    }
}

function update_counting_header($stock_count_id)
{
    $header_ref = validate_counting_header($stock_count_id);
    if($header_ref === false){
        return array("passed" => false, "message" => _("Reference exists already."));
    }
    
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date("Y-m-d H:i:s");
    
    update_stock_count_header($stock_count_id,
                            $_POST['reference'], $_POST['loc_code'], $_POST['tran_date'],
                            $_POST['comments'], $updated_by, $updated_on, SC_COUNTING,
                            $_POST['project_id'], $_POST['task_id']);
     
    $result = get_stock_count_details($stock_count_id);
    
    while ($myrow = db_fetch($result))
    {
        if(check_num($myrow["stock_id"])){
            update_stock_count_details($stock_count_id, $myrow["stock_id"], 
                    input_num($myrow["stock_id"]), $updated_on, $updated_by);
        }
    }
    return array("passed" => true, "message" => _("Stock Count $stock_count_id has been updated."));
}






function display_stock_count_details($stock_count_id, $selected_id)
{
//    set_global_stock_item($_POST['stock_id']);

    $sheet_no = $_POST['sheet_no'];
    
    start_table(TABLESTYLE, "width=98%");

    $th = array(_("Itemcode"),_("Description"), 
        
                nl2br("Tran \r\n Unit"), 
                nl2br("Sheet \r\n No."), 
        
                nl2br("Tran \r\n Unit \r\n Good \r\n Qty"), 
                nl2br("Tran \r\n Unit \r\n Damaged \r\n Qty"),
        
                nl2br("Base \r\n Unit"), 
                nl2br("Conv. \r\n Factor"), 
        
                nl2br("Base \r\n Unit \r\n Good \r\n Qty"), 
                nl2br("Base \r\n Unit \r\n Damaged \r\n Qty"), 
        
                nl2br("Base \r\n Unit \r\n System \r\n Qty"),"", "");
    
    table_header($th);

    $j = 1;
    $k = $count = 0; //row colour counter

    $result = get_stock_count_details($stock_count_id, $sheet_no);

    if (@$_GET['popup'])
    {
        hidden('_tabs_sel', get_post('_tabs_sel'));
        hidden('popup', @$_GET['popup']);
    }
    while ($myrow = db_fetch($result))
    {
        if($selected_id != $myrow["id"]){
            $dec = '2';
            alt_table_row_color($k);

            label_cell($myrow["stock_id"]);
            label_cell($myrow["description"]);
            
            label_cell($myrow["tran_unit_name"]);
            label_cell($myrow["sheet_no"], "align=center");
            
            label_cell(number_format($myrow["tran_unit_good_qty"], $dec), "align=right");
            label_cell(number_format($myrow["tran_unit_damaged_qty"], $dec), "align=right");           
            
            label_cell($myrow["base_unit_name"]);
            label_cell($myrow["conversion_factor"], "align=right");
            
            label_cell(number_format($myrow["good_qty"], $dec), "align=right");
            label_cell(number_format($myrow["damaged_qty"], $dec), "align=right");
            
             label_cell(number_format($myrow["system_qty"], $dec), "align=right");
            
            
            edit_button_cell("Edit".$myrow["id"], _("Edit"));    
            delete_button_cell("Delete".$myrow["id"], _("Delete"));

            end_row();
            $j++;
            If ($j == 25)
            {
                $j = 1;
                table_header($th);
            }
        }
        else{
            start_row();
            $m = "This will NOT update system quantity and standard cost to their latest values. "
                    . "If the item has been counted again at a later time delete this line and re-enter. "
                    . " \r\n That will update system quantity and standard cost to their latest values.";
            label_cell( "<font color='red'>".nl2br($m)."</font>","colspan=13 align=center");
            
            end_row();
            display_stock_count_details_edit_controls($stock_count_id, $selected_id);
        }
        
        $count++;
    }
    
    if(!($selected_id > 0)){
        display_stock_count_details_edit_controls($stock_count_id, $selected_id);
    }
    
    start_row();
    label_cell("No of records: ".$count, "colspan=13");
    end_row();
    end_table(1);

    hidden('selected_id', $selected_id);

}

function display_stock_count_details_edit_controls($stock_count_id, $selected_id)
{
    if($selected_id> 0){
        $sc_detail = get_stock_count_detail($selected_id);
    }
    
    start_row();
    if($selected_id> 0){
        $stock_id = $sc_detail['stock_id'];
        label_cell($stock_id);
        label_cell($sc_detail['item_description']);
//        label_cell($sc_detail['unit_name']);
        
        $_POST['good_qty_'.$selected_id] = $sc_detail['good_qty'];
        $_POST['damaged_qty_'.$selected_id] = $sc_detail['damaged_qty'];
        $_POST['line_sheet_no_'.$selected_id] = $sc_detail['sheet_no'];
        
        $_POST['tran_unit_good_qty_'.$selected_id] = $sc_detail['tran_unit_good_qty'];
        $_POST['tran_unit_damaged_qty_'.$selected_id] = $sc_detail['tran_unit_damaged_qty'];
        
        if(!(isset($_POST['tran_unit_'.$selected_id]) && strlen($_POST['tran_unit_'.$selected_id]))){
            $_POST['tran_unit_'.$selected_id] = $sc_detail['tran_unit'];
        }
        $_POST['conversion_factor_'.$selected_id] = $sc_detail['conversion_factor'];
        
        units_list_cells(null, 'tran_unit_'.$selected_id, $stock_id, null, 'Select unit', true);
//        hidden('unit', $sc_detail['unit']);
        hidden('stock_id_'.$selected_id, $sc_detail['stock_id']);
    }
    else{
        stock_items_list_cells(null, 'stock_id_'.$selected_id, null, false, true);
        $stock_id = $_POST['stock_id_'.$selected_id];
//        $item = get_stock_item_edit_info($_POST['stock_id']);
        
        units_list_cells(null, 'tran_unit_'.$selected_id, $stock_id, null, 'Select unit', true);
        
        
//        label_cell($item['unit_name']);
        
        $_POST['good_qty_'.$selected_id] = 0;
        $_POST['damaged_qty_'.$selected_id] = 0;
        if($_POST['sheet_no'] > 0){
            $_POST['line_sheet_no_'.$selected_id] = $_POST['sheet_no'];
        }
        else{
            $_POST['line_sheet_no_'.$selected_id] = 1;
        }
//        hidden('unit', $item['units']);
    }
    
    small_qty_cells(null, 'line_sheet_no_'.$selected_id, null, null, null, 0);
    amount_cells(null, 'tran_unit_good_qty_'.$selected_id);
    amount_cells(null, 'tran_unit_damaged_qty_'.$selected_id);
    
    if($selected_id> 0){
        hidden('base_unit_'.$selected_id, $sc_detail['unit']);
        label_cell($sc_detail['base_unit_name']);
    }
    else{
        $stock_item = get_stock_item_edit_info($_POST['stock_id_'.$selected_id]);
        hidden('base_unit_'.$selected_id, $stock_item['units']);
        label_cell($stock_item['unit_name']);
    }
    
    label_cell('');
    label_cell('');
    label_cell('');
    label_cell('');
    
    if ($selected_id > 0)
	{
		button_cell('UpdateItem', _("Update"),
				_('Confirm changes'), ICON_UPDATE);
		button_cell('CancelItemChanges', _("Cancel"),
				_('Cancel changes'), ICON_CANCEL);
		hidden('LineNo', $selected_id);
 		set_focus('qty');
	}
	else
	{
		submit_cells('AddItem', _("Add Item"), "colspan=2",
		    _('Add new item to document'), true);
	}
    
    end_row();
//    end_table();
//    div_end();
}

function can_end_count($stock_count_id)
{
    $can_end_count = true;
    $result = get_stock_count_duplicate_items($stock_count_id);
    
    while ($row = db_fetch($result)) {
        $can_end_count = false;
        display_error("Not posible to End counting due to below duplicate counted items:");
        $itemq = get_stock_count_duplicate_item_details($stock_count_id, $row['stock_id']);
        while ($item = db_fetch($itemq)) {
            $l = "Stock item ".$item['stock_id']." - ".$item['item_description']." in sheet No ".$item['sheet_no'];
            display_error($l);
        }
    }

    if($can_end_count == false){
        
        return false;
    }
    
    return true;
}


function build_stock_count_detail_array(&$sc_item, $selected_id, $stock_count_id)
{
    
    $sc_item['selected_id'] = $selected_id;
    
    $sc_item['stock_count_id'] = $stock_count_id;
    $sc_item['stock_id'] = $_POST['stock_id_'.$selected_id];
    $sc_item['tran_unit'] = $_POST['tran_unit_'.$selected_id];
    
    $sc_item['tran_unit_good_qty'] = input_num('tran_unit_good_qty_'.$selected_id);
    $sc_item['tran_unit_damaged_qty'] = input_num('tran_unit_damaged_qty_'.$selected_id);
    
    $sc_item['line_sheet_no'] = $_POST['line_sheet_no_'.$selected_id];
    
    $sc_item['base_unit'] = $_POST['base_unit_'.$selected_id];
    
    return true;
}

function save_stock_count_detail(&$selected_id, $stock_count_id)
{
    
    if(!check_stock_count_detail_data($selected_id, $stock_count_id)){
        return;
    }
    
    $sc_header = get_stock_count_header($stock_count_id);
    if($sc_header['status_id'] != SC_COUNTING){
        display_error("This stock count status does not allow updating details."); 
        return;
    }
    
    $sc_item = array();
    build_stock_count_detail_array($sc_item, $selected_id, $stock_count_id);
    
    $sc_item['header_status_id'] = $sc_header['status_id'];
    $sc_item['loc_code'] = $sc_header['loc_code'];
    $sc_item['tran_date'] = $sc_header['tran_date'];

    $msg = save_stock_count_detail_item($sc_item);    
    if($msg['success'] !== true){        
        display_error($msg['message']);      
    }
    else{
        $selected_id = -1;
        display_notification($msg['message']);  
    }      
        
}

function save_stock_count_detail_item($sc_item)
{

    $selected_id = $sc_item['selected_id'];
    $stock_count_id = $sc_item['stock_count_id'];
    $stock_id = $sc_item['stock_id'];
    $tran_unit = $sc_item['tran_unit'];
    $base_unit = $sc_item['base_unit'];
    $convesion_factor = 1;
    get_convertion_factor2($stock_id, $tran_unit, $convesion_factor);
    
    $tran_unit_good_qty = $sc_item['tran_unit_good_qty'];
    $tran_unit_damaged_qty = $sc_item['tran_unit_damaged_qty'];
    
    $line_sheet_no = $sc_item['line_sheet_no'];
    
    $status_id = $sc_item['header_status_id'];
    $loc_code = $sc_item['loc_code'];
    $tran_date = $sc_item['tran_date'];

    $base_unit_good_qty = $tran_unit_good_qty * $convesion_factor;
    $base_unit_damaged_qty = $tran_unit_damaged_qty * $convesion_factor;

    
    $item = get_item_edit_info($stock_id);
    
    $standard_cost = $item['standard_cost'];
    
    
    $qoh = get_qoh_on_date($stock_id, $loc_code, sql2date($tran_date));
            
    if($selected_id > 0){
        $n = update_stock_count_detail($selected_id, $line_sheet_no, 
                                $base_unit, $base_unit_good_qty, $base_unit_damaged_qty,
                                $tran_unit, $convesion_factor, $tran_unit_good_qty, $tran_unit_damaged_qty,
                                $qoh, $status_id);
        if($n==1){
            return array("success"=>true, "message"=>"Selected item has been updated.");    
        }
        else{ 
            return array("success"=>false, "message"=>"Another user has updated selected item.");    
        }        
    }
    else{
        add_stock_count_detail($stock_count_id, $line_sheet_no, $stock_id, 
                                $base_unit, $base_unit_good_qty, $base_unit_damaged_qty,
                                $tran_unit, $convesion_factor, $tran_unit_good_qty, $tran_unit_damaged_qty,
                                $qoh, $standard_cost, $status_id);

        return array("success"=>true, "message"=>"New counted detail has been added.");    
    }

}


function delete_stock_count_detail_item(&$selected_id, $stock_count_id)
{
    
    if(!can_delete_stock_count_detail($selected_id, $stock_count_id)){
        return;
    }
    
    $n = delete_stock_count_detail($selected_id);
    if($n == 1){
        display_notification("Selected stockcount detail item has been deleted.");    
    }
    else{
        display_error("Could not delete selected stockcount detail item.");    
    }
    

}