<?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);
$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"];
                    //     $updatedOn = $row["updated_on"] . ".0";
                    // }
                    $secretKey = $macId;
                    $isValidSignature = hash_equals(
                        hash_hmac('sha256', "$header.$payload", $yourSecretKey),
                        $signature
                    );
                    // $updateTime = date('Y-m-d H:i:s.0');
                    if (!$isValidSignature) {
                        $jsonData = file_get_contents('php://input');
                        // Decode the JSON data into a PHP associative array
                        $data = json_decode($jsonData, true);
                        $query = mysqli_query($conn, "SELECT * FROM attendance_device_users");
                        $details = array();
                        while ($spec = mysqli_fetch_assoc($query)) {
                            // $id = $spec['id'];
                            // $name = $spec['FirstName'] . " " . $spec["LastName"];
                            // $class = $spec['Class'];
                            // $classarm = $spec['ClassArm'];
                            // $studentid = $spec['StudentId'];
                            // $cardnumber = $spec['CardNumber'];
                            // $sex = $spec['Sex'];
                            // $school = $spec['School'];
                            // $details[] = array(
                            //     "id" => $id,
                            //     "cname" => $school_initials,
                            //     "name" => $name,
                            //     "department" => $class,
                            //     "departmentId" => $school,
                            //     "post" => $classarm,
                            //     "phone" => "",
                            //     "picturePath" => "mjkband01.oss-cn-shenzhen.aliyuncs.com/images/c6535f83-7733-4fae-a8fa-682125bb2d62.png?x-oss-process=image/resize,m_lfit,h_500,w_500",
                            //     "jobNumber" => $studentid,
                            //     "sex" => $sex,
                            //     "tenantId" => $id,
                            //     "idCard" => $cardnumber,
                            //     "updateTime" => $updatedOn
                            // );
                            $id = $spec['id'];
                            $name = $spec['name'];
                            $department = $spec['departmentName'];
                            $departmentId = $spec['departmentId'];
                            $post = $spec['post'];
                            $phone = $spec['phone'];
                            $picturePath = $spec["picturePath"];
                            $jobNumber = $spec['jobNumber'];
                            $sex = $spec['sex'];
                            $tenantId = $spec['tenantId'];
                            $idCard = $spec['idCard'];
                            $fingerprint = $spec['fingerPrint'];
                            $fingerprint2 = $spec['fingerPrint2'];
                            $fingerprint3 = $spec['fingerPrint3'];
                            $updateTime = $spec['updateTime'] . ".0";
                            $details[] = array(
                                "id" => $id,
                                "cname" => $school_initials,
                                "name" => $name,
                                "department" => $department,
                                "departmentId" => $departmentId,
                                "post" => $post,
                                "phone" => $phone,
                                "picturePath" => $picturePath,
                                "jobNumber" => $jobNumber,
                                "sex" => $sex,
                                "tenantId" => $tenantId,
                                "idCard" => $idCard,
                                "fingerprint" => $fingerprint,
                                "fingerprint2" =>  $fingerprint2,
                                "fingerprint3" =>  $fingerprint3,
                                "updateTime" => $updateTime
                            );
                            // $remove[] = array(
                            //     "id" => "1370218071475884034",
                            //     "jobNumber" => "huang",
                            //     "tenantId" => "124",
                            //     "updateTime" => $updateTime,
                            //     "fake" => "1"
                            // );
                            // , 'removeList' => $remove

                        }
                        $resultData = array(
                            'code' => 1,
                            'msg' => "success",
                            "data" => ['uuid' => date('Y-m-d H:i:s.0'), 'updateList' => $details]
                        );

                        $sql = ("TRUNCATE attendance_device_users");
                        if (mysqli_query($conn, $sql)) {
                        } else {
                            echo "Error: " . mysqli_error($conn);
                        }
                    }
                }
            } else {
                $resultData = array('code' => 8003, 'error' => "Token is invalid");
            }
        // } else {
        //     $resultData = array('code' => 8001, 'error' => "Invalid Authorization header format");
        // }
    } else {
        $resultData = array('code' => 8002, 'error' => "Authorization header not found");
    }
}
file_put_contents('callback.getUpdateInfo.txt', print_r($resultData, true));
echo json_encode($resultData);
mysqli_close($business_conn);
mysqli_close($conn);