<style>
  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;
}
</style>
<?php
date_default_timezone_set('GMT');

session_start();
include("../../php_crud/my_class.php");
$obj = new my_class();

//
$curr_date = date('d-m-Y h:i');

$curr_date =  strtotime($curr_date);

//

$river = trim($_POST[' river']);
$station_id = trim($_POST['station_id']);
//$year    = trim($_POST['year']);
//$month = trim($_POST['month']);
//echo "$subdivision<br/>$station_id<br/>$year<br/>$month";
$file = $_FILES['td_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['td_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_'.$river.'_'.$station_id .'.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 = 'B';
		$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="td_save_btn" type="button" style="margin-right: 1px; padding: 4px!important; font-size: 12px;" class="btn btn-small btn-success" onclick="td_multiple_save()"><i class="icon-save"></i><b>Save All</b></button>
                 </div>
             </div>
         </div>
			<table id="td_dis_data_table" class="table table-bordered table-hover">
            
				<thead style="background-color: #ffb752;">
					<tr style="font-family: \'Open Sans\';">
                    <th style="text-align:center; background-color: #b3e0ff;">Date Time</th>
                    <th style="text-align:center; background-color: #b3e0ff;">Water Level (m)</th>
                    <th style="text-align:center; background-color: #b3e0ff;">Water Width (m)</th>
                    <th style="text-align:center; background-color: #b3e0ff;">Area (m2)</th>
                    <th style="text-align:center; background-color: #b3e0ff;">Discharge (m3/s)</th>
                    <th style="text-align:center; background-color: #b3e0ff;">V Max (m/s)</th>
                    <th style="text-align:center; background-color: #b3e0ff;">V Mean (m/s)</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="td_dis_data_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 H:i:s', PHPExcel_Shared_Date::ExcelToPHP($row_data[0][0]));
					$date = date('Y-m-d H:i:s', PHPExcel_Shared_Date::ExcelToPHP($row_data[0][0]));
					$timestamp = strtotime($date);
					$day = date("j", $timestamp);
					$date = date('Y-m-d H:i:s',strtotime('-6 hour',strtotime($date)));
					$date = date('d/m/Y H:i',strtotime($date));
					$date = strtoupper($date);
          $input_date = strtoupper($date);

					        if($row_data[0][0] != ""){
				          	$wl_data        = $row_data[0][1];
                    $ww_data        = $row_data[0][2];
                    $area_data      = $row_data[0][3];
                    $discharge_data = $row_data[0][4];
                    $vmax_data      = $row_data[0][5];
                    $vmean_data     = $row_data[0][6]; 
                    $note_data      = $row_data[0][7];
                
					// $date_id = "date_$day";
					// $rf_col_id = "rf_$day";
                    $date_id      = "date_$r_id";
                    $wl_id        = "wl_$r_id";
                    $ww_id        = "ww_$r_id";
                    $area_id      = "area_$r_id";
                    $discharge_id = "dischrg_$r_id";
                    $vmax_id      = "vmax_$r_id";
                    $vmean_id     = "vmean_$r_id";
                    $note_id      = "note_$r_id";

                    $after_note_id="";  
                    $next_row_val          = $r_id+ 1;
                    $after_note_id         = "date_$next_row_val";
                    $function_for_nxt_val  = "call_next_val_loader(event,'$note_id','$after_note_id')";
                    $function_for_wl       = "call_save_function(event,'$vmean_id','$after_note_id','$r_id')";
                      ////Current Date Issue////
                    $input_date = strtotime($input_date);
                   //  echo "Input".$input_date;
                   //  echo '<br>';
                   //  echo "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="wl_id" name="wl_id[]" value="'.$wl_id.'"/> 
                            <input type="hidden" class="ww_id" name="ww_id[]" value="'.$ww_id.'"/> 
                            <input type="hidden" class="area_id" name="area_id[]" value="'.$area_id.'"/> 
                            <input type="hidden" class="discharge_id" name="discharge_id[]" value="'.$discharge_id.'"/> 
                            <input type="hidden" class="vmax_id" name="vmax_id[]" value="'.$vmax_id.'"/> 
                            <input type="hidden" class="vmean_id" name="vmean_id[]" value="'.$vmean_id.'"/> 
                            <input type="hidden" class="note_id" name="note_id[]" value="'.$note_id.'"/> 

							<td style="text-align: center;">
                                <input type="text" class=" td_date" name="date-time"  id="'.$date_id.'" style="text-align: center;font-weight:bold; width:60%;" value="'.$date.'" onkeyup="'.$call_key_up_function.'">
                            </td>
							<td style="text-align: center;">
                                <input type="text" class="input-mini td_wl" name="water-level" id="'.$wl_id.'" style="text-align:center;font-weight:bold; "  value="'.$wl_data.'"  onkeyup="call_next_val_loader(event,\''.$wl_id .'\',\''. $ww_id.'\')" onkeypress="return isDecimalInput(event) ">
                            </td>
                            <td style="text-align: center;">
                                 <input type="text" class="input-small td_ww" name="water-width" id="'.$ww_id.'" style="text-align:center;font-weight:bold; " value="'.$ww_data.'"  onkeyup="call_next_val_loader(event,\''. $ww_id .'\',\''. $area_id.'\')"  onkeypress="return isNumericInput(event)">
                            </td>
                            <td style="text-align: center;">
                                 <input type="text" class="input-small td_area" name="area" id="'.$area_id.'" style="text-align:center;font-weight:bold; " value="'.$area_data.'" onkeyup="call_next_val_loader(event,\''.$area_id .'\',\''. $discharge_id.'\')" onkeypress="return isNumericInput(event)">
                            </td>
                            <td style="text-align: center;">
                                 <input type="text" class="input-mini td_discharge" name="discharge" id="'.$discharge_id.'" style="text-align:center;font-weight:bold; " value="'.$discharge_data.'" onkeyup="call_next_val_loader(event,\''.$discharge_id.'\',\''.$vmax_id.'\')" onkeypress="return isNumericInput(event)">
                            </td>
                            <td style="text-align: center;">
                                <input type="text" class="input-mini td_v_max" name="v-max" id="'.$vmax_id.'" style="text-align:center;font-weight:bold; " value="'.$vmax_data.'"   onkeyup="call_next_val_loader(event,\''. $vmax_id.'\',\''. $vmean_id.'\')" onkeypress="return isNumericInput(event)">
                            </td>
                            <td style="text-align: center;">
                                 <input type="text" class="input-mini td_v_mean" name="v-mean" id="'.$vmean_id.'" style="text-align:center;font-weight:bold; " value="'.$vmean_data.'" onkeyup="call_next_val_loader(event,\''. $vmean_id.'\',\''. $note_id.'\')" onkeypress="return isNumericInput(event)">
                            </td>
                            <td style="text-align: center;">
                                <input type="text" class="input-mini td_note" name="note" id="'.$note_id.'" style="text-align:center;font-weight:bold; " value="'.$note_data.'" onkeyup="'.$function_for_wl.'">
                            </td>
                            <td style="text-align: center;">
                                <button class="btn btn-minier btn-purple" type="button" onclick="save_single_td_discharge_info('.$r_id.',\'btn_click\')"><i class="icon-save"></i> <b style="padding:-1%!important;">Save</b></button>
                           </td>
            
						</tr>';			 
			}
    }
			$mon = date("m", $timestamp);
			$yr = date("Y", $timestamp);
			$mm_yy = "$mon-$yr";
				$table .= '</tbody>
                </table>
				<input type="text" style="width: 95%;" id="ex_mm_yr" name="ex_mm_yr" value="'.$mm_yy.'" />
                <div class="row-fluid" style="margin-bottom:5px;">
                     <div class="control-group" style="float:right;">
                        <div class="controls">
                              <button id="td_save_btn" type="button" style="margin-right: 1px; padding: 4px!important; font-size: 12px;" class="btn btn-small btn-success" onclick="td_multiple_save()"><i class="icon-save"></i><b>Save All</b></button>
                        </div>
                     </div>
                 </div>';
			echo $table;
			
	}else{
		echo "upload error";
	}
}else{
   echo "File Could not Upload .Check Directory permission missing";	   
}
unlink($excel_file);	
?>


<script type="text/javascript">
    function call_next_val_loader(e, sel_col_id,next_col_id){
		// if(event.keyCode==13 || event.keyCode=='tab'){
		// 	var curr_val = $("#"+sel_col_id).val();
		// 	//$("#"+sel_col_id).select();
		// 	//alert('moving to the next column');
		// 	//save_water_level_info(sel_col_id,curr_val,next_col_id);
		// 	$("#"+next_col_id).select();
		// }
    if(event.keyCode==13 || event.keyCode=='tab' || event.keyCode==9){
			var col_name_arr = sel_col_id.split("_");
			var col_name = col_name_arr[0];
			var curr_val = $("#"+sel_col_id).val();
      //for date validation
      // alert(curr_val);
      if(col_name=='date'){
			//alert(col_name);
			var operation = "date_checker";
      var cur_date = encodeURIComponent($("#"+sel_col_id).val());
			var datastr = "operation="+operation+"&sel_in_date="+cur_date;
      //alert(datastr);
			$.ajax({
				url: 'module/ground_water_ex/tidal_discharge_entry_from_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();
					}
					
				}
			});
		}
      //for validation end


			//alert(col_name);
      
				// if(curr_val.length==1 || curr_val.length==2){
				// 	curr_val = curr_val+'.00';
				// 	$("#"+sel_col_id).val(curr_val);
				// }
			
        else{
				if (curr_val > Math.floor(curr_val)) {
					curr_val = parseFloat(curr_val).toFixed(2);
				}
				else{
					curr_val = (Math.round(curr_val * 100) / 100).toFixed(2);
				}
				$("#"+sel_col_id).val(curr_val);
      }
			//$("#"+sel_col_id).select();
			//alert('moving to the next column');
			//save_water_level_info(sel_col_id,curr_val,next_col_id);
			$("#"+next_col_id).select();
		}
	}

	function call_save_function(e,sel_col_id,next_col_id,sel_day){
		// if(event.keyCode==13 || event.keyCode=='tab'){
		// 	alert('will be saving now');
		// 	save_single_td_discharge_info(sel_day,press_op)
		// 	$("#"+next_col_id).select();
		// }
    if(event.keyCode==13 || event.keyCode=='tab'|| event.keyCode==9){
			var col_name_arr = sel_col_id.split("_");
			var col_name = col_name_arr[0];
			var curr_val = $("#"+sel_col_id).val();
  
		
				// if(curr_val.length==1 || curr_val.length==2){
				// 	curr_val = curr_val+'.00';
				// 	$("#"+sel_col_id).val(curr_val);
				// }
			// else{
				if (curr_val > Math.floor(curr_val)) {
					curr_val = parseFloat(curr_val).toFixed(2);
				}
				else{
					curr_val = (Math.round(curr_val * 100) / 100).toFixed(2);
				}
				$("#"+sel_col_id).val(curr_val);
		//	}
			//var press_op = "enter_click";
      var press_op = "enter_click";
     // alert(press_op);
			save_single_td_discharge_info(sel_day,press_op);
    	$("#"+next_col_id).select();
		}
	}
</script>

<!--validation-->
<!-- <script type="text/javascript">
 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();
    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> -->
 <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>
 
 <script>
let inputReset = false;
function isNumberKey(evt) {
    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();
    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 a value less than -99.99 or greater than 99.99, disallow it
  const newValue = parseFloat(currentValue + keyChar);
  if (newValue < 0000 || newValue > 9999) {
    event.preventDefault();
    event.target.value = "";
    event.target.value += keyChar;
    return 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 !== "-") {
    inputReset = true;
    event.preventDefault();
    return false;
  }
  
  if (currentValue === "0" && keyChar !== "." && keyChar !== "-") {
    event.preventDefault();
    return false;
  }

  return true;
}
</script>

<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>
<!--load new row-->
<script type="text/javascript">
var filed = <?php echo $r_id; ?>;
 //alert(filed);
function load_new_row(){
 //alert('load_new_row');
  filed++;
	var datastr="row_num="+filed;
	// alert(datastr);
			$.ajax({
				type:"post",
				url:"module/ground_water_ex/load_item_tbl_for_td_discharge_request.php",
				data:datastr ,
				success:function(st){
				//alert(st);
				// $("#td_dis_data_table").append(st);
        $("#td_dis_data_tbl_body").append(st);
        $('#date_'+filed).select();
				}
			}); 
}

</script>
<script>
  function show_alert(event){
		alert('You cannot enter for any day after today');
	}
</script>
