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

// $json = file_get_contents('php://input');
// $_POST = json_decode($json, true);
$json = file_get_contents('php://input');

$get_json = json_decode($json);
if (isset($get_json->username) && isset($get_json->password)) {
    $_POST = json_decode($json, true);
}

$username = isset($_POST["username"]) ? $_POST["username"] : '';
$password = isset($_POST["password"]) ? $_POST["password"] : '';


$query = "SELECT * FROM users WHERE email = '$username' AND password = '$password' or phone = '$username' AND password = '$password' or username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);
$rowCount = mysqli_num_rows($result);
if ($rowCount > 0) {
    function authCode()
    {
        $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 25; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }
    $authCode = authCode();

    while ($row = mysqli_fetch_assoc($result)) {
        $unique_user_id = $row["unique_user_id"];
        $role = $row["role"];
        $sql = ("UPDATE users SET auth_code = '$authCode' WHERE unique_user_id = '$unique_user_id'");
        if (mysqli_query($conn, $sql)) {
            $statusCode = 200;
            $statusMessage = "Signed In Successfully";
        } else {
            $error = "Error: " . mysqli_error($conn);
        }

        $query1 = "SELECT * FROM users WHERE email = '$username' AND password = '$password' or phone = '$username' AND password = '$password' or username = '$username' AND password = '$password'";
        $result1 = mysqli_query($conn, $query1);
        $postData = array();
        while ($row = mysqli_fetch_assoc($result1)) {
            $postData[] = $row;
        }
    }
} else {
    $statusCode = 1062;
    $statusMessage = "Login credentials was not found!";
}


$resultData = array('code' => $statusCode, 'message' => $statusMessage, 'user' => $role, 'token' => $authCode, 'data' => $postData);
echo json_encode($resultData);
