<style type="text/css">
  select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input {
  display: inline-block;
  height: 1px!important;
  padding: 8px 3px!important;
  margin-bottom: 2px!important;
  font-size: 13px!important;
  line-height: 23px!important;
  color: #555;
  vertical-align: middle;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}
.table th, .table td {
  padding: 2px!important;
  line-height: 20px;
  text-align: left;
  vertical-align: top;
  border-top: 1px solid #ddd;
}
.button{
position: relative;
top: -20px;
}
.tbl{
position: relative;
top: -15px;
}
</style>
<?php
session_start();
include("../../php_crud/my_class.php");
$obj = new my_class();

///--Date--///
$date_array = explode("-", $date);
$month = $date_array[0];
$year = $date_array[1];
$month_day = cal_days_in_month(CAL_GREGORIAN,$month,$year);
$curr_date = date('d-m-Y');
$curr_date =  strtotime($curr_date);
$is_readonly = "";
$call_key_up_function = "";
//print_r($curr_date);
///--Date--///

$station_id = trim($_POST['station']);
$river_name = trim($_POST['river_name']);

//echo "$subdivision<br/>$station_id<br/>$year<br/>$month";
$file = $_FILES['od_file']['name'];

$dir = '../../asset/custom/upload/';	 
$excel_file = $dir .$file;

if(file_exists($excel_file)){
	//echo "file_exists<br/>";
  unlink($excel_file);
}

if(is_writable($dir)) 
{
	//echo "write directory<br/>";
	if(move_uploaded_file($_FILES['od_file']['tmp_name'] , $excel_file))	
	{									
		//echo "file_moved<br/>";
		$i =0;
		error_reporting(1);  //E_ALL
		ini_set('display_errors', TRUE);
		ini_set('display_startup_errors', TRUE);

		require_once('../../asset/custom/PHPExcel_class/PHPExcel.php');
		require_once('../../asset/custom/PHPExcel_class/PHPExcel/Calculation.php');
		require_once('../../asset/custom/PHPExcel_class/PHPExcel/Cell.php');
	
		$inputFileType = 'Excel5';			
		$filename = '../../asset/custom/upload/sample_mark_sheet_'.$station_id.'_'.$river_name .'_'.$year.'_'.$month.'.xlsx';			
		//$inputFileName =  $filename;
		$inputFileName =  $excel_file;
			
			
		//  Read your Excel workbook
		try {
			//echo "<br/>inside try";
			$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
			//echo "<br/>input file worked";
			$objReader = PHPExcel_IOFactory::createReader($inputFileType);
			//echo "<br/>objReader worked";
			$objPHPExcel = $objReader->load($inputFileName);
			//echo "<br/>objPHPExcel worked";
		} catch (Exception $e) {
			echo $excel_file;
			echo "<br/>";
			die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
		}
			
		$sheet = $objPHPExcel->getSheet(0);
		$highestRow = $sheet->getHighestRow();
		$highestColumn = $sheet->getHighestColumn();
		$high = $highestRow;			
		$highestColumn = 'K';
		$data = array();
		$i = 0;

		//=========================== excel uploaded grid 	start

		$table =
			'<button  style="float:left;" id="btn2" class="btn btn-warning" onclick="load_new_row()">New</button>
			<div class="row-fluid" style="margin-bottom:5px;">
			  <div class="control-group" style="float:right;">
				  <div class="controls">
					  <button id="obs_dis_sva_btn" type="button" style="margin-right: 1px; padding: 4px!important; font-size: 12px;" class="btn btn-small btn-success" onclick="obs_dis_multiple_save()"><i class="icon-save"></i><b>Save All</b></button>
				  </div>
			  </div>
		  	</div>
			
			<table id="obs_dis_data_table" class="table table-bordered table-hover">
				<thead style="background-color: #ffb752;">
					<tr>
					<th style="text-align:center;  background-color: #b3e0ff; width: 15%;">Date</th>
					<th style="text-align:center;  background-color: #b3e0ff;">WL (m)</th>
					<th style="text-align:center;  background-color: #b3e0ff; width:10%;">Discharge (m3/s)</th>
					<th style="text-align:center;  background-color: #b3e0ff;">Area (m2)</th>
					<th style="text-align:center;  background-color: #b3e0ff;">Width (m)</th>
					<th style="text-align:center;  background-color: #b3e0ff; ">Max Depth (m)</th>
					<th style="text-align:center;  background-color: #b3e0ff;">Max Depth Location</th>
					<th style="text-align:center;  background-color: #b3e0ff;">Max Velocity (m/s)</th>
					<th style="text-align:center;  background-color: #b3e0ff;">Location </th>
					<th style="text-align:center;  background-color: #b3e0ff;">Section ID</th>
					<th style="text-align:center;  background-color: #b3e0ff;">Note</th>
					<th style="text-align:center;  background-color: #b3e0ff;">Action</th>
					</tr> 
				</thead>
				<tbody id = "ods_tbl_body">';
				$r_id = 0;
				for ($row = 2; $row <= $high; $row++) {
					
					$r_id ++;
					$row_data = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);   
					$date = date('d/m/Y', PHPExcel_Shared_Date::ExcelToPHP($row_data[0][0]));
					//$date = date('d-M-Y h:i', PHPExcel_Shared_Date::ExcelToPHP($row_data[0][0]));
					$timestamp = strtotime($date);
					$day = date("j", $timestamp);
					$date = strtoupper($date);
					$input_date = date('d-m-Y',strtotime($date)); 
					//$input_date = strtoupper($date);
					//print_r($input_date);

					if($row_data[0][0] != ""){
						$wl  = $row_data[0][1];
						$dis = $row_data[0][2];
						$area  = $row_data[0][3];
						$width  = $row_data[0][4];
						$max_dep  = $row_data[0][5];
						$max_dep_loc = $row_data[0][6];
						$max_vel = $row_data[0][7];
						$loc = $row_data[0][8];
						$sta = $row_data[0][9];
						$note = $row_data[0][10];

						$date_id = "date_$r_id";
						$wl_id = "obs_discharge_wl_$r_id";
						$disch_id = "obs_discharge_disch_$r_id";
						$csa_id = "obs_discharge_csa_$r_id";
						$rw_id = "obs_discharge_rw_$r_id";
						$md_id = "obs_discharge_md_$r_id";
						$mdl_id = "obs_discharge_mdl_$r_id";
						$mval_id = "obs_discharge_mval_$r_id";
						$loc_id = "obs_discharge_local_$r_id";
						$sta_id = "obs_discharge_sect_col_$r_id";
						$note_id = "obs_discharge_not_col_$r_id";
						$date_row_id = "date_row_$r_id";
						$after_obs_discharge_not_col_id = "";
						$next_row_val = $r_id + 1;
						$after_note_id = "date_$next_row_val";

						////Current Date Issue////
						$input_date = strtotime($input_date);
						// print_r("Inpute: $input_date");
						// print_r("<br>");
						// print_r("Current: $curr_date");
						if($input_date > $curr_date){
						$is_readonly = "readonly";
						$call_key_up_function = "show_alert(event)";
						}
						else{
						 $is_readonly = "";
						 $call_key_up_function = "call_next_val_loader(event,'$date_id','$wl_id')";
					   }
					   ////Current Date Issue////
	
						$table .= '<tr id="'.$r_id.'">	
								<input type="hidden" class="date" name="date[]" value="'.$date.'"/> 
								<input type="hidden" class="swq_wl" name="od_wl[]" value="'.$wl_id.'"/> 
								<input type="hidden" class="swq_bp" name="od_dis[]" value="'.$disch_id.'"/> 
								<input type="hidden" class="swq_temp" name="od_ar[]" value="'.$csa_id.'"/> 
								<input type="hidden" class="swq_ph" name="od_wid[]" value="'.$csa_id.'"/> 
								<input type="hidden" class="swq_do" name="od_md[]" value="'.$md_id.'"/> 
								<input type="hidden" class="swq_sal" name="od_mdl[]" value="'.$mdl_id.'"/> 
								<input type="hidden" class="swq_tds" name="od_mv[]" value="'.$mval_id.'"/> 
								<input type="hidden" class="swq_ec" name="od_loc[]" value="'.$loc_id.'"/> 
								<input type="hidden" class="swq_trns" name="od_sta[]" value="'.$sta_id.'"/> 
                                <input type="hidden" class="swq_note" name="od_nt[]" value="'.$note_id.'"/>  
	
								<td style="text-align: center;">
									<input type="text" id="'.$date_id.'" class="input-small month_date" style="text-align: center; font-weight: 700;" value="'.$date.'" onkeyup="'.$call_key_up_function.'"</td>
								<td style="text-align: center;">
									<input onkeypress="return isDecimalInput(event)" type="text" class="input-mini waterlevel" style="text-align: center; font-weight: bold;" id="'.$wl_id.'"
									value="'.$wl.'" onkeyup="call_next_val_loader(event,\''.$wl_id .'\',\''. $disch_id.'\')"></td>
								<td style="text-align: center;">
									<input onkeypress="return isNumericInput(event)" type="text" class="input-mini dis" style="text-align: center; font-weight: bold;" id="'.$disch_id.'"
									value="'.$dis.'" onkeyup="call_next_val_loader(event,\''.$disch_id .'\',\''. $csa_id.'\')"></td>	
								<td style="text-align: center;">
									<input onkeypress="return isNumericInput(event)" type="text" class="input-mini area" style="text-align: center; font-weight: bold;" id="'.$csa_id.'"
									value="'.$area.'" onkeyup="call_next_val_loader(event,\''.$csa_id .'\',\''. $rw_id.'\')"></td>
								<td style="text-align: center;">
									<input onkeypress="return isNumericInput(event)" type="text" class="input-mini width" style="text-align: center; font-weight: bold;" id="'.$rw_id.'"
									value="'.$width.'" onkeyup="call_next_val_loader(event,\''.$rw_id .'\',\''. $md_id.'\')"></td>
								<td style="text-align: center;">
									<input onkeypress="return isNumericInput(event)" type="text" class="input-mini max_dep" style="text-align: center; font-weight: bold;" id="'.$md_id.'"
									value="'.$max_dep.'" onkeyup="call_next_val_loader(event,\''.$md_id .'\',\''. $mdl_id.'\')"></td>
								<td style="text-align: center;">
									<input onkeypress="return isNumericInput(event)" type="text" class="input-mini max_dep_loc" style="text-align: center; font-weight: bold;" id="'.$mdl_id.'"
									value="'.$max_dep_loc.'" onkeyup="call_next_val_loader(event,\''.$mdl_id .'\',\''. $mval_id.'\')"></td>
								<td style="text-align: center;">
									<input onkeypress="return isNumericInput(event)" type="text" class="input-mini max_vel" style="text-align: center; font-weight: bold;" id="'.$mval_id.'"
									value="'.$max_vel.'" onkeyup="call_next_val_loader(event,\''.$mval_id .'\',\''. $loc_id.'\')"></td>
								<td style="text-align: center;">
									<input onkeypress="return isNumericInput(event)" type="text" class="input-mini location" style="text-align: center; font-weight: bold;" id="'.$loc_id.'"
									value="'.$loc.'" onkeyup="call_next_val_loader(event,\''.$loc_id .'\',\''. $sta_id.'\')"></td>	
								<td style="text-align: center;">
									<input onkeypress="return isNumericInput(event)" type="text" class="input-mini station" style="text-align: center; font-weight: bold;" id="'.$sta_id.'"
									value="'.$sta.'" onkeyup="call_next_val_loader(event,\''.$sta_id .'\',\''. $note_id.'\')"></td>
                                <td style="text-align: center;">
									<input type="text" class="input-mini note" style="text-align: center; font-weight: bold;" id="'.$note_id.'"
									value="'.$note.'" 
									onkeyup = "save_n_load_next_row(event,\''. $note_id. '\',\'' .$after_note_id.'\',\'' .$r_id. '\')"></td>
								<td style="text-align: center;">
								<button class="btn btn-minier btn-purple" type="button" onclick="save_single_observed_discharge_info('.$r_id.',\'btn_click\')"><i class="icon-save"></i> <b style="padding:-1%!important;">Save</b></button>
								</td>																						
							</tr>';		
					}
						 
			}
				$table .= '</tbody></table>
				<div class="row-fluid" style="margin-bottom:5px;">
				<div class="control-group" style="float:right;">
					<div class="controls">
						<button id="obs_dis_sva_btn" type="button" style="margin-right: 1px; padding: 4px!important; font-size: 12px;" class="btn btn-small btn-success" 
						onclick="obs_dis_multiple_save()"><i class="icon-save"></i><b>Save All</b></button>
						</div>
					</div>
				</div>
				<input type="hidden" id="total_row" name="total_row" value="'.$row.'" />';
			echo $table;
			
	}else{
		echo "upload error";
	}
}else{
   echo "File Could not Upload .Check Directory permission missing";	   
}
unlink($excel_file);	
?>

<!-- ================ input  validation ================= -->

<script>
function call_next_val_loader(e, sel_col_id,next_col_id){
	//alert('call_next_val_loader');
    if(event.keyCode==13 || event.keyCode=='tab'){
		var curr_val = $("#"+sel_col_id).val();
		var col_name_arr = sel_col_id.split('_');
		var col_name = col_name_arr[0];
        //alert(curr_val);
		if(col_name=='date'){
			//alert(col_name);
			var operation = "date_checker";
			var datastr = "operation="+operation+"&sel_in_date="+curr_val;
            //alert(datastr);
			$.ajax({
				url: 'module/ground_water_ex/observed_discharge_information_ajax.php', 
				type: 'post',
				data: datastr,
				cache: false,
				success: function(result) {
					//alert(result);
					if(result== 0){
						alert('You only enter data till today');
                        $("#"+sel_col_id).val('');
                        $("#"+sel_col_id).select();
						return false;
					}
					else{
						$("#"+sel_col_id).val(result);
                        $("#"+next_col_id).select();
					}
					
				}
			});
		}
		else{
			if (curr_val > Math.floor(curr_val)) {
				curr_val = parseFloat(curr_val).toFixed(2);
			}
			$("#"+sel_col_id).val(curr_val);
            $("#"+next_col_id).select();
		}
    }
}
function save_n_load_next_row(e, sel_col_id,next_col_id,sel_row){
	if(event.keyCode==13 || event.keyCode=='tab'){
		//alert(sel_col_id);
		//alert(next_col_id);
		var curr_val = $("#"+sel_col_id).val();
		var press_op = 'enter_press';
       // $("#"+sel_col_id).select();
        save_single_swq_info(sel_row,press_op);
        $("#"+next_col_id).select();
		/*var tot_row = <?php echo $row_id; ?>;
		if(tot_row==sel_row){
			load_new_row();
		}*/
	}
}
</script>
<script>
var filed = <?php echo $r_id; ?>;
//alert(filed);
function load_new_row(){
	filed++;
	var datastr="row_num="+filed;
    //alert(datastr);
	$.ajax({
		type:"post",
		url:"module/ground_water_ex/load_new_row_for_observed_discharge.php",
		data:datastr ,
		success:function(st){
		//	alert(st);
            $("#ods_tbl_body").append(st);
			$('#date_'+filed).select();
             $('#total_row').val(filed);
		}
	}); 
}
</script>

<!-- 00.00 formating and Alpha-Numeric Checking-->
<script>
let inputReset = false; // Track whether input should be reset

function isDecimalInput(event) {
const key = event.keyCode || event.which;
const keyChar = String.fromCharCode(key);

const regex = /[0-9]|\.|\-/;

// Only allow numeric, decimal, or minus sign input
if (!regex.test(keyChar)) {
  event.preventDefault();
  return false;
}

const input = event.target;
const currentValue = input.value;

// If the input already contains a decimal point or minus sign, disallow another one
if ((keyChar === "." && currentValue.indexOf(".") !== -1) || 
    (keyChar === "-" && currentValue.indexOf("-") !== -1)) {
  event.preventDefault();
  event.target.value = "";
  event.target.value += keyChar;
  return false;
}

//If the input would result in a value less than -99.99 or greater than 99.99, disallow it
const newValue = parseFloat(currentValue + keyChar).toFixed(2);
if (newValue < -99.99 || newValue > 99.99) {
  event.preventDefault();
  return false;
}

// If input should be reset, do so and allow new input
if (inputReset) {
  input.value = "";
  inputReset = false;
}

// If the input would result in more than 2 decimal places, set inputReset flag
const parts = currentValue.split(".");
if (parts.length === 2 && parts[1].length >= 2 && keyChar !== "-") {
  event.preventDefault();
  event.target.value = "";
  event.target.value += keyChar;
  return false;
}

if (currentValue === "0" && keyChar !== "." && keyChar !== "-" && currentValue.indexOf(".") === -1) {
  event.preventDefault();
  return false;
}

return true;
}
</script>
<!-- 00.00 formating and Alpha-Numeric Checking-->

<!-- Alpha-Numeric Checking-->
<script>
let inputReset = false; // Track whether input should be reset

function isNumericInput(event) {
const key = event.keyCode || event.which;
const keyChar = String.fromCharCode(key);

const regex = /[0-9]|\.|\-/;

// Only allow numeric, decimal, or minus sign input
if (!regex.test(keyChar)) {
  event.preventDefault();
  return false;
}

const input = event.target;
const currentValue = input.value;

// If the input already contains a decimal point or minus sign, disallow another one
if ((keyChar === "." && currentValue.indexOf(".") !== -1) || 
    (keyChar === "-" && currentValue.indexOf("-") !== -1)) {
  event.preventDefault();
  event.target.value = "";
  event.target.value += keyChar;
  return false;
}

// If the input would result in a value less than -99.99 or greater than 99.99, disallow it
// const newValue = parseFloat(currentValue + keyChar).toFixed(2);
// if (newValue < -99.99 || newValue > 99.99) {
//   event.preventDefault();
//   return false;
// }

// If input should be reset, do so and allow new input
if (inputReset) {
  input.value = "";
  inputReset = false;
}

// If the input would result in more than 2 decimal places, set inputReset flag
const parts = currentValue.split(".");
if (parts.length === 2 && parts[1].length >= 2 && keyChar !== "-") {
  event.preventDefault();
  event.target.value = "";
  event.target.value += keyChar;
  return false;
}

if (currentValue === "0" && keyChar !== "." && keyChar !== "-" && currentValue.indexOf(".") === -1) {
  event.preventDefault();
  return false;
}

return true;
}
</script>
<!-- Alpha-Numeric Checking-->
<script>
  function show_alert(event){
		alert('You cannot enter for any day after today');
	}
</script>