<?php
	ob_start();
	include_once("class/class.MySQL.php");
	$db	=new MySQL();
	//session_start();
	error_reporting(-1);
	
    if(isset($_POST['btnsubmit']))
	{
		echo "hiiii";
	}
	
			if(isset($_POST['save'])){
		   			
			
			if(isset($_POST['filename'])){
			$filename=addslashes($_POST['filename']);
			}
			
			if(isset($_POST['branchid'])){
			$branchid=addslashes($_POST['branchid']);
			}
			
			$sqldevice = mysql_query("select * from branches where branch_id = '$branchid' ");
			$rwdevice=mysql_fetch_array($sqldevice);
			$deviceid=$rwdevice['device_id'];
			
			$import_file=strtolower($_FILES['import_file']['name']);
			$tmp_file=$_FILES['import_file']['tmp_name'];
			mysql_query("TRUNCATE TABLE cf_deliveryarea");
			mysql_query("Delete from cf_deliverycsv");
			if($import_file!="")
			{
				$path=pathinfo($import_file);
				
				$ext=$path['extension'];
				$allowed=array('csv');
				if(in_array($ext,$allowed))
				{
						$uploaddir = 'import/';
						$uploadfile = $uploaddir.$import_file;
						if($fal=move_uploaded_file($tmp_file,$uploadfile))
						{
							$filename=$uploadfile;
							$id = fopen($filename, "r"); 
							while ($data = fgetcsv($id, filesize($filename))) 
								$table[] = $data; 
							fclose($id); 
							
							//echo "<table border='1'>\n";
							$num=1;
							foreach($table as $row)
							{
							
								if($num==1)
								{
									$num++;
									continue;
								}
								//echo "<tr>";
								$arr = array();
							   foreach($row as $data)
							   {
									$arr[]=$data;
									//echo "<td>$data</td>";
							   }
							 	//echo "<pre>";
								//print_r($arr);  
							   $item_id=trim($arr[0]);
							//-----------------------------------------------------------------------------//
							 
							// $arr[1]
							 
							$dt =  explode("/",$arr[1]);
							//print_r($dt);
							//echo "<br/>";
							//$edate = date('Y-m-d', strtotime($arr[1]));
							
							$edate = $dt[2].'-'.$dt[1].'-'.$dt[0];
							$empid = $arr[2];
							/*$branchid = $arr[3];
							$deviceid = $arr[4];*/
							$ein = $arr[3];
							$eout = $arr[4];
							
							$time1 = strtotime($arr[3]);
							$time2 = strtotime($arr[4]);
							
							if($ein == 'L')
							{
								$sqleavecnt = mysql_query("select * from payroll_user_leave_requests where day_from = '$edate' and employee_id = '$empid'");
								
							 	if(mysql_num_rows($sqleavecnt) > 0){
								
								echo "UPDATE payroll_user_leave_requests set employee_id='$empid',leave_id='21',no_of_days='1',day_from='$edate',day_to='$edate',reason='Personal',half_full_day='2',imd_status='1'
 where  day_from='$edate' and employee_id='$empid'";
 echo "<br/>";
							 	 $query6=mysql_query("UPDATE payroll_user_leave_requests set employee_id='$empid',leave_id='21',no_of_days='1',day_from='$edate',day_to='$edate',reason='Personal',half_full_day='2',imd_status='1'
 where  day_from='$edate' and employee_id='$empid'");
							 	
								
							 }
							 else
							 {
							 		$query6=mysql_query("INSERT INTO payroll_user_leave_requests (employee_id,leave_id,no_of_days,day_from,day_to,reason,half_full_day,imd_status) 
									VALUES ('".$empid."','21','1','".$edate."','".$edate."','Personal','2','1')");
							 }
							}
							else{
							
							$diff = $time2 - $time1;
							//echo "<br/>";
							
							$totalWorkTime = date('H:i:s',strtotime("-6 hours 30 minutes",$diff));
							
							$LogTimeIn =  date("H:i",strtotime($ein));  
							$dt_frtIn =  date('A', strtotime($ein));
							
							$LogTimeOut =  date("H:i",strtotime($eout));  
							$dt_frtOut =  date('A', strtotime($eout));
							 
							 
							 $ein_nw = $edate.' '.$ein;
							 $eout_nw = $edate.' '.$eout; 
							 
							$sqlcnt = mysql_query("select * from time
 where e_date = '$edate' and e_id = '$empid'");
							 if(mysql_num_rows($sqlcnt) > 0){
							 
							 $ein_nw = $edate.' '.$ein;
							 	 $query5="UPDATE time
 set e_in='$ein_nw',e_out='$eout_nw',e_work='$totalWorkTime',time_in='$LogTimeIn',time_inloc='$dt_frtIn',time_out='$LogTimeOut',time_outloc='$dt_frtOut',total_worked_hours='$totalWorkTime' 
 where  e_date='$edate' and e_id='$empid'";
							 	
							 }else{
							 	 $query5="INSERT INTO time
 (e_date,e_id,deviceids,e_in,e_out,e_work,time_in,time_inloc,time_out,time_outloc,total_worked_hours,brchid) 
									VALUES ('".$edate."','".$empid."','".$deviceid."','".$ein_nw."','".$eout_nw."','".$totalWorkTime."','".$LogTimeIn."','".$dt_frtIn."','".$LogTimeOut."','".$dt_frtOut."','".$totalWorkTime."','".$branchid."')";
							   } 
							 
							
							 mysql_query($query5) or die("Some Data base Error".mysql_error());
							
							 unset($arr);
								//echo "<td>$query</td></tr>\n";
							} 
						}	
						exit;	
							 $queryin="INSERT INTO cf_deliverycsv (filename,dates) 
															VALUES ('".trim($import_file)."','".date("Y-m-d")."')";
							 mysql_query($queryin) or die("Some Data base Error".mysql_error());
								//}
							//@unlink($filename);
							/*echo "<script>alert('Succesfully Uploaded to Database');</script>";
							echo "<script> document.location='attendance-upload.php?user=".$user."';</script>";
							exit;*/
							
							//echo "</table>\n";
						}
						else
						{
							echo "<script>alert('Could not upload the file');</script>";
							echo "<script> document.location='attendance-upload.php';</script>";
							exit;
						}
		
				}
				else
				{
					echo "<script> document.location=attendance-upload.php';</script>";
					exit;
				}
			}
			else
			{
				/*echo "<script> document.location='exportdelivery-file.php?user=".$user."';</script>";
				exit;*/
			}
			
			$today = date('Y-m-d');
															
			//$sqlObj->tablename=$tablename;
			/*if($townname!=''){
			$sqlObj->fieldname='(filename,date)';
			$sqlObj->fieldvalue='"'.$filename.'","'.$today.'"';
			
			echo $qsy= "insert into ".$tablename.$sqlObj->fieldname." values(".$sqlObj->fieldvalue.")";
								
			$CreateClient 	= mysql_query($qsy);
			
			
			}*/
			
			
}
	
	
	
?>
<!DOCTYPE html>
<html>
    <head>
	
	
	<?php /*$emp_id=$_REQUEST['employees']; 
	
	echo $emp_id;
	
	exit();*/ ?>
        <?php include("header-js.php");?>	
		
<!-----hrm-------------->		
<link rel="stylesheet" href="css/style.css" />
<!-- Responsive -->
<link rel="stylesheet" href="css/responsive.css" />
<!--<link rel="stylesheet" href="css/style.css" />-->
<link rel="stylesheet" href="css/styles.css" />
<!-- Responsive -->
<!--<script language="javascript" src="js/css3-mediaqueries.js" type="text/javascript"></script>-->

<script src="js/individualtimelist.js"></script>

<script type="text/javascript">         
     $(document).ready( function() { 
            var cur_year=new Date().getFullYear();
            var obj=document.getElementById("year");         
            for (var i = 2013; i <= 2030; i++)     {                
                opt = document.createElement("option");
                opt.value = i;
                opt.text=i;
                obj.appendChild(opt);
            }
            document.getElementById("year").value = cur_year;
			
			var month1='';
		 	 var cur_mon=new Date().getMonth() + 1;
            var obj=document.getElementById("month");         
            for (var i = 1; i <= 12; i++)     {                
                opt = document.createElement("option");
				if(i<10) i='0'+i;	
				//-------------------------------------//
				if(i==1)month1='January';if(i==2)month1='February';;if(i==3)month1='March';if(i==4)month1='April';if(i==5)month1='May';
if(i==6)month1='Jun';if(i==7)month1='July';;if(i==8)month1='August';if(i==9)month1='September';if(i==10)month1='October';
if(i==11)month1='November';if(i==12)month1='December';
				//---------------------------------------//
                opt.value = i;
                opt.text=month1;
                obj.appendChild(opt);
            }
        document.getElementById("month").value = cur_mon;
        });
		
	$(document).ready( function() { 
            var cur_year=new Date().getFullYear();
            var obj=document.getElementById("year_muster");         
            for (var i = 2013; i <= 2030; i++)     {                
                opt = document.createElement("option");
                opt.value = i;
                opt.text=i;
                obj.appendChild(opt);
            }
            document.getElementById("year_muster").value = cur_year;
			
			var month1='';
		 	 var cur_mon=new Date().getMonth() + 1;
            var obj=document.getElementById("month_muster");         
            for (var i = 1; i <= 12; i++)     {                
                opt = document.createElement("option");
				if(i<10) i='0'+i;	
				//-------------------------------------//
				if(i==1)month1='January';if(i==2)month1='February';;if(i==3)month1='March';if(i==4)month1='April';if(i==5)month1='May';
if(i==6)month1='Jun';if(i==7)month1='July';;if(i==8)month1='August';if(i==9)month1='September';if(i==10)month1='October';
if(i==11)month1='November';if(i==12)month1='December';
				//---------------------------------------//
                opt.value = i;
                opt.text=month1;
                obj.appendChild(opt);
            }
        document.getElementById("month_muster").value = cur_mon;
        });
		
function printDiv(divName) {
	
     var printContents = document.getElementById(divName).innerHTML;
	
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();
	setTimeout(function(){document.body.innerHTML = originalContents;},3000);
     
}


		
    </script>

<!-----hrm-------------->
        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
          <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>

        <![endif]-->
    </head>
	<?php
	include_once("class/class.MySQL.php");
	include_once("class/userdefinedfunctions.php");
	$db	=new MySQL();
	$userfunction	=new userdefinefunctions();
    session_start();

	function firstSunday($DATE)
    {
	// $DATE='2014-04-01';
         $date = date('Y-m',strtotime($DATE));
         $day = trim(strtotime("%e",$DATE));

        for($day; $day <= '7'; $day++){
             $dd = strftime("%A",strtotime($date.'-'.$day));
            if($dd == 'Sunday'){
                return $day;
            }
        }
    }
	
?>
<?php /*?><?php
$mm= date('m');
$yy=date('Y');
$empid=$_REQUEST['employees'];
$desigs = mysql_query("SELECT * FROM employee where e_id='$employees' ");
$desigs = mysql_fetch_array($desigs);
 $branch=$desigs['branchid'];

?>
<input type="hidden" name="month" id="month" value="<?=$mm?>">
<input type="hidden" name="year" id="year" value="<?=$yy?>">
<input type="hidden" name="employees" id="employees" value="<?=$empid?>">
<input type="hidden" name="branch" id="branch" value="<?=$branch?>">

<?php */?>
    <body class="skin-blue" >
 <?php 
 
 include("header.php");?>
                 <!-- Small boxes (Stat box) -->
				 	<?php $useridss=$_SESSION['admin_id']; ?>
<?php /*?> <input type="hidden" name="u_ids" id="u_ids" class="userid" value="<?php echo $useridss;?>"  />   
 
  <input type="hidden" name="user_idss" id="user_idss"  value="<?php echo $_GET['employees'];?>"  />     <?php */?>            

                    <!-- Main row -->
                    <div class="row">
                    
					<div id="wrapper" style="width:1048px;">


<div class="content">

<div class="report-tab">

<div class="report-cell-02">

<!--<label><input type="button" value="Timesheet" data-page="Timesheet_show"  class="btn-tab-01 Timesheet_show" /></label>
<label><input type="button" value="Muster Roll" data-page="Muster_Roll_show"  class="btn-tab-01 Muster_Roll_show" /></label>-->
    
<ul class="payroll-menu" style="margin-bottom:0px !important; ">
	<li data-page="Timesheet_show" class="Timesheet_show" style="padding-bottom: 30px !important;"><translate>Timesheet</translate></li>
</ul>
<?php

if($_SESSION['usertype'] == 'Superadmin' || $_SESSION['branchadmin'] == 'Y')
{	
?>
<!--<ul class="payroll-menu" style="margin-bottom:0px !important; ">
<li data-page="Muster_Roll_show" class="Muster_Roll_show"  style="padding-bottom: 30px !important;"><translate>Muster Roll</translate></li>
</ul>-->
<ul class="payroll-menu" style="margin-bottom:0px !important; ">
<li data-page="Attendance_show" class="Attendance_show" style="padding-bottom: 30px !important;"><translate>Attendance Report</translate></li>
</ul>

<ul class="payroll-menu" style="margin-bottom:0px !important; ">
<li data-page="Attendance_upload" class="Attendance_upload" style="padding-bottom: 30px !important;"><translate>Attendance Upload</translate></li>
</ul>


<?php } ?>
	
	
    
<div class="clear-float"></div>
</div>
<div class="Emp_timesheet" style="display:none">
<div class="report-left">

<h2><translate>Employee Time Sheet</translate></h2>
</div>
<div class="clear-float"></div>

<!-- /report-cell-03 -->

<!--/employee-tab-01-->

<!--/employee-tabcells-->

<div class="clear-float"></div>
</div>

<div class="Muster_roll_Grid" > 

<div class="report-left">

<h2><translate>Attendance Upload</translate></h2>
</div>
<div class="clear-float"></div>

<!-- /report-cell-03 -->
                    <form action="" method="post"  id="frm1" name="frm1" enctype="multipart/form-data">
              <!-- Recruitment ////////////////////////////////////////////////////////////////////// -->
              <fieldset class="step">
              
                <!--<p class="heading01">Reference</p>-->
              <p>
                <label for="Source">Branch Name</label>
                <?php
				
				if($_SESSION['usertype'] == 'Superadmin') {
					$sqlbranch = $db->fetchQuery("select * from branches where branch_id NOT IN (123,128,131)"); 
				}
				else
				{
					$sqlbranch = $db->fetchQuery("select * from branches where branch_id=".$_SESSION['branch_id'].""); 
				}
				?>
                <select name="branchid" id="branchid" onChange="get_time()" >
                  <option value="">-Select-</option>
                  <?php 	foreach($sqlbranch as $list){ ?>
                  <option value="<?=$list['branch_id']?>">
                    <?=$list['branch_name']?>
                  </option>
                  <?php } ?>
                </select>
              </p>
                <p>
                <label for="Date">Attendance</label>
                <input name="import_file" type="file"  id="import_file" />
              </p>
                <div class="clear-float"></div>
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td align="center"  style="padding-left:50px;padding-top:10px;">
					  <input name="save" type="submit" class="color-button3" style="background: #026091; width:120px; height:40px;"  value="Save" />
				   </td>
				  </tr>
				</table>

              
             
              </fieldset>
            </form>
                    
                </div>



</div>
<div class="clear-float"></div>
</div><!-- /content -->


<div class="footer">
<strong>© add-HRM </strong><span class="currentversion"></span><br />
<span><translate>Developed by</translate> <a href="http://www.aadhocc.com" target="_blank"><translate>Aadhocc</translate></a></span></div><!-- /footer -->

</div>
                    </div><!-- /.row (main row) -->
                </section><!-- /.content -->
            </aside><!-- /.right-side -->
        </div><!-- ./wrapper -->
<?php 
include("footer-js.php");
?>
		
		<!--------------scripts for employee list-------------->
<!--<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>-->
<script src="js/common.js"></script>
<script src="js/employee.js"></script>
<script language="javascript" src="js/css3-mediaqueries.js" type="text/javascript"></script>
<script src="js/employee_sg.js"></script>
	<!--------------scripts for employee list-------------->
	
	<script type="text/javascript">
	var uuiid=document.getElementById('user_idss').value;
	var uuiid=document.getElementById('user_idss').value;
	//employeetimesheet(uuiid,1); //alert(4);
	</script>
	
    </body>
</html>