<?php
include("epush_db.php");
// header('Content-Type: application/json');

// function biometric(){ 
while (true) {
    global $db;


    $last_id = $db->getVal("select last_id from aa_count "); 
    $nextid = $last_id+1;

    // $getrecords = $db->getRow("select * from DeviceLogs_Processed order by DeviceLogId desc limit 1 ");
    $getrecords = $db->getRow("select * from DeviceLogs_Processed where DeviceLogId=$nextid");

if(count($getrecords)>1){
    $updary = array("last_id" => $getrecords['DeviceLogId']);

    $devicedetail = $db->getRow("select * from biometric_device where device_id=$getrecords[DeviceId] ");

    // print_r($devicedetail);

    $logdate = $getrecords['LogDate'];

    $date = date('Y-m-d',strtotime($logdate));

    $checkpreviousrecord = $db->getRow("select * from DeviceLogs_Processed where DeviceId='$getrecords[DeviceId]' and UserId='$getrecords[UserId]' and LogDate like '$date%' and DeviceLogId<$getrecords[DeviceLogId] ");

    if(count($checkpreviousrecord)>1){
        $previoustime = $checkpreviousrecord['LogDate'];
        
        $datetime_1 = $checkpreviousrecord['LogDate']; 
        $datetime_2 = $logdate; 
         
        $start_datetime = new DateTime($datetime_1); 
        $diff = $start_datetime->diff(new DateTime($datetime_2)); 

        $total_minutes = ($diff->days * 24 * 60); 
        $total_minutes += ($diff->h * 60); 
        $total_minutes += $diff->i; 
        
        $difference = $total_minutes*60;
        
        $duration = $devicedetail['duration']*60*60;
        
        if($difference > $duration){
            $type = "OUT";
        } else {
            $type = "IN";
        }

    } else {
        $type = "IN";
    }

    $timestamp = strtotime($getrecords['LogDate']);

    // From URL to get webpage contents.
    $url = "$devicedetail[school_url]/assignmentApi/epush/attendance.php?userid=$getrecords[UserId]&type=$type&newtimestamp=$timestamp";

    // Initialize a CURL session.
    $ch = curl_init();

    // Return Page contents.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //grab URL and pass it to the variable.
    curl_setopt($ch, CURLOPT_URL, $url);

    $result = curl_exec($ch);

    echo $result;

    $db->updateAry("aa_count", $updary, "where 1");



}
sleep(1);
// echo "<br>";

// assignmentApi
}

// biometric();
?>
