<?php
include($_SERVER['DOCUMENT_ROOT'] . "/API-Others/connection/api-business-conn.php");
include($_SERVER['DOCUMENT_ROOT'] . "/API-Others/connection/api-conn.php");
$timezone = new DateTimeZone('Africa/Accra'); // Replace with your desired timezone
$datetime = new DateTime('now', $timezone);
$timezone = 'Africa/Accra';
date_default_timezone_set($timezone);
$formattedDateTime = $datetime->format('Y-m-d H:i:sP');
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    $timestamp = $formattedDateTime;
    $status = 405;
    $error = "Method Not Allowed";
    $message = "Request method is not valid";
    $resultData = array('timestamp' => $timestamp, 'status' => $status, 'error' => $error, 'message' => $message);
} else {
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $authorizationHeader = $_SERVER['HTTP_AUTHORIZATION'];
        if ($authorizationHeader == 0) {
            $headers = getallheaders();
            $token = $headers['Authorization'];
            list($header, $payload, $signature) = explode('.', $token);
            $decodedHeader = json_decode(base64_decode($header), true);
            $decodedPayload = json_decode(base64_decode($payload), true);
            $query = mysqli_query($business_conn, "SELECT * FROM attendance_device_list WHERE token = '$token'");
            $affectedRow = mysqli_affected_rows($business_conn);
            if ($affectedRow > 0) {
                if (isset($decodedPayload['exp']) && $decodedPayload['exp'] < time()) {
                    $resultData = array('code' => 1, 'msg' => "Token has expired");
                } else {
                    // while ($row = mysqli_fetch_assoc($query)) {
                    //     $businessid = $row["businessid"];
                    //     $macId = $row["macId"];
                    // }
                    $secretKey = $macId;
                    $isValidSignature = hash_equals(
                        hash_hmac('sha256', "$header.$payload", $yourSecretKey),
                        $signature
                    );
                    $updateTime = date('Y-m-d H:i:s');
                    // Retrieve the raw POST data
                    $jsonData = file_get_contents('php://input');
                    // Decode the JSON data into a PHP associative array
                    $data = json_decode($jsonData, true);
                    // Check if decoding was successful
                    if ($data !== null) {
                        // Access the data and perform operations
                        $attendanceTime = $data['attendanceTime'];
                        $corporationName = $data['corporationName'];
                        $cpuId = $data['cpuId'];
                        $departmentName = $data['departmentName'];
                        $deviceName = $data['deviceName'];
                        $jobNumber = $data['jobNumber'];
                        $name = $data['name'];
                        $temperature = $data['temperature'];
                        $base64 = $data['base64'];
                        $checkingDesc = $data['checkingDesc'];
                        if ($departmentName == "Staff") {
                            $entryId = trim(preg_replace("/[^a-zA-Z0-9]+/", "", $jobNumber.DATE("Ymd")));
                            $query = mysqli_query($conn, "SELECT * FROM staff WHERE unique_user_id = '$jobNumber'");
                            $affectedRow = mysqli_affected_rows($conn);
                            if ($affectedRow > 0) {
                                while ($spec = mysqli_fetch_assoc($query)) {
                                    $staffDetails[] =  $spec;
                                    $idd = $spec['unique_user_id'];
                                    $image = $spec['profile_photo'];
                                    $sex = $spec['gender'];
                                    $firstname = $spec['first_name'];
                                    $lastname = $spec['last_name'];
                                    $staffid = $spec['unique_user_id'];
                                    $stafftype = $spec['department'];
                                    $role = $spec['role'];  
                                    $year = DATE("Y");
                                }

                   
                                $query = mysqli_query($conn, "SELECT * FROM attendance_time_set WHERE Department = 'General' ");
                                while ($spec = mysqli_fetch_assoc($query)) {
                                    $arrival_time_from = $spec['ArrivalFrom'];
                                    $arrival_time_to = $spec['ArrivalTo'];
                                    $depature_time_from = $spec['DepatureFrom'];
                                    $depature_time_to = $spec['DepatureTo'];
                                }

                                $statusIndicating = "Present";
                                $date = DATE("Y-m-d");
                                $time = DATE("H:i:s");

                                $query = mysqli_query($conn, "SELECT * FROM staff_attendance WHERE idd = '$idd' AND Date = '" . DATE("Y-m-d") . "'");
                                $affected_row = mysqli_affected_rows($conn);
                                if ($affected_row > 0) {
                                    $clockin_done = "Yes";
                                } else {
                                    $clockin_not_done = "Yes";
                                }

                                if ($clockin_done == "Yes" && $time < $depature_time_from) {
                                    $LogicResponse = 2;
                                } else {
                                    if ($clockin_not_done == "Yes" && $time > $depature_time_from) {
                                        $LogicResponse = 4;
                                    } else {
                                        $query = mysqli_query($conn, "SELECT * FROM staff_attendance WHERE idd = '$idd' AND Date = '" . DATE("Y-m-d") . "'");
                                        $affected_row = mysqli_affected_rows($conn);
                                        if ($affected_row == 1) {
                                            $clockOutTime = $time;
                                            while ($spec = mysqli_fetch_assoc($query)) {
                                                if ($spec["TimeOut"] == "00:00:00") {
                                                    $sql = ("UPDATE staff_attendance SET idd = '$idd', Year = '$year', TimeOut = '$time', DeviceUsedForClockOut = '$deviceName' WHERE idd = '$idd' AND Date = '$date'");
                                                    if (mysqli_query($conn, $sql)) {
                                                        $LogicResponse = 1;
                                                    } else {
                                                        echo "Error: " . mysqli_error($conn);
                                                    }
                                                } else {
                                                    $LogicResponse = 6;
                                                }
                                            }
                                        } else {
                                            if ($time <= $arrival_time_to) {
                                                $statusIndicating = "Present";
                                            } else {
                                                $statusIndicating = "Late";
                                            }
                                            $clockInTime = $time;
                                            $clockOutTime = "";
                                            $sql = ("INSERT INTO staff_attendance (idd, EntryId, Year, StaffId, SignedInBy, StatusIndicating, Temperature, TimeIn, DeviceUsedForClockIn, Date) VALUES ('$idd','$entryId','$year','$staffid','$deviceName', '$statusIndicating','$temperature','$time','$deviceName', '$date')");
                                            if (mysqli_query($conn, $sql)) {
                                                $LogicResponse = 1;
                                            } else {
                                                echo "Error: " . mysqli_error($conn);
                                            }
                                        }
                                    }
                                };
                            }
                        } 
                        
                    

                    } else {
                        // JSON decoding failed
                        $code = http_response_code(400); // Bad Request
                        $statusMessage = "Invalid JSON data";
                        $status = false;
                    }

                    $resultData = array('code' => $code, 'msg' => $statusMessage, 'data' => $status);
                }
            } else {
                $resultData = array('code' => 8003, 'error' => "Token is invalid");
            }
        } else {
            $resultData = array('code' => 8001, 'error' => "Invalid Authorization header format");
        }
    }
}
echo json_encode($resultData);
