<?php
/**********************************************************************
    Copyright (C) FrontAccounting, LLC.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************/
include_once($path_to_root . "/includes/ui.inc");

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

function display_bom($item_check,$myrow2=null)
{
	global $SysPrefs;
    $result = get_bom($item_check);

    if (db_num_rows($result) == 0)
    {
    	display_note(_("The bill of material for this item is empty."), 0, 1);
    }
    else
    {

        start_table(TABLESTYLE);
        $th = array(_("Component"), _("Description"), _("Work Centre"),
        	_("From Location"), _("Quantity"),_("Unit"), _("Total Quantity"), _("On Hand"), _("Required Qty"), _("Unit Cost"), _("Cost"));

          if(!$_SESSION["wa_current_user"]->can_access('SA_WORKORDERCOST'))
           unset($th[8],$th[9]);
        table_header($th);

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

        $total_cost = 0;

        while ($myrow = db_fetch($result))
        {


        	$qoh = 0;
			$show_qoh = true;
			if($myrow2["loc_code"])
			{	
			// if it's a non-stock item (eg. service) don't show qoh
			if (!has_stock_holding($myrow["ResourceType"]))
				$show_qoh = false;

               // display_error($myrow["ResourceType"]);
			if ($show_qoh)
				$qoh = get_qoh_on_date($myrow["component"], $myrow2["loc_code"]);
			// display_error(number_format($myrow2["units_reqd"] * $myrow["quantity"],3)." == ". number_format($qoh,3)." > ".$qoh);
			if ($show_qoh && (number_format3($myrow2["units_reqd"] * $myrow["quantity"],5) > number_format3($qoh,5) ) &&
				!$SysPrefs->allow_negative_stock())
			{
               // display_error($qoh." ==  ".$myrow["component"]." = ".$myrow2["loc_code"]);
               // display_error($myrow2["units_reqd"] ." * ". $myrow["quantity"]);
				// oops, we don't have enough of one of the component items
				start_row("class='stockmankobg'");
				$has_marked = true;
			}
			else
				alt_table_row_color($k);
             }
             else
			alt_table_row_color($k);

			label_cell($myrow["component"]);
			label_cell($myrow["description"]);
			label_cell($myrow["WorkCentreDescription"]);
			label_cell($myrow["location_name"]);
			qty_cell($myrow["quantity"], false, get_qty_dec($myrow["component"]));
			label_cell($myrow["units"]);
			$total_qty=$myrow["quantity"] *$myrow2["units_reqd"];
			qty_cell($total_qty, false, get_qty_dec($myrow["component"]));
			qty_cell($qoh , false, get_qty_dec($myrow["component"]));
			if($total_qty>$qoh)
			qty_cell($total_qty-$qoh , false, get_qty_dec($myrow["component"]));	
		    else
		    qty_cell(0);
		    	
			if($_SESSION["wa_current_user"]->can_access('SA_WORKORDERCOST'))
			{
				amount_cell($myrow["ProductCost"]);
		     	amount_cell($myrow["ComponentCost"]);
			 }
			end_row();
        	$total_cost += $myrow["ComponentCost"];

        	$j++;
        	if ($j == 12)
        	{
        		$j = 1;
        		table_header($th);
        	}
		}

  if($_SESSION["wa_current_user"]->can_access('SA_WORKORDERCOST'))
  { 	
		$item = get_item($item_check);
		if ($item['labour_cost'] != 0)
		{
			$total_cost += $item['labour_cost'];
			alt_table_row_color($k);
	        label_cells(_("Standard Labour Cost"), number_format2($item['labour_cost'],user_price_dec()),
    	    	"colspan=6 align=left", "class=odd_row nowrap align=right");
    	    end_row();
		}
		if ($item['overhead_cost'] != 0)
		{
			$total_cost += $item['overhead_cost'];
			alt_table_row_color($k);
	        label_cells(_("Standard Overhead Cost"), number_format2($item['overhead_cost'],user_price_dec()),
    	    	"colspan=6 align=left", "nowrap align=right");
    	    end_row();
		}
        label_row("<b>" . _("Total Cost") . "</b>", "<b>" . number_format2($total_cost,user_price_dec()) ."</b>",
        	"colspan=6 align=right", "nowrap align=right");

      }   
		end_table();
    }
}

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

function display_wo_requirements($woid, $quantity, $show_qoh=false, $date=null)
{
	global $SysPrefs;

    $result = get_wo_requirements($woid);

    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no Requirements for this Order."), 1, 0);
    }
    else
    {

        start_table(TABLESTYLE, "width='80%'");
        $th = array(_("Component"), _("From Location"), _("Work Centre"),
        	_("Unit Quantity"),_("Unit"), _("Total Quantity"), _("Units Issued"), _("On Hand"), _("On Required"), _("Unit Cost"), _("Total Cost"));

        table_header($th);

        $total_cost=$k = 0; //row colour counter
		$has_marked = false;

		if ($date == null)
			$date = Today();
       	$workorder = get_work_order($woid);
        while ($myrow = db_fetch($result))
        {

			$qoh = 0;
			$show_qoh = true;
			// if it's a non-stock item (eg. service) don't show qoh
			if (!has_stock_holding($myrow["mb_flag"]))
				$show_qoh = false;

			if ($show_qoh)
				$qoh = get_qoh_on_date($myrow["stock_id"], $myrow["loc_code"], $date);
	       // display_error(number_format3($myrow["units_reqd"] * $quantity,5)." == ". number_format3($qoh,5)." > ".$qoh);
			if ($show_qoh && (number_format3($myrow["units_req"] * $quantity,5) > number_format3($qoh,5) ) &&
				!$SysPrefs->allow_negative_stock())
			{
				// oops, we don't have enough of one of the component items
					if(!$workorder['closed'])
				start_row("class='stockmankobg'");
				$has_marked = true;
			}
			else
				alt_table_row_color($k);

            if(is_manufactured($myrow["mb_flag"])){
            	if (user_show_codes())
	        		label_cell( viewer_link( $myrow["stock_id"]. " - " . $myrow["description"],
    		"/manufacturing/manage/bom_edit.php?stock_id=" . $myrow["stock_id"]));
	        	else
	        		label_cell( viewer_link( $myrow["description"],
    		"/manufacturing/manage/bom_edit.php?stock_id=" . $myrow["stock_id"]));

            }
            else{

	        	if (user_show_codes())
	        		label_cell($myrow["stock_id"]. " - " . $myrow["description"]);
	        	else
	        		label_cell($myrow["description"]);
            }
                    Get_Stock_balance_with_batch($myrow["stock_id"], $myrow['loc_code']);
			label_cell($myrow["location_name"]);
			label_cell($myrow["WorkCentreDescription"]);
			label_cell($myrow["units"]);
			$dec = get_qty_dec($myrow["stock_id"]);
            qty_cell($myrow["units_req"], false, $dec);
			qty_cell($myrow["units_req"] * $quantity, false, $dec);
            qty_cell($myrow["units_issued"], false, $dec);
			if ($show_qoh)
				qty_cell($qoh, false, $dec);
			else
				label_cell("");

         $req = ($myrow["units_req"] * $quantity)-$myrow["units_issued"];
		qty_cell(( ($req )>$qoh) ? $req-$qoh : 0 , false, $dec);
             	amount_cell($myrow["ComponentCost"]);
             $total_cost+=$myrow["ComponentCost"] * $myrow["units_req"] * $quantity ;
           // display_error($myrow["ComponentCost"] ."*". $quantity);
			amount_cell($myrow["ComponentCost"] * $myrow["units_req"] * $quantity);
   //         echo "<pre>"; ComponentCost
			// print_r($myrow);
			end_row();

		}


// display_error( number_format2($total_cost,2));
		// label_row(_("Total"), number_format2($total_cost,2),
		// 	"colspan=9", "nowrap align=right");
		end_table();

		if ($has_marked)
			display_note(_("Marked items have insufficient quantities in stock."), 0, 0, "class='red'");
    }

    return $total_cost;
}


function display_bom_requirements($bom_id, $quantity, $show_qoh=false, $date=null)
{
	global $SysPrefs,$Ajax;

    $result = get_bom($bom_id);

    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no define bom for this item ".$bom_id), 1, 0);
    }
    else
    {
    	if(!$_POST['store_loc'])
    		$_POST['store_loc']='CHMST';

        start_table(TABLESTYLE, "width='80%'");
        $th = array(_("Component"), _("From Location"), _("Work Centre"),
        	_("Unit Quantity"), _("Total Quantity"), _("On Hand"),_("Price"),_(all_locations_list('store_loc', $_POST['store_loc'],false,true).'<br> Store Qty'), _("Required Qty"));  //, _("Units Issued")

        table_header($th);

        $k = 0; //row colour counter
		$has_marked = false;

		if ($date == null)
			$date = Today();

       $max_array_qty=array();
        while ($myrow = db_fetch($result))
        {

			$qoh = 0;
			$show_qoh = true;
			// if it's a non-stock item (eg. service) don't show qoh
			if (!has_stock_holding($myrow["ResourceType"]))
				$show_qoh = false;

         // display_error(	$show_qoh ." == ".$myrow["component"]);
			if ($show_qoh)
				$qoh = get_qoh_on_date($_POST['component'.$myrow["component"]], $myrow["loc_code"], $date);



			if ($show_qoh && ($myrow["quantity"] * $quantity > $qoh) &&
				!$SysPrefs->allow_negative_stock())
			{
				// oops, we don't have enough of one of the component items
				start_row("class='stockmankobg'");
				$has_marked = true;
			}
			else
				alt_table_row_color($k);
			echo "<td>";
			echo stock_component_items_list('component'.$myrow["component"],$myrow["stock_id"] , $_POST['component'.$myrow["component"]], null, false, true);
			if (get_post('component'.$myrow["component"])) 
			{
			 $Ajax->activate('component'.$myrow["component"]);
			}
			echo "</td>";

            // if(is_manufactured($myrow["ResourceType"])){
            // 	if (user_show_codes())
	        // 		label_cell( viewer_link( $myrow["component"]. " - " . $myrow["description"],
    		// "/manufacturing/manage/bom_edit.php?stock_id=" . $myrow["component"]));
	        // 	else
	        // 		label_cell( viewer_link( $myrow["description"],
    		// "/manufacturing/manage/bom_edit.php?stock_id=" . $myrow["component"]));

            // }
            // else{

	        // 	if (user_show_codes())
	        // 		label_cell($myrow["component"]. " - " . $myrow["description"]);
	        // 	else
	        // 		label_cell($myrow["description"]);
            // }

    // label_row(display_bom_requirements($_POST['stock_id'], $myrow["component"], true, $_POST['date_']));
					// echo stock_component_items_list('component', $selected_parent, null, false, true);


			label_cell($myrow["location_name"]);
			label_cell($myrow["WorkCentreDescription"]);
			$dec = get_qty_dec($myrow["component"]);
            qty_cell($myrow["quantity"], false, $dec);
            $total_qty=$myrow["quantity"] * $quantity;
			// qty_cell($total_qty, false, $dec);

				qty_cells(null, 'quantity'.$myrow["component"], $tal_qty, null, null, $dec);

            // qty_cell($myrow["units_issued"], false, $dec);
			if ($show_qoh)
				qty_cell($qoh, false, $dec);
			else
				label_cell("");
             
             	$item_info = get_item_edit_info($_POST['component'.$myrow["component"]]);
					        	// $batch_price=;
             	label_cell($item_info['material_cost']);
             	$store_qty = get_qoh_on_date($myrow["component"], $_POST['store_loc'], $date);

             		qty_cell($store_qty, false, $dec);
             		$max_array_qty[$myrow["quantity"]]=$store_qty;

			if($total_qty>$qoh)
				qty_cell($total_qty-$qoh, false, $dec);
			else
				label_cell("");

			end_row();

		}

        label_cell('Max qty produce finish good asseumption','colspan=6');
        $unit_qty=array_keys($max_array_qty, min($max_array_qty))[0];
        $min_qty=min($max_array_qty);
        $rim_val=$min_qty/$unit_qty;
        qty_cell( $rim_val);
        label_cell('');
		end_table(1);

		if ($has_marked)
			display_note(_("Marked items have insufficient quantities in stock."), 0, 0, "class='red'");
    }
}

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

function display_wo_productions($woid)
{
	global $path_to_root;

    $result = get_work_order_productions($woid);
     $total_qty = 0;
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no Productions for this Order."), 1, 1);
    }
    else
    {
        start_table(TABLESTYLE);
        $th = array(_("#"), _("Reference"), _("Date"), _("Quantity"),_("Amount"));

        table_header($th);

        $k = 0; //row colour counter
		$sum = $total = $total_qty = 0;
    
        while ($myrow = db_fetch($result))
        {

			alt_table_row_color($k);

			$total_qty += $myrow['quantity'];

        	label_cell(get_trans_view_str(ST_MANURECEIVE, $myrow["id"]));
			label_cell($myrow['reference']);
			label_cell(sql2date($myrow["date_"]));
			qty_cell($myrow['quantity'], false, get_qty_dec($myrow['reference']));
              $res = get_stock_moves(ST_MANURECEIVE, $myrow["id"]);
			    while ($row = db_fetch($res)) {
                     	$total = abs($row["qty"])*$row["price"];
			    		$sum += $total;
			    }
			end_row();
		}//end of while

		label_row(_("Total"), number_format2($total_qty,user_qty_dec()),
			"colspan=3", "nowrap align=right");

		end_table();
    }

// display_error($total_qty." === ".$sum);
    return array( 'total_qty' => $total_qty , 'amount' => $sum ) ;
}

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

function display_wo_issues($woid)
{
	global $path_to_root;

         $total=0;
    $result = get_work_order_issues($woid,$type);

    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no Issues for this Order."), 0, 1);
    }
    else
    {
        start_table(TABLESTYLE);
        // $th = array(_("#"), _("Reference"), _("Date"), _("Amount"));
         $th = array(_("#"),_("Component"),_("Category"), _("Quantity"), _("Units"), _("Unit Cost"), _("Total"));

        table_header($th);

        $k = 0; //row colour counter

        while ($myrow = db_fetch($result))
        {
                 // print_r($myrow);
			alt_table_row_color($k);

             $res = get_work_order_issue_details($myrow["issue_no"]);

				while ($row = db_fetch($res))
				{

					alt_table_row_color($k);
                    label_cell(get_trans_view_str(ST_MANUISSUE, $myrow["issue_no"]), " align='center' ");
					label_cell($row["stock_id"]  . " - " . $row["description"]);
                     // label_cell( ($myrow['issue_type']) ?   '<span class="label label-info"> OUTPUT <span>' :  '<span class="label label-success"> INPUT <span>'  );
                    label_cell('<span class="label label-info"> '.get_category_name($row['category_id']).' <span>' );
					qty_cell($row["qty_issued"] , false, get_qty_dec($row["stock_id"]));
					label_cell($row["units"]);
					amount_cell($row["unit_cost"] );
					amount_cell($row["unit_cost"]*$row["qty_issued"]);
                    
					end_row();
                    $total+=$row["unit_cost"]*$row["qty_issued"];
					$j++;
					If ($j == 12)
					{
					$j = 1;
					table_header($th);
					}//end of page full new headings if
				}//end of while

    
   //      	label_cell(get_trans_view_str(ST_MANUISSUE, $myrow["issue_no"]), " align='center' ");
			// label_cell($myrow['reference'], " align='center' ");
			// label_cell(sql2date($myrow["issue_date"]), " align='center' ");
			// $row = get_issue_qty_amount($myrow["issue_no"]);
			// label_cell(price_format(abs($row['amount']) ), " align='center' ");
			end_row();
		}

		 label_cells(_("Total"), price_format($total ), " class='tableheader2' align='left' colspan='5' ");

		end_table();
    }

    return $total;
}

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

function display_wo_payments($woid)
{
	global $path_to_root, $wo_cost_types;

    $result = get_wo_costing($woid);
     $tot_cost=0;
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no additional costs for this Order."), 0, 1);
    }
    else
    {
        start_table(TABLESTYLE);
        $th = array(_("#"), _("Type"), _("Date"), _("Amount"));

        table_header($th);

        $k = 0;
        while ($myrow = db_fetch($result))
        {
			alt_table_row_color($k);

        	label_cell(get_gl_view_str( $myrow["trans_type"], $myrow["trans_no"], $myrow["trans_no"]));
        	label_cell($wo_cost_types[$myrow['cost_type']]);
        	$date = sql2date($myrow["tran_date"]);
        	label_cell($date);
			amount_cell($myrow['amount']);
			$tot_cost+=$myrow['amount'];
			end_row();
		}

		end_table();
    }
    return $tot_cost;
}

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

function display_wo_details($woid, $suppress_view_link=false, $kv_batch= 0, $kv_exp_date=null){
	global $wo_types_array;

	$myrow = get_work_order($woid, true);

    if ($myrow == false)
    {
    	display_note(_("The work order number sent is not valid."));
    	exit;
    }

   	start_table(TABLESTYLE, "width='80%'");

	if ($myrow["released"] == true)
		$th = array(_("#"), _("Reference"), _("Type"), _("Manufactured Item"),
			_("Into Location"), _("Date"), _("Required By"), _(" Batch No. "), _(" Batch Size "),
			_("Released Date"), _("Manufactured"), _("File System")); //, _("Manufactured")
	else
		$th = array(_("#"), _("Reference"), _("Type"), _("Manufactured Item"),_("Into Location"), _("Date"), _("Required By"), _("Batch Size"), _("Quantity"), _("File System"));
		
	if($kv_batch || $kv_exp_date){
		array_push($th, _("Batch No"));
		if($kv_exp_date)
			array_push($th, _("Exp Date"));
		$sql_wo = "SELECT batch_no ";
		if($kv_exp_date)
			$sql_wo .= ", exp_date ";
		$sql_wo .= "FROM ".TB_PREF."stock_moves WHERE trans_no = ".db_escape($woid)." AND type=".ST_WORKORDER;
		$resul_wo = db_query($sql_wo, "can't get move data");
		if(db_num_rows($resul_wo) > 0 ) {			
			$exp_batch=true;
		} else {
			if ($myrow["released"] == true){
				unset($th[11]);
				unset($th[10]);
				array_splice( $th, 10, 0, _("File System") );


			}else{
				unset($th[9]);
				unset($th[8]);
			}
			$exp_batch=false;
		}
	} else
		$exp_batch=false;
	table_header($th);
	start_row();
	if ($suppress_view_link)
		label_cell($myrow["id"]);
	else
		label_cell(get_trans_view_str(ST_WORKORDER, $myrow["id"]));
	label_cell($myrow["wo_ref"]);
	label_cell($wo_types_array[$myrow["type"]]);
	view_stock_status_cell($myrow["stock_id"], $myrow["StockItemName"]);
	label_cell($myrow["location_name"]);
	label_cell(sql2date($myrow["date_"]));
	label_cell(sql2date($myrow["required_by"]));
	label_cell( ($myrow["released"] == true) ? $myrow["batch_no"] : 'Not Release' ,'style="color:blue; font-weight:500px;"');
	$dec = get_qty_dec($myrow["stock_id"]);
	qty_cell($myrow["units_reqd"], false, $dec);

	if ($myrow["released"] == true)	{		
		if($exp_batch && $row= db_fetch($resul_wo)){
			label_cell($row["batch_no"]);
			
		}
		label_cell(sql2date($myrow["released_date"]));
		if($myrow["units_issued"])
		qty_cell($myrow["units_issued"], false, $dec);
		
	} else {
		if($exp_batch && $row=db_fetch($resul_wo)){
			label_cell($row['batch_no']);
			label_cell(sql2date($row['exp_date']));
		}
	}
	label_cell(get_file_system_name($myrow["file_system"]), "align='center'");

	end_row();

	comments_display_row(ST_WORKORDER, $woid);

	end_table();

    if ($myrow["closed"] == true)
    {
    	display_note(_("This work order is closed."));
    }
}

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

function display_wo_details_quick($woid, $suppress_view_link=false)
{
	global $wo_types_array;

	$myrow = get_work_order($woid, true);

    if ($myrow === false)
    {
    	display_note(_("The work order number sent is not valid."));
    	exit;
    }

   	start_table(TABLESTYLE, "width='80%'");
	$kv_batch = get_company_pref('kv_batch');
	$kv_exp_date = get_company_pref('kv_exp_date');
	$th = array(_("#"), _("Reference"), _("Type"), _("Manufactured Item"), _("Into Location"), _("Date"), _("Quantity"));
	if($kv_batch || $kv_exp_date){
		array_push($th, _("Batch No"));
		if($kv_exp_date)
			array_push($th, _("Exp Date"));
		$sql_wo = "SELECT batch_no " ;
		if($kv_exp_date)
			$sql_wo .=", exp_date ";
		$sql_wo .= "FROM ".TB_PREF."stock_moves WHERE trans_no = ".db_escape($woid)." AND type=".ST_WORKORDER;
		$resul_wo = db_query($sql_wo, "can't get move data");
		if(db_num_rows($resul_wo) > 0 ) {			
				$exp_batch=true;
		} else {
			if ($myrow["released"] == true){
				if(isset($th[8]))
					unset($th[8]);
				unset($th[7]);
			}
			$exp_batch=false;
		}
	} else
		$exp_batch=false;
	table_header($th);

	start_row();
	if ($suppress_view_link)
		label_cell($myrow["id"]);
	else
		label_cell(get_trans_view_str(ST_WORKORDER, $myrow["id"]));
	label_cell($myrow["wo_ref"]);
	label_cell($wo_types_array[$myrow["type"]]);
	view_stock_status_cell($myrow["stock_id"], $myrow["StockItemName"]);
	label_cell($myrow["location_name"]);
	label_cell(sql2date($myrow["date_"]));

	qty_cell($myrow["units_issued"], false, get_qty_dec($myrow["stock_id"]));
	if ($myrow["closed"] == 1) {		
		if($exp_batch && $row= db_fetch($resul_wo)){
			label_cell($row["batch_no"]);
			label_cell(sql2date($row['exp_date']));
		}
	}
	end_row();

	comments_display_row(ST_WORKORDER, $woid);

	end_table();

    if ($myrow["closed"] == true)
    {
    	display_note(_("This work order is closed."));
    }
}

