<?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>.
***********************************************************************/
$page_security = 'SA_CREATE_QC';
$path_to_root = "../..";
include_once($path_to_root . "/purchasing/includes/po_class.inc");

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


include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
include_once($path_to_root . "/purchasing/includes/ui/po_ui.inc");

$js = '';
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(900, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();
page(_($help_context = "Create QC "), false, false, "", $js);

// page($_SESSION['page_title'], false, false, "", $js);

// simple_page_mode(true);

if (isset($_GET['trans_no']) && $_GET['trans_no'] > 0 && !isset($_POST['Update']))
{
//   display_error($_POST['type']);
        if($_GET['type']!=ST_WORKORDER){

			create_new_po(ST_PURCHORDER, $_GET['trans_no']);
			$_SESSION['PO']->order_no =$_GET['trans_no'];
        }
	// $_SESSION['PO']->trans_type = ST_INWARD;
	// $_SESSION['PO']->reference = $Refs->get_next(ST_SUPPRECEIVE, 
	// 	array('date' => Today(), 'supplier' => $_SESSION['PO']->supplier_id));
	// copy_from_cart();
}

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

function can_process()
{
	global $SysPrefs;
	

          if($_POST['type']==ST_WORKORDER)
        {
        	// $res = get_qc_trans($_POST['order_no'], ST_WORKORDER)
        	    $lock_trans_no = get_next_qc_trans_no($_POST['type']);
                // hidden('lock_trans_no',$lock_trans_no);

        	if($_POST['lock_trans_no']!=$lock_trans_no)
        	{
        	     display_error(_("dubble click process or if stop transaction again process."));
        	     $_POST['lock_trans_no']=$lock_trans_no;
        		return false;
        	}	
        
        return true;
        }
        	
	if (count($_SESSION['PO']->line_items) <= 0)
	{
        display_error(_("There is nothing to process. Please enter valid quantities greater than zero."));
    	return false;
	}
	$something_received = 0;
	foreach ($_SESSION['PO']->line_items as $order_line)
	{
	  	if ($order_line->receive_qty > 0)
	  	{
			$something_received = 1;
			break;
	  	}
	}

    // Check whether trying to deliver more items than are recorded on the actual purchase order (+ overreceive allowance)
    $delivery_qty_too_large = 0;
	foreach ($_SESSION['PO']->line_items as $order_line)
	{
		// display_error($order_line->receive_qty."+".$order_line->qc_qty." ==  (".$order_line->qty_inward."- "s.$order_line->qty_outward." )   --- ". $order_line->id  );
			//   	if ($order_line->receive_qty+$order_line->qc_qty >
	  		// ($order_line->qty_inward-$order_line->qty_outward)  * (1+ ($SysPrefs->over_receive_allowance() / 100)))
	  	if ($order_line->receive_qty+$order_line->qty_received  >
	  		($order_line->quantity)  * (1+ ($SysPrefs->over_receive_allowance() / 100)))
	  	{
			$delivery_qty_too_large = 1;
			break;
	  	}
	}

    if ($something_received == 0)
    { 	/*Then dont bother proceeding cos nothing to do ! */
        display_error(_("There is nothing to process. Please enter valid quantities greater than zero."));
    	return false;
    }
    elseif ($delivery_qty_too_large == 1)
    {
    	display_error(_("Entered quantities cannot be greater than the quantity entered on the purchase order including the allowed over-receive percentage") . " (" . $SysPrefs->over_receive_allowance() ."%)."
    		. "<br>" .
    	 	_("Modify the ordered items on the purchase order if you wish to increase the quantities."));
    	return false;
    }

// exit();
// return false;
	return true;

}

function display_po_receive_items($kv_batch=0, $kv_exp_date=0)
{
	 start_table(TABLESTYLE, "colspan=7 width='90%'");
   // print_r($_SESSION['PO']);
	 start_row();
        $result = get_gl_trans($_GET['type_id'], $_SESSION['PO']->order_no);
        $row=db_fetch($result);

          label_cells(_("Inward Date	"), sql2date($row["doc_date"]), "class='tableheader2'");
        label_cells(_("QC Required Date	"), $_SESSION['PO']->qc_req_date, "class='tableheader2'");

	     end_row();
	     end_table();
	     br();
	div_start('grn_items');
    start_table(TABLESTYLE, "colspan=7 width='90%'");
    $th = array(_("Item Code"), _("Description"), _("Ordered"),_("In ward"),("Out Ward"), _("Units"), _("Received"),	_("Outstanding"), _("This Inward"), _("Price"), _("Total"));
	// if($kv_exp_date){
	// 	array_splice( $th, 7, 0, _("Batch No") );
	// 	array_splice( $th, 8, 0, _("Exp Date") );
	// }elseif($kv_batch)
	// 	array_splice( $th, 7, 0, _("Batch No") );
	
    table_header($th);

    /*show the line items on the order with the quantity being received for modification */

    $total = 0;
    $k = 0; //row colour counter

    if (count($_SESSION['PO']->line_items)> 0 )
    {
       	foreach ($_SESSION['PO']->line_items as $ln_itm)
       	{

			alt_table_row_color($k);

    		$qty_outstanding = $ln_itm->quantity;//($ln_itm->qty_inward-$ln_itm->qty_outward ) - $ln_itm->qc_qty;

 			if (!isset($_POST['Update']) && !isset($_POST['ProcessGoodsReceived']) && $ln_itm->receive_qty == 0)
    	  	{   //If no quantites yet input default the balance to be received
    	    	$ln_itm->receive_qty = $qty_outstanding;
    		}

    		$line_total = ($ln_itm->receive_qty * $ln_itm->price);
    		$total += $line_total;

			label_cell($ln_itm->stock_id);
			if ($qty_outstanding > 0)
				text_cells(null, $ln_itm->stock_id . "Desc", $ln_itm->item_description, 30, 50);
			else
				label_cell($ln_itm->item_description);
			$dec = get_qty_dec($ln_itm->stock_id);
			qty_cell($ln_itm->quantity, false, $dec);
				qty_cell($ln_itm->qty_inward, false, $dec);
					qty_cell($ln_itm->qty_outward, false, $dec);
			label_cell($ln_itm->units);
			qty_cell($ln_itm->qty_received, false, $dec);
			qty_cell($qty_outstanding, false, $dec);

// display_error($ln_itm->qty_inward);
			if ($qty_outstanding > 0)
				qty_cells(null, $ln_itm->line_no, number_format2($ln_itm->receive_qty, $dec), "align=right", null, $dec);
			else
				label_cell(number_format2($ln_itm->receive_qty, $dec), "align=right");
			// if($kv_exp_date){
			// 	text_cells(null,$ln_itm->stock_id .'batch_no', null, 20, 20);
			// 	date_cells(null, $ln_itm->stock_id .'exp_date', '', null, 0, 0, 0);
			// } elseif($kv_batch){
			// 	text_cells(null,$ln_itm->stock_id .'batch_no', null, 20, 20);
			// 	hidden($ln_itm->stock_id .'exp_date', '');
			// } else{
			// 	hidden($ln_itm->stock_id .'batch_no', 0);
			// 	hidden($ln_itm->stock_id .'exp_date', '');
			// }
			//date_cells(null, $ln_itm->stock_id .'exp_date', '', null, 0, 0, 0);
			//month_year_cells(null, 'exp_date', null, null, 0, 0, 0);
			if(!$_SESSION["wa_current_user"]->can_access('SA_WORKORDERCOST'))
			{
			label_cell("-");
			label_cell("-");
			}
			else{

			amount_decimal_cell($ln_itm->price);
			amount_cell($line_total);
			}
			end_row();
       	}
    }

	$colspan = count($th)-1;

	$display_sub_total = price_format($total/* + input_num('freight_cost')*/);

	label_row(_("Sub-total"), $display_sub_total, "colspan=$colspan align=right","align=right");
	$taxes = $_SESSION['PO']->get_taxes(input_num('freight_cost'), true);
	
	$tax_total = display_edit_tax_items($taxes, $colspan, $_SESSION['PO']->tax_included);

	$display_total = price_format(($total + input_num('freight_cost') + $tax_total));

	start_row();
	label_cells(_("Amount Total"), $display_total, "colspan=$colspan align='right'","align='right'");
	end_row();
    end_table();
	div_end();
}
//----------------------------------------------------------------------------------------------------





if (isset($_POST['addupdate']) && $_POST['type']!=ST_WORKORDER)
{

	/* if update quantities button is hit page has been called and ${$line->line_no} would have be
 	set from the post to the quantity to be received in this receival*/
	foreach ($_SESSION['PO']->line_items as $line)
	{
	 if( ($line->quantity - $line->qty_received)>0) {
		$_POST[$line->line_no] = max($_POST[$line->line_no], 0);
		if (!check_num($line->line_no))
			$_POST[$line->line_no] = number_format2(0, get_qty_dec($line->stock_id));

		if (!isset($_POST['DefaultReceivedDate']) || $_POST['DefaultReceivedDate'] == "")
			$_POST['DefaultReceivedDate'] = new_doc_date();

		$_SESSION['PO']->line_items[$line->line_no]->receive_qty = input_num($line->line_no);

		if (isset($_POST[$line->stock_id . "Desc"]) && strlen($_POST[$line->stock_id . "Desc"]) > 0)
		{
			$_SESSION['PO']->line_items[$line->line_no]->item_description = $_POST[$line->stock_id . "Desc"];		

			$_SESSION['PO']->line_items[$line->line_no]->batch_no = $_POST[$line->stock_id . "batch_no"];
			$_SESSION['PO']->line_items[$line->line_no]->exp_date = $_POST[$line->stock_id . "exp_date"];
		}
	 }
	}

	$Ajax->activate('grn_items');
}




if (isset($_POST['addupdate']) && can_process())
{




	 global $path_to_root;
	// add_sales_type($_POST['sales_type'], check_value('tax_included'),
	//     input_num('factor'));
	 	begin_transaction();
     $order_no =$_POST['order_no'];
          $type =$_POST['type'];
      $qc_trans_no = get_next_qc_trans_no(   $type)    ;
    $sql=get_po_qc_category_detalis($order_no,$type);
	$i=1;
	$qc_status = ($_POST['is_qc_pass']) ? $_POST['is_qc_pass'] :0;
	$res=db_query($sql);
	while ($myrow = db_fetch($res))
    {
	     $result = get_qc_details($myrow['category_id']);
		 while ($row = db_fetch($result))
	     {
             
             $sql = "INSERT INTO ".TB_PREF."qc_trans (trans_no,po_order_no, type , field_id	, label_name, 
    		 value,qc_status) VALUES ("
			.db_escape($qc_trans_no). ","
			.db_escape($order_no). ","
			.db_escape($type). ","
			.db_escape($row['id']). ","
			.db_escape($row['name']). ","
			.db_escape($_POST["qc".$row['id']]) . ","
			.db_escape($qc_status). ")";
			// display_error($sql);
		  db_query($sql, "QC trans could not be added");
   

	     }
     
     }	




     if($type==ST_WORKORDER)
     {
     	$sql = "UPDATE ".TB_PREF."workorders SET 
		is_qc=1";
		$sql .= " WHERE id = ".db_escape($order_no);
		// display_error($sql);
		if($qc_status)
		db_query($sql, "could not update compete req against purchase order");
		 add_audit_trail(ST_QC_TRANS, $qc_trans_no ,  Today() ,_(" Add QC against WorkOrder # ".$order_no) );
             commit_transaction();
				meta_forward($path_to_root . "/manufacturing/search_work_orders.php?outstanding_only=1");
	display_notification(_('QC has been added order # '.$order_no));
	// unset($_POST);


     }
     else{

		$sql = "UPDATE ".TB_PREF."purch_orders SET 
		is_qc_complete=1";
		$sql .= " WHERE order_no = ".db_escape($order_no);
		// display_error($sql);
		db_query($sql, "could not update complte req against purchase order");

		 add_audit_trail(ST_QC_TRANS, $qc_trans_no ,  Today() ,_(" Add QC against order  # ".$order_no) );
	display_notification(_('QC has been added order # '.$order_no));


	$grn = &$_SESSION['PO'];
	$grn->orig_order_date = $_POST['DefaultReceivedDate'];

	foreach ($grn->line_items as $line){


		 $sql = "INSERT INTO ".TB_PREF."inward_grn (type, order_no, po_line_id, ord_date, 
     	qty) VALUES(";
     $sql .= db_escape(ST_QC_TRANS) . "," .
         db_escape($grn->order_no) . "," .
         db_escape($line->po_detail_rec) . ", " .
		 db_escape(date2sql($grn->orig_order_date)) . ", " .
         db_escape($line->receive_qty) . ")";

// display_error($sql);
   	db_query($sql, "The purchase order header record could not be inserted");

   		$sql = "UPDATE ".TB_PREF."purch_order_details SET qc_qty = qc_qty+".$line->receive_qty." WHERE po_detail_item=".db_escape($line->po_detail_rec);
  	db_query($sql, "Can't change PO update for again Inward ");


	}






       commit_transaction();

		unset($_SESSION['PO']->line_items);
		unset($_SESSION['PO']);
				meta_forward($path_to_root . "/purchasing/inquiry/po_search.php");
     }	




	// $Mode = 'RESET';
}

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

// if ($Mode=='UPDATE_ITEM' && can_process())
// {

// 	update_sales_type($selected_id, $_POST['sales_type'], check_value('tax_included'),
// 	     input_num('factor'));
// 	display_notification(_('Selected sales type has been updated'));
// 	$Mode = 'RESET';
// }

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

// if ($Mode == 'Delete')
// {
// 	// PREVENT DELETES IF DEPENDENT RECORDS IN 'debtor_trans'
	
// 	if (key_in_foreign_table($selected_id, 'debtor_trans', 'tpe'))
// 	{
// 		display_error(_("Cannot delete this sale type because customer transactions have been created using this sales type."));

// 	}
// 	else
// 	{
// 		if (key_in_foreign_table($selected_id, 'debtors_master', 'sales_type'))
// 		{
// 			display_error(_("Cannot delete this sale type because customers are currently set up to use this sales type."));
// 		}
// 		else
// 		{
// 			delete_sales_type($selected_id);
// 			display_notification(_('Selected sales type has been deleted'));
// 		}
// 	} //end if sales type used in debtor transactions or in customers set up
// 	$Mode = 'RESET';
// }

if ($Mode == 'RESET')
{
	$selected_id = -1;
	$sav = get_post('show_inactive');
	unset($_POST);
	$_POST['show_inactive'] = $sav;
}
//----------------------------------------------------------------------------------------------------

// $result = get_all_sales_types(check_value('show_inactive'));

// start_form();
// start_table(TABLESTYLE, "width='30%'");

// $th = array (_('Type Name'), _('Factor'), _('Tax Incl'), '','');
// inactive_control_column($th);
// table_header($th);
// $k = 0;
// $base_sales = get_base_sales_type();

// while ($myrow = db_fetch($result))
// {
// 	if ($myrow["id"] == $base_sales)
// 	    start_row("class='overduebg'");
// 	else
// 	    alt_table_row_color($k);
// 	label_cell($myrow["sales_type"]);
// 	$f = number_format2($myrow["factor"],4);
// 	if($myrow["id"] == $base_sales) $f = "<I>"._('Base')."</I>";
// 	label_cell($f);
// 	label_cell($myrow["tax_included"] ? _('Yes'):_('No'), 'align=center');
// 	inactive_control_cell($myrow["id"], $myrow["inactive"], 'sales_types', 'id');
//  	edit_button_cell("Edit".$myrow['id'], _("Edit"));
//  	delete_button_cell("Delete".$myrow['id'], _("Delete"));
// 	end_row();
// }
// inactive_control_row($th);
// end_table();

// display_note(_("Marked sales type is the company base pricelist for prices calculations."), 0, 0, "class='overduefg'");

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

start_form();

    $order_no=$_GET['trans_no'];
        $type=$_GET['type'];
	// $sql="SELECT sc.* FROM 0_purch_order_details pod , 0_stock_master sm , 0_stock_category sc WHERE pod.order_no=".db_escape($order_no)." AND pod.item_code=sm.stock_id AND sm.category_id=sc.category_id";
  // $k
   // for ($j=0; $j < 2 ; $j++) { 
   	# code...

		$sql=get_po_qc_category_detalis($order_no,$type);
		$i=1;
		$res=db_query($sql);
		while ($myrow = db_fetch($res))
	    {
	       start_outer_table(TABLESTYLE);
	         if(($i++%2)==0){
	  //     if()	 
	       $i=1;
			table_section($i);
		}
			table_section_title(_("<strong style='font-size: 20px;''>".$myrow['item_description']." ( ".$myrow['description']." ) "."</strong >"));
			$result = get_qc_details($myrow['category_id']);
			while ($row = db_fetch($result))
			{
			 display_qc_fields("qc".$row['id'],$row['name'],$row['qc_type'],$row['min'],$row['max'],$row['options']);
			}     
           	 if(($i++%2)==0)
	       end_outer_table($i);


	    }
    
   // }
    hidden('order_no',$order_no);
        hidden('type',$type);

        if($type!=ST_WORKORDER)
    {
        display_heading(_("Items to QC"));
             
 hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=".ST_QC_TRANS."&trans_no=$order_no");  
display_po_receive_items($kv_batch, $kv_exp_date);
        }
   elseif($type==ST_WORKORDER){

   	    start_table(TABLESTYLE, " width='50%'");
   	    start_row();
   	    	yesno_list_row(_("QC PASS / FAILED:"), 'is_qc_pass', null, "", "", false);
   	    end_row();

   	    end_table();


   }
   br(2);
        if($_GET['trans_no'])
    $lock_trans_no = get_next_qc_trans_no($type);
    hidden('lock_trans_no',$lock_trans_no);
// text_row_ex(_("Sales Type Name").':', 'sales_type', 20);
// amount_row(_("Calculation factor").':', 'factor', null, null, null, 4);
// check_row(_("Tax included").':', 'tax_included', $_POST['tax_included']);

// display_error($_POST['addupdate']);

// submit_add_or_update_center($selected_id == -1, 'create QC');


		submit_center_first('addupdate', _("Create QC"), '', 
			$page_nested ? true : 'default');
end_form();

end_page();

