<?php
include($_SERVER['DOCUMENT_ROOT'] . "/attendance/attendance-mobile-api/connection/business_conn.php");
header('content-type:application/json');


$DeviceName = $_GET['DeviceName'];
$PassKey = $_GET['PassKey'];
$UniqueId = $_GET['UniqueId'];
$_SESSION['UniqueId'] = $UniqueId;
$UniqueId = $_SESSION['UniqueId'];


$query = mysqli_query($conn, "SELECT * FROM businesses_account WHERE UniqueId='$UniqueId'");
while ($spec = mysqli_fetch_assoc($query)) {
    $postData[] = $spec;
    $businessname = $spec['BusinessName'];
    $businessid = $spec['Businessid'];
    $number_of_devices_for_attendance = $spec['NumberOfDevicesForAttendance'];
}

$query = mysqli_query($conn, "SELECT COUNT(id) AS TOTAL FROM businesses_devices_for_attendance WHERE Businessid='$businessid'");
$affected_row = mysqli_affected_rows($conn);
if ($affected_row < 1) {
    $number_of_devices_configured = 0;
} else {
    while ($spec = mysqli_fetch_assoc($query)) {
        $number_of_devices_configured = $spec['TOTAL'];
    }
}

$sql = "SELECT * FROM businesses_account WHERE Businessid='$businessid'";
$query = $conn->query($sql);
if ($query->num_rows < 1) {
    $message = 'The UNIQUE INSTITUTION / BUSINESS ID you entered is incorrect.';
} else {
    if ($number_of_devices_configured <  $number_of_devices_for_attendance) {
        $sql1 = "INSERT INTO businesses_devices_for_attendance (BusinessId, pass_key, device_name, date_added) VALUES ('$businessid', '$PassKey', '$DeviceName','" . DATE("Y-m-d") . "')";
        if (mysqli_query($conn, $sql1)) {
            $code =  200;
        } else {
            echo "Error: " . mysqli_error($conn);
        }
    } else {
        if ($number_of_devices_for_attendance == 0) {
            $message = 'You have not configured the number of devices for your Institution / Business that can access this app.';
        } else {

            $sql1 = "SELECT * FROM businesses_devices_for_attendance WHERE pass_key='$PassKey'";
            $query1 = $conn->query($sql1);
            if ($query1->num_rows < 1) {
                $message = 'The PASS KEY you entered is incorrect.';
            } else {
                $code =  200;
            }
        }
    }
}
$resultData = array('status' => true, 'code' => $code, 'message' => $message, 'businessid' => $businessid, 'businessname' => $businessname, 'results' => $postData);

echo json_encode($resultData);
