<?php
include($_SERVER['DOCUMENT_ROOT'] . "/CONNECTION/api-school-conn.php");
include($_SERVER['DOCUMENT_ROOT'] . "/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($school_conn, "SELECT * FROM attendance_device_list WHERE token = '$token'");
            $affectedRow = mysqli_affected_rows($school_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)) {
                    //     $schoolid = $row["schoolid"];
                    //     $macId = $row["macId"];
                    // }
                    $secretKey = $macId;
                    $isValidSignature = hash_equals(
                        hash_hmac('sha256', "$header.$payload", $yourSecretKey),
                        $signature
                    );
                    $updateTime = date('Y-m-d H:i:s');
                    if (!$isValidSignature) {
                        // 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
                            $type = $data['type'];
                            $name = $data['name'];
                            $sex = $data['sex'];
                            $jobNumber = $data['jobNumber'];
                            $post = $data['post'];
                            $departmentName = $data['departmentName'];
                            $tenantId = $data['tenantId'];
                            $idCard = $data['idCard'];
                            $phone = $data['phone'];
                            $isAdmin = $data['isAdmin'];
                            $picturePath = $data["picBase64"];
                            $fingerprint = $data['fingerprint'];
                            $fingerprint2 = $data['fingerprint2'];
                            $fingerprint3 = $data['fingerprint3'];
                            if ($type == "add") {
                                $sql = ("INSERT INTO attendance_device_users (cname, name, sex, jobNumber, post, departmentName, tenantId, idCard, phone, isAdmin, picturePath, fingerPrint, fingerPrint2, fingerPrint3, updateTime) VALUES ('$type','$name', '$sex', '$jobNumber', '$post', '$departmentName', '$tenantId', '$idCard', '$phone', '$isAdmin', '$picturePath', '$fingerprint', '$fingerprint2', '$fingerprint3','" . date('Y-m-d H:i:s') . "')");
                                if (mysqli_query($conn, $sql)) {
                                    $code = http_response_code(200);
                                    $statusMessage = "Saved Successfully";
                                    $status = true;
                                } else {
                                    $error = "Error: " . mysqli_error($conn);
                                }

                                $sql = ("UPDATE attendance_device_list SET updated_on = '" . date('Y-m-d H:i:s') . "' WHERE schoolid = '$schoolid' AND macId = '$macId'");
                                if (mysqli_query($school_conn, $sql)) {
                                } else {
                                }
                            } else if ($type == "del") {
                                $sql = ("DELETE FROM attendance_device_users WHERE jobNumber = '$jobNumber'");
                                if (mysqli_query($conn, $sql)) {
                                } else {
                                    echo "Error: " . mysqli_error($conn);
                                }

                            }
                        } else {
                            $code = http_response_code(400);
                            $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");
        }
    } else {
        $resultData = array('code' => 8002, 'error' => "Authorization header not found");
    }
}
// file_put_contents('callback.richard.json', print_r($jsonData, true));
echo json_encode($resultData);
mysqli_close($school_conn);
mysqli_close($conn);
