<?php
session_start();
header('content-type:application/json');
header("Access-Control-Allow-Origin: *");
$timezone = new DateTimeZone('Africa/Accra');
$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 {
    // $servername = "localhost";
    // $username = "schoolro_maker";
    // $password = "JesusChristisLord";
    // $dbname = "schoolro_schoolrobot_schools_account";
    // $school_conn = mysqli_connect($servername, $username, $password, $dbname) or die('Could not connect the database : Username or password incorrect');
    $macId = $_GET["macId"];
    try {
        $query = mysqli_query($school_conn, "SELECT * FROM attendance_device_list WHERE macId = '$macId'");
        $affectedRow = mysqli_affected_rows($school_conn);
        if ($affectedRow > 0) {
            while ($row = mysqli_fetch_assoc($query)) {
                $status = $row["status"];
                $schoolid = $row['schoolid'];
                $schoolname = $row['School_Initials'];
            }
            if ($status == 0) {
                $resultData = array('code' => 2005, 'msg' => "MACID is not actived. Please contact admin.");
            } else {
                $date = DATE("Y-m-d H:i:s");
                $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
                $encodedHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
                $payload = json_encode([
                    "userName" => $macId,
                    "type" => 0,
                    "exp" => 1905326548 + 3600,
                    // time() + (60 * 60),
                    "userId" => $schoolid,
                    "mac_id" => $macId
                ]);
                $encodedPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
                $secretKey = $macId;
                $signature = hash_hmac('sha256', "$encodedHeader.$encodedPayload", $secretKey, true);
                $encodedSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
                $jwt = "$encodedHeader.$encodedPayload.$encodedSignature";
                $sql = ("UPDATE attendance_device_list SET token = '$jwt' WHERE macId = '$macId'");
                if (mysqli_query($school_conn, $sql)) {
                } else {
                    echo "Error: " . mysqli_error($school_conn);
                }
                $resultData = array('code' => 1, 'msg' => "success", 'data' => $jwt);
            }
        } else {
            $resultData = array('code' => 2006, 'msg' => "MACID Doesn't exist");
        }
    } catch (Exception $e) {
        $resultData = array('code' => 1005, 'msg' => $e->getMessage());
    }
}
file_put_contents('callback.richard.txt', print_r($macId, true));
echo json_encode($resultData);
