<?php 
	session_start();

    $notif = "";
    $border_type = "";
    if(isset($_SESSION['timein'])){
        $notif = "Swal.fire({ title: 'Clocked In!', text: '" . addslashes($_SESSION['timein']) . "', icon: 'success', timer: 1500, timerProgressBar: true, showConfirmButton: false });";
        $border_type = "in";
        unset($_SESSION['timein']);
    }
    if(isset($_SESSION['timeout'])){
        $notif = "Swal.fire({ title: 'Clocked Out!', text: '" . addslashes($_SESSION['timeout']) . "', icon: 'success', iconColor: '#ef4444', timer: 1500, timerProgressBar: true, showConfirmButton: false });";
        $border_type = "out";
        unset($_SESSION['timeout']);
    }
    if(isset($_SESSION['warne'])){
        $notif = "Swal.fire({ title: 'Duplicate Scan!', text: '" . addslashes($_SESSION['warne']) . "', icon: 'warning', timer: 1500, timerProgressBar: true, showConfirmButton: false });";
        unset($_SESSION['warne']);
    }
    if(isset($_SESSION['warn'])){
        $notif = "Swal.fire({ title: 'Error', text: '" . addslashes($_SESSION['warn']) . "', icon: 'error', timer: 1500, timerProgressBar: true, showConfirmButton: false });";
        unset($_SESSION['warn']);
    }

    $conn = new mysqli("localhost", "root", "", "qrattendance");
    $total_in = 0; $total_out = 0; $recent_scans = [];
    if(!$conn->connect_error){
        $r = $conn->query("SELECT COUNT(*) as cnt FROM qrattendance WHERE CAST(LOGDATE AS DATE)=CAST(CURDATE() AS DATE) AND status='I'");
        if($r) $total_in = $r->fetch_assoc()['cnt'];
        $r2 = $conn->query("SELECT COUNT(*) as cnt FROM qrattendance WHERE CAST(LOGDATE AS DATE)=CAST(CURDATE() AS DATE) AND status='O'");
        if($r2) $total_out = $r2->fetch_assoc()['cnt'];
        $r3 = $conn->query("SELECT EMPID, ORIGIN, STATUS FROM qrattendance ORDER BY ID DESC LIMIT 12");
        if($r3) while($row = $r3->fetch_assoc()) $recent_scans[] = $row;
    }

?>
<script>
			function startTime() 
				{
	                var now = new Date();
                    var ph = new Date(now.toLocaleString("en-US", { timeZone: "Asia/Manila" }));
                    var h = ph.getHours(), m = ph.getMinutes(), s = ph.getSeconds();
                    var ampm = h >= 12 ? 'PM' : 'AM';
                    h = h % 12; if(h == 0) h = 12;
                    document.getElementById('live-clock').textContent = (h<10?'0'+h:h)+':'+(m<10?'0'+m:m)+':'+(s<10?'0'+s:s)+' '+ampm;
					document.getElementById('l-c').textContent = (h<10?'0'+h:h)+':'+(m<10?'0'+m:m)+':'+(s<10?'0'+s:s)+' '+ampm;
                    var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
                    var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
                    document.getElementById('live-date').textContent = days[ph.getDay()]+', '+months[ph.getMonth()]+' '+ph.getDate()+', '+ph.getFullYear();
                    document.getElementById('ph-date-long').textContent = days[ph.getDay()]+', '+months[ph.getMonth()]+' '+ph.getDate();
                    var rawH = ph.getHours();
                    var greetText = rawH < 6 ? "Good night! 🌙" : rawH < 12 ? "Good morning! 🌅" : rawH < 17 ? "Good afternoon! ☀️" : "Good evening! 🌇";
                    var greetSub = rawH < 6 ? "Working late? Take care!" : rawH < 12 ? "Have a great day at work!" : rawH < 17 ? "Keep up the great work!" : "Thanks for your hard work!";
                    document.getElementById('greeting-text').textContent = greetText;
                    document.getElementById('greeting-sub').textContent = greetSub;
					setTimeout(startTime, 1000);
				};



        // Weather with auto geolocation
        function getWeatherIcon(wcode){
            if(wcode <= 1) return {icon:'☀️', desc:'Clear sky'};
            if(wcode <= 3) return {icon:'⛅', desc:'Partly cloudy'};
            if(wcode <= 48) return {icon:'🌫️', desc:'Foggy'};
            if(wcode <= 67) return {icon:'🌧️', desc:'Rainy'};
            if(wcode <= 77) return {icon:'🌨️', desc:'Snowy'};
            if(wcode <= 82) return {icon:'🌦️', desc:'Rain showers'};
            return {icon:'⛈️', desc:'Thunderstorm'};
        }

        function fetchWeather(lat, lon, locationName) {
            document.getElementById('weather-location').textContent = '📍 ' + locationName;
			document.getElementById('w-l').textContent = '' + locationName;
            fetch('https://api.open-meteo.com/v1/forecast?latitude='+lat+'&longitude='+lon+'&current_weather=true&hourly=relativehumidity_2m,apparent_temperature,windspeed_10m&timezone=Asia%2FManila')
                .then(r => r.json())
                .then(data => {
                    var cw = data.current_weather;
                    var temp = Math.round(cw.temperature);
                    var wind = Math.round(cw.windspeed);
                    var w = getWeatherIcon(cw.weathercode);
                    document.getElementById('weather-icon').textContent = w.icon;
                    document.getElementById('weather-temp').textContent = temp + '°C';
                    document.getElementById('weather-desc').textContent = w.desc;
                    document.getElementById('weather-wind').textContent = wind + ' km/h';
                    var ph = new Date(new Date().toLocaleString("en-US",{timeZone:"Asia/Manila"}));
                    var hr = ph.getHours();
                    if(data.hourly){
                        var hum = data.hourly.relativehumidity_2m ? data.hourly.relativehumidity_2m[hr] : '--';
                        var feels = data.hourly.apparent_temperature ? Math.round(data.hourly.apparent_temperature[hr]) : '--';
                        document.getElementById('weather-humidity').textContent = hum + '%';
                        document.getElementById('weather-feels').textContent = feels + '°C';
                    }
                })
                .catch(function(){ document.getElementById('weather-desc').textContent = 'Unavailable'; });
        }

        function reverseGeocode(lat, lon, callback) {
            fetch('https://nominatim.openstreetmap.org/reverse?lat='+lat+'&lon='+lon+'&format=json')
                .then(r => r.json())
                .then(data => {
                    var city = data.address.city || data.address.town || data.address.municipality || data.address.suburb || 'Your Location';
                    callback(city);
                })
                .catch(() => callback('Your Location'));
        }

        // Try to get device location
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(
                function(pos){
                    var lat = pos.coords.latitude;
                    var lon = pos.coords.longitude;
                    reverseGeocode(lat, lon, function(city){
                        fetchWeather(lat, lon, city + ', PH');
                    });
                },
                function(err){
                    // If denied, fallback to Las Piñas / San Pedro area
                    document.getElementById('weather-location').textContent = '📍 Las Piñas, PH';
					document.getElementById('w-l').textContent = '' + locationName;
                    fetchWeather(14.4500, 120.9833, 'Las Piñas, PH');
                }
            );
        } else {
            // No geolocation support fallback
            document.getElementById('weather-location').textContent = '📍 Las Piñas, PH';
			document.getElementById('w-l').textContent = '' + locationName;
            fetchWeather(14.4500, 120.9833, 'Las Piñas, PH');
        }




</script>

<html>


    <head>
	  <meta charset="utf-8">
	  <meta http-equiv="X-UA-Compatible" content="IE=edge">
	  <title>Licaland QR Code</title>

	  			<meta name="viewport" content="width=device-width, initial-scale=1">
				<script type="text/javascript" src="js/instascan.min.js"></script>
				<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr" crossorigin="anonymous">
				<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js" integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q" crossorigin="anonymous"></script>

				<style>

				    #divvideo{ box-shadow: 0px 0px 1px 1px rgba(0, 0, 0, 0.1); }

                    /* CARDS */
                    .panel-card {
                        background: #fff;
                        border-radius: 12px;
                        border: 1px solid #e5e7eb;
                        padding: 12px;
                        box-shadow: 0 2px 6px rgba(0,0,0,0.05);
                    }
                    /* GREETING */
                    .greeting { font-size: 19px; font-weight: 700; color: #374151; margin-bottom: 3px; }
                    .greeting-sub { font-size: 15px; color: #9ca3af; margin-bottom: 8px; }
                    .info-row { display: flex; align-items: center; gap: 5px; font-size: 16px; color: #6b7280; margin-bottom: 4px; }
                    /* STATS */
                    .stat-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
                    .stat-label { font-size: 16px; color: #6b7280; }
                    .stat-badge { font-size: 15px; font-weight: 700; padding: 1px 1px; border-radius: 20px; }
                    .badge-green { background: #dcfce7; color: #166534; }
					/* Weather */
					.weather-temp { font-size: 36px; font-weight: 300; color: #1a1a2e; text-align: center; line-height: 1; margin: 6px 0 2px; }
					.weather-icon { font-size: 28px; text-align: center; margin-bottom: 2px; }
					.weather-desc { font-size: 15px; color: #9ca3af; text-align: center; margin-bottom: 10px; }
					.weather-row { display: flex; justify-content: space-between; font-size: 15px; color: #6b7280; margin-bottom: 4px; }
					/* Others */
					.company-title { text-align: center; font-size: 13px; font-weight: 600; color: #6b7280; letter-spacing: 2px; text-transform: uppercase; margin-bottom: 4px; }
					.big-clock { text-align: center; font-size: 48px; font-weight: 300; color: #1a1a2e; letter-spacing: 5px; line-height: 1; margin: 2px 0; }
					.big-date  { text-align: center; font-size: 13px; color: #9ca3af; margin-bottom: 14px; letter-spacing: 1px; }

                    /* Recent scans */
            .scan-item { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
            .avatar { width: 28px; height: 28px; border-radius: 50%; background: #dbeafe; display: flex; align-items: center; justify-content: center; font-size: 9px; font-weight: 600; color: #1e40af; flex-shrink: 0; }
            .scan-name { font-size: 12px; font-weight: 500; color: #374151; }
            .scan-time { font-size: 10px; color: #9ca3af; }
            .scan-status { font-size: 13px; font-weight: 600; padding: 2px 10px; border-radius: 5px; margin-left: auto; flex-shrink: 0; }



				</style>
    </head>



    <body style="background:#F5F5DC" onload="startTime();">
        

				<nav class="navbar bg-body-tertiary">
        			<div class="container">
            			<a class="navbar-brand" href="#">
            			<img src="database/logo.ico" alt="Bootstrap" width="30" height="24">
                		LICALAND QR ATTENDANCE
            			</a>
        			</div>
        			<ul class="nav navbar-nav">
			            <!--<li class="active"><a href="exportui.php"><span class="glyphicon glyphicon-time"></span> Export</a></li>-->
			            <!--<li><a href="attendance.php"><span class="glyphicon glyphicon-cog"></span> Attendance </a></li>-->
                        <!--<li><a href="qr.php"><span class="glyphicon glyphicon-qrcode"></span> Generate QR </a></li>-->
                        <!--<li><a href="exportui.php"><span class="glyphicon glyphicon-export"></span> Export </a></li>-->
			            <!--<li><a href="export.php"><span class="glyphicon glyphicon-align-justify"></span> Reports</a></li>-->
			</ul>
    			</nav>

		<br>

       <div class="container">
			<div class="row">			
                
                <div class="col-md-3">
                    <div class="side-panel">

                            <!-- Greeting -->
                            <div class="panel-card">
                                <div class="greeting" id="greeting-text">Good morning! 🌅</div>
                                <div class="greeting-sub" id="greeting-sub">Have a great day at work!</div>
                                <hr class="divider"><b>
									<div class="stat-row">
										<span class="stat-label">Clocked In</span>
										<span class="stat-badge badge-green"><?php echo $total_in; ?></span>
                					</div>
									<div class="stat-row">
										<span class="stat-label">Clocked Out</span>
										<span class="stat-badge badge-blue"><?php echo $total_out; ?></span>
									</div>
									<div class="stat-row">
										<span class="stat-label">Total Scans</span>
										<span class="stat-badge" style="background:#f3f4f6;color:#374151;"><?php echo $total_in + $total_out; ?></span>
									</div>
                                <div style="display:none;" class="info-row">📅 <span id="ph-date-long">April 29, 2026</span></div>
                                <div style="display:none;" class="info-row">📍 <span id="w-l">Manila, PH</span></div>
                                <div style="display:none;" class="info-row">🕐 <span id="live-clock">8AM – 5PM</span></div></b>
                            </div>
							<br>
							<!-- Weather - auto location -->
							<div class="panel-card">
								<div class="panel-title">Current Weather</div>
								<div class="weather-location" id="weather-location">📍 Detecting location...</div>
								<div class="weather-icon" id="weather-icon">⛅</div>
								<div class="weather-temp" id="weather-temp">--°C</div>
								<div class="weather-desc" id="weather-desc">Loading...</div>
								<hr class="divider">
								<div class="weather-row"><span>Humidity</span><span id="weather-humidity">--%</span></div>
								<div class="weather-row"><span>Wind</span><span id="weather-wind">-- km/h</span></div>
								<div class="weather-row"><span>Feels like</span><span id="weather-feels">--°C</span></div>
							</div>

                    </div>

                </div>

				<div class="col-md-6">
                    

                    <div class="panel-card" id="divvideo">
                        <video id="preview" width="100%" style="border-radius:10px;"></video>
                    </div>
					<div class="panel-card">
						<div class="company-title">LICALAND QR ATTENDANCE</div>
						<div class="big-clock" id="l-c">00:00:00</div>
            			<div class="big-date" id="live-date">Loading...</div>
					</div>
						

                    <form action="insert.php" method="post" class="form-horizontal" style="border-radius: 5px;padding:10px;background:#fff;" id="divvideo" onsubmit="return false">
                        <i class="glyphicon glyphicon-qrcode"></i> <label id="txt"></label>
						
                        <input type="hidden" name="empid" id="text" placeholder="scan qrcode" class="form-control" autofocus>
                        <input type="hidden" name="empname" id="enel" placeholder="scan qrcode" class="form-control">
                        <input type="hidden" name="klak" id="enem" placeholder="scan qrcode" class="form-control">
                        <input type="hidden" name="lats" id="lats_id" placeholder="scan qrcode" class="form-control">
                        <input type="hidden" name="longs" id="longs_id" placeholder="scan qrcode" class="form-control">
                    </form>

                    


					<br>
				<?php
					if(isset($_SESSION['emp'])){
						echo "
						  <div class='alert alert-success alert-dismissible' style='background:green;color:#fff'>
							".$_SESSION['emp']."
						  </div>
						";
						unset($_SESSION['emp']);
					  }
					if(isset($_SESSION['error'])){
					  echo "
						<div class='alert alert-danger alert-dismissible' style='background:red;color:#fff'>
						  <h4><i class='icon fa fa-warning'></i> Error!</h4>
						  ".$_SESSION['error']."
						</div>
					  ";
					  unset($_SESSION['error']);
					}
					if(isset($_SESSION['success'])){
					  echo "
						<div class='alert alert-success alert-dismissible' style='background:blue;color:#fff'>
						  <h4><i class='icon fa fa-check'></i> Welcome!</h4>
						  ".$_SESSION['success']."
						</div>
					  ";
					  unset($_SESSION['success']);
					}
					if(isset($_SESSION['dup'])){
						echo "
						  <div class='alert alert-success alert-dismissible' style='background:orange;color:#fff'>
							<h4><i class='icon fa fa-check'></i> Notice:</h4>
							".$_SESSION['dup']."
						  </div>
						";
						unset($_SESSION['dup']);
					  }
					  if(isset($_SESSION['inv'])){
						echo "
						  <div class='alert alert-success alert-dismissible' style='background:orange;color:#fff'>
							<h4><i class='icon fa fa-check'></i> Invalid QR: </h4>
							".$_SESSION['inv']."
						  </div>
						";
						unset($_SESSION['inv']);
					  }
					  
				  ?>
				</div>
				<div class="col-md-3">
					<div class="panel-card">
                		<div class="panel-title">Recent Scans</div> 
                        <hr class="divider">
                			<?php if(empty($recent_scans)): ?>
                    			<div style="font-size:11px;color:#9ca3af;text-align:center;padding:10px 0;">No scans yet today</div>	
                			<?php else: ?>
                    <?php foreach($recent_scans as $scan):
                        $fname = $scan['ORIGIN'] ?? '';
                        $is_in = $scan['STATUS'];
                        $time_display = $is_in ? $scan['STATUS'] : $scan['STATUS'];
                    ?>
                    <div class="scan-item">
                        <div style="flex:1;min-width:0;">
                            <div class="scan-status"><?php echo $fname; ?></div> 
                        </div>
                        <span class="scan-status" style="background:<?php if($is_in == "I") {  echo '#dcfce7'; } else { echo '#fee2e2'; } ?>;color:<?php echo $is_in ? '#166534' : '#991b1b'; ?>">
                            <?php if($is_in == "I") {  echo 'CLOCK -IN'; } else { echo 'CLOCK OUT'; } ?>
                        </span>
                    </div>
                    <?php endforeach; ?>
                    <hr class="divider">
                <?php endif; ?>
            </div>
				</div>

			</div>

        </div>
		<script>
			function Export()
			{
				var conf = confirm("Please confirm if you wish to proceed in exporting the attendance in to Excel File");
				if(conf == true)
				{
					window.open("export.php",'_blank');
				}
			}
		</script>				
        <script>
           let scanner = new Instascan.Scanner({ video: document.getElementById('preview')});
           Instascan.Camera.getCameras().then(function(cameras){
               if(cameras.length > 0 ){
                   scanner.start(cameras[0]);
               } else{
                   alert('No cameras found');
               }

           }).catch(function(e) {
               console.error(e);
           });
           scanner.addListener('scan',function(c){
			   var a = c.split(":")
			   var emp = "Employee name:";
			   document.getElementById('text').value=a[0];
			   document.getElementById('enel').value=a[1];
			   document.getElementById('enem').value=a[2];
               document.forms[0].submit();  
           }); 
		   
        </script>
		<script type="text/javascript">
		var timestamp = '<?=time();?>';
		function updateTime(){
		  $('#time').html(Date(timestamp));
		  timestamp++;
		}
		$(function(){
		  setInterval(updateTime, 1000);
		});
		</script>
		<script src="plugins/jquery/jquery.min.js"></script>
		<script src="plugins/bootstrap/js/bootstrap.min.js"></script>
		<script src="plugins/datatables/jquery.dataTables.min.js"></script>
		<script src="plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
		<script src="plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
		<script src="plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>

		<script>
		  $(function () {
			$("#example1").DataTable({
			  "responsive": true,
			  "autoWidth": false,
			  "order": [[0,"desc"]]
			});
			$('#example2').DataTable({
			  "paging": true,
			  "lengthChange": false,
			  "searching": false,
			  "ordering": true,
			  "info": true,
			  "autoWidth": false,
			  "responsive": true,
			});
		  });
		</script>
		
    </body>
</html>