<?php
/**********************************************************************
	Copyright (C) Evolve Techniologies
	Author : Chathuri Gunawardana
	Email : chathuri@evolve-sl.com
	Company : Evolve Technologies(pvt)Ltd
***********************************************************************/
$page_security = 'SA_SALESGROUP';
$path_to_root = "../..";
include($path_to_root . "/includes/session.inc");

page(_($help_context = "Batch Registration"));

include($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/sales/includes/db/batch_db.inc");
include_once($path_to_root . "/sales/includes/db/course_registration_db.inc");

include_once($path_to_root . "/inventory/includes/db/items_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_codes_db.inc");

include_once($path_to_root . "/inventory/includes/db/items_prices_db.inc");

simple_page_mode(true);

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

if ($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') 
{
	//initialise no input errors assumed initially before we test
	$input_error = 0;

	/*if (strlen($_POST['courseName']) == 0)
	{
		$input_error = 1;
		display_error(_("The course name cannot be empty."));
		set_focus('courseName');
	}*/
	/*if (!check_num('courseRegFee', 0)) {
		$input_error = 1;
		display_error( _("Course reg. Fee must be numeric and not less than 0."));
		set_focus('courseRegFee');
	}*/

	if ($input_error != 1)
	{
                if ($selected_id != -1) 
                {
				   //$batchName = $_POST['batchYear']." ".$_POST['batchMonth']." ".$_POST['courseShortNameB']." ".$_POST['courseEntrMeth'];
				   $batchName = $_POST['batchYear']." ".$_POST['batchMonth']." ".preg_replace('/[^A-Za-z0-9\-]/', '_', $_POST['courseShortNameB'])." ".$_POST['courseEntrMeth'];
				   
				   $_POST['totPrice'] = number_format((input_num('tuitionFee') +  input_num('uweFee')),2);
				   
                   //update_batches($selected_id, $batchName, $_POST['courseNameB'], $_POST['courseShortNameB'],$_POST['batchYear'], $_POST['batchMonth'], $_POST['courseEntrMeth'], input_num('tuitionFee'), input_num('uweFee'), input_num('totPrice')); 
				   update_batches($selected_id, $batchName, $_POST['courseNameB'], preg_replace('/[^A-Za-z0-9\-]/', '_', $_POST['courseShortNameB']) ,$_POST['batchYear'], $_POST['batchMonth'], $_POST['courseEntrMeth'], input_num('tuitionFee'), input_num('uweFee'), input_num('totPrice'));
				           
				   
				    $myrow2 = get_batches3($batchName);
					//print_r($myrow2);
					
					$amount = $myrow2['totalFee'];
					$duration = $myrow2['total_duration'];
					$perYear = $amount/$duration;
					//echo "perYear= ".$perYear;
					
					$arr = array('Annualy', 'Monthly', 'Semesterly', 'Total');
					
					foreach ($arr as &$value) 
					{
						$batchNameStkId = $myrow2['batch_year']."_".$myrow2['batch_month']."_".$myrow2['course_short_name']."_".$myrow2['batch_entrM']."_".$value;
						
						$descriptionStk = $batchName."_".$value;
						
						$details = array();
						$details = get_itemCat_details($batchName);
						//print_r($details);
						
						//update_item_isAdminCat($batchNameStkId, $descriptionStk, $value, $details[0], $details[1], $details[2], $details[3],$details[4], $details[5], $details[7], $details[6], $details[8], $details[9], $details[10], 0, 0, 0, 1);
						
						if($value == "Annualy")
						{
							$fee = $perYear;
							$calcPrice = number_format2($perYear,2);
							//echo "calcPrice A = ".$calcPrice;
							update_item_price_isAdminCat2($batchNameStkId, $fee, $details[0]);
						}
						if($value == "Monthly")
						{
							$fee = $perYear/12;
							$calcPrice = number_format2($perYear/12,2);
							//echo "calcPrice M = ".$calcPrice;
							update_item_price_isAdminCat2($batchNameStkId,  $fee, $details[0]);
						}
						if($value == "Semesterly")
						{
							$fee = $perYear/2;
							$calcPrice = number_format2($perYear/2,2);
							//echo "calcPrice S = ".$calcPrice;
							update_item_price_isAdminCat2($batchNameStkId,  $fee, $details[0]);
						}
						if($value == "Total")
						{
						    $fee = $amount;
							$calcPrice = number_format2($amount,2);
							//echo "calcPrice T = ".$calcPrice;
							update_item_price_isAdminCat2($batchNameStkId,  $amount, $details[0]);
						}
				
					}         
                }
                else
                {	
					//$batchName = $_POST['batchYear']." ".$_POST['batchMonth']." ".$_POST['courseShortNameB']." ".$_POST['courseEntrMeth'];
					$batchName = $_POST['batchYear']." ".$_POST['batchMonth']." ".preg_replace('/[^A-Za-z0-9\-]/', '_', $_POST['courseShortNameB'])." ".$_POST['courseEntrMeth'];
					
					$_POST['totPrice'] = number_format((input_num('tuitionFee') +  input_num('uweFee')),2);
					
					//add_batches($batchName, $_POST['courseNameB'], $_POST['courseShortNameB'],$_POST['batchYear'], $_POST['batchMonth'], $_POST['courseEntrMeth'], input_num('tuitionFee'), input_num('uweFee'), input_num('totPrice'));
					add_batches($batchName, $_POST['courseNameB'], preg_replace('/[^A-Za-z0-9\-]/', '_', $_POST['courseShortNameB']) ,$_POST['batchYear'], $_POST['batchMonth'], $_POST['courseEntrMeth'], input_num('tuitionFee'), input_num('uweFee'), input_num('totPrice'));
					
					
					
					$myrow2 = get_batches2($batchName);
					//print_r($myrow2);
					
					$amount = $myrow2['totalFee'];
					$duration = $myrow2['total_duration'];
					$perYear = $amount/$duration;
					//echo $perYear .'</br>';
					
					$arr = array('Annualy', 'Monthly', 'Semesterly', 'Total');
					
					foreach ($arr as &$value) 
					{
						//$batchNameStkId = $_POST['batchYear']."_".$_POST['batchMonth']."_".$_POST['courseShortNameB']."_".$_POST['courseEntrMeth']."_".$value;
						$batchNameStkId = $_POST['batchYear']."_".$_POST['batchMonth']."_".preg_replace('/[^A-Za-z0-9\-]/', '_', $_POST['courseShortNameB'])."_".$_POST['courseEntrMeth']."_".$value;
						
						
						
						$descriptionStk = $batchName."_".$value;
						
						$details = array();
						$details = get_itemCat_details($batchName);
						//print_r($details);
						
						if( !(strtolower($_POST['courseEntrMeth']) == 'direct' && $value == 'Annualy') && !(strtolower($_POST['courseEntrMeth']) == 'direct' && $value == 'Monthly')  )
						{
							add_item_isAdminCat($batchNameStkId, $descriptionStk, $value, $details[0], $details[1], $details[2], $details[3],$details[4], $details[5], $details[7], $details[6], $details[8], $details[9], $details[10], 0, 0, 0, 1);	
						}
						
						if($value == "Annualy")
						{
							if(strtolower($_POST['courseEntrMeth']) == 'direct')
							{
							  //echo "No Annualy method for direct".'</br>';
							}
							else
							{
								$fee = $perYear;
								$calcPrice = number_format2($perYear,2);
								//echo "calcPrice A regular= ".$calcPrice.'</br>';
								add_item_price_isAdminCat($batchNameStkId, 1,'LKR', $fee, $details[0], 1);
							}
						}
						if($value == "Monthly")
						{
							if(strtolower($_POST['courseEntrMeth']) == 'direct')
							{
							  //echo "No Monthly method for direct".'</br>';
							}
							else
							{
								$fee = $perYear/12;
								$calcPrice = number_format2($perYear/12,2);
								//echo "calcPrice M regular = ".$calcPrice.'</br>';
								add_item_price_isAdminCat($batchNameStkId, 1,'LKR', $fee, $details[0], 1);
							}
						}
						if($value == "Semesterly")
						{
							if(strtolower($_POST['courseEntrMeth']) == 'direct')
							{
							  $fee = ($amount/3)+5000;
							  $calcPrice = number_format2(($amount/3)+5000,2);
							  //echo "calcPrice S direct = ".$calcPrice.'</br>';
							  add_item_price_isAdminCat($batchNameStkId, 1,'LKR', $fee, $details[0], 1);
							}
							else
							{
								$fee = ($perYear/2)+5000;
								$calcPrice = number_format2(($perYear/2)+5000,2);
								//echo "calcPrice S regular = ".$calcPrice.'</br>';
								add_item_price_isAdminCat($batchNameStkId, 1,'LKR', $fee, $details[0], 1);
							}
						}
						if($value == "Total")
						{
						    $fee = $amount;
							$calcPrice = number_format2($amount,2);
							//echo "calcPrice T regular & direct = ".$calcPrice.'</br>';
							add_item_price_isAdminCat($batchNameStkId, 1,'LKR', $amount, $details[0], 1);
						}
				
					}
					
				
                }
				
        if ($selected_id != -1)
			display_notification(_('Selected batch has been updated'));
		else
			display_notification(_('New batch has been added'));
		
		$Mode = 'RESET';
	}
}
if ($Mode == 'Delete')
{
	//the link to delete a selected record was clicked instead of the submit button
	$cat_id = get_stockCat_cat_id($selected_id);
	// PREVENT DELETES IF DEPENDENT RECORDS IN 'cust_branch'

	/*if ( (key_in_foreign_table($cat_id, 'stock_master', 'category_id')) || (key_in_foreign_table($cat_id, 'item_codes', 'category_id')) )
	{
		display_error(_("Cannot delete this batch because batch have records in Stock master/Item Code table."));
	}
	else
	{*/
		delete_batches($selected_id);
		display_notification(_('Selected batch has been deleted'));
	//}
	$Mode = 'RESET';
	
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
	$sav = get_post('show_inactive');
	unset($_POST);
	$_POST['show_inactive'] = $sav;
	if ($sav) $_POST['show_inactive'] = 1;
	
	/***********BOF Chat Added******************/
	$_POST['batchName'] = '';
	$_POST['courseNameB'] = '';
	$_POST['courseid'] = '';
	$_POST['courseShortNameB'] = '';
	$_POST['batchYear'] = -1;
	$_POST['batchMonth'] = -1;
	$_POST['courseEntrMeth'] = -1;
	$_POST['tuitionFee'] = 0.00;
	$_POST['uweFee'] = 0.00;
	$_POST['totalFee'] = 0.00;
	/***********EOF Chat Added******************/
}
//------------------------------------------------------------------------------------------------

//$result = get_salesmen(check_value('show_inactive'));
$result = get_all_batches(check_value('show_inactive'));

start_form();
start_table(TABLESTYLE, "width=60%");
//$th = array(_("Name"), _("Phone"), _("Fax"), _("Email"), _("Provision"), _("Break Pt."), _("Provision")." 2", "", "");
$th = array (_('Batch Name'), _('Course'), _('Years'),_('Month'),_('Entrance Methode'),_('Tuition Fee'),_('UWE Fee'),_('Total Fee'), '','');
inactive_control_column($th);
table_header($th);

$k = 0;

while ($myrow = db_fetch($result))
{
	alt_table_row_color($k);
	label_cell($myrow["batch_name"]);
	label_cell($myrow["course_full_name"]);
	//label_cell($myrow["course_short_name"]);
	//label_cell($myrow["course_id"]);
	label_cell($myrow["batch_year"]);
	label_cell($myrow["batch_month"]);
	label_cell($myrow["batch_entrM"]);
	amount_cell($myrow["tuitionFee"]);
	amount_cell($myrow["uweFee"]);
	amount_cell($myrow["totalFee"]);
	
	inactive_control_cell($myrow["id"], $myrow["inactive"], 'courses', 'id');
	
 	//edit_button_cell("Edit".$myrow["id"], _("Edit"));
 	delete_button_cell("Delete".$myrow["id"], _("Delete"));
  	end_row();
	
} //END WHILE LIST LOOP

inactive_control_row($th);
end_table();
echo '<br>';

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

if ($selected_id != -1) 
{
 	if ($Mode == 'Edit') {
		//editing an existing courses
		
		$myrow2 = get_batches($selected_id);
		
		//$_POST['batchName'] = $myrow2["batch_name"];
		$_POST['courseNameB'] = get_course_id($myrow2["course_full_name"]);
		$_POST['courseid'] = $myrow2["course_id"];
		$_POST['courseShortNameB'] = $myrow2["course_short_name"];
		$_POST['batchYear'] = $myrow2["batch_year"];
		$_POST['batchMonth'] = $myrow2["batch_month"];
		$_POST['courseEntrMeth'] = $myrow2["batch_entrM"];
		$_POST['tuitionFee']  = number_format2($myrow2["tuitionFee"],2);
		$_POST['uweFee']  = number_format2($myrow2["uweFee"],2);
		$_POST['totalFee']  = number_format2($myrow2["totalFee"],2);
	}
	hidden('selected_id', $selected_id);
	
	
} elseif ($Mode != 'ADD_ITEM') {
	
		//$_POST['courseRegFee']  = number_format2(1,2);
		$_POST['batchName'] = '';
		$_POST['courseNameB'] = -1;
		$_POST['courseShortNameB'] = '';
		$_POST['batchYear'] = -1;
		$_POST['batchMonth'] = -1;
		$_POST['courseEntrMeth'] = -1;
		$_POST['tuitionFee']  = number_format2(1,2);
		$_POST['uweFee']  = number_format2(0,2);
		$_POST['totalFee']  = number_format2(1,2);
}

start_table(TABLESTYLE2);

//text_row_ex(_("Batch Name").':', 'batchName', null);
course_name_list_row(_("Course Name").':', 'courseNameB', null);
hidden('courseid', null);
text_row_ex(_("Course Short Name").':', 'courseShortNameB', null);
course_year_list_row(_("Year:"), 'batchYear', null);
course_month_list_row(_("Month:"), 'batchMonth', null);
entranceMeth_list_row(_("Entrance Method:"), 'courseEntrMeth', null);
amount_row(_("Tuition Fee:"), 'tuitionFee', null);
amount_row(_("UWE:"), 'uweFee', null);
hidden('totalFee', null);

end_table(1);

submit_add_or_update_center($selected_id == -1, '', 'both');

end_form();

end_page();


function get_batches3($bname) //ger duration refered through main catagory table not course table
{
  //echo $bname;

  $sql = "SELECT b.*,c.total_duration FROM ".TB_PREF."stock_category sc LEFT JOIN ".TB_PREF."main_category mc ON mc.main_category_id  = sc.main_category_id
  LEFT JOIN ".TB_PREF."courses c ON c.id = mc.course_id
  LEFT JOIN ".TB_PREF."batches b ON b.id = sc.batch_id
  WHERE sc.description='".$bname."' ";
  
  $result = db_query($sql, "could not get batches");
  return db_fetch($result);
}


function get_batches2($bname)
{
  //echo $bname;
  $sql = "SELECT b.*,c.total_duration FROM ".TB_PREF."batches b LEFT JOIN ".TB_PREF."courses c ON b.course_id = c.id WHERE b.batch_name='".$bname."' ";
  $result = db_query($sql, "could not get batches");
  return db_fetch($result);
}


function get_calcAmount_for_paymeth($amount,$years)
{
  $final = 0;
  
  $perYear = $amount/$years;  
  
  if($paymth=="Annualy")
  {
	  //$final = number_format2($perYear,2);
	  return number_format2($perYear,2);
  }
  elseif($paymth=="Monthly")
  {
	  //$final = number_format2($perYear/12,2);
	  return number_format2($perYear/12,2);
  }
  elseif($paymth=="Semesterly")
  {
	  //$final =  number_format2($perYear/2,2);
	  return number_format2($perYear/2,2);
  }
  elseif($paymth=="Total")
  {
	  //$final =  number_format2($amount,2);
	  return number_format2($amount,2);
  }
  return $final;

  //echo "Final Fee= ".$final;
}	



?>
