<?php
session_start();
header('Access-Control-Allow-Origin: *');
$vars = json_decode(file_get_contents("php://input"));
if (!isset($vars->email)) {
    die(json_encode(array("status" => false, "message" => "Email Not Found")));
}
if (!isset($vars->password)) {
    die(json_encode(array("status" => false, "message" => "Password Not Found")));
}
if (empty($vars->email)) {
    die(json_encode(array("status" => false, "message" => "Email is invalid")));
}
include "konnection.php";
include "func.php";
// $site = getSite();
// $email = filter_var($vars->email, FILTER_SANITIZE_STRING);
// $email = mysqli_real_escape_string($conn, $email);
// $pass = filter_var($vars->password, FILTER_SANITIZE_STRING);
// $pass = mysqli_real_escape_string($conn, $pass);
// $hash = substr(sha1(md5($pass)), 3, 10);
// $check = mysqli_query($conn, "SELECT * FROM users WHERE (email = '$email' OR phone = '$email') AND (password = '$pass' OR password='$hash')");
// if (mysqli_num_rows($check) == 1) {
//     $r = mysqli_fetch_array($check);
//     $hasValidCredentials = true;
//     if ($hasValidCredentials) {
//         $_SESSION["user"] = $r["email"];
//         echo json_encode(
//             array("status" => true, "message" => "Success")
//         );
//     }
// } else
//     echo json_encode(
//         array("status" => false, "message" => "Incorrect")
//     );
$site = getSite();
$email = filter_var($vars->email, FILTER_SANITIZE_STRING);
$email = mysqli_real_escape_string($conn, $email);
$pass = filter_var($vars->password, FILTER_SANITIZE_STRING);
$pass = mysqli_real_escape_string($conn, $pass);
$hashPass = getPass($email);
if ($hashPass) {
    $verifyPass = password_verify($pass, $hashPass);
    if ($verifyPass) {
        $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? OR phone = ?");
        $stmt->bind_param("ss", $email, $email);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows == 1) {
            $r = $result->fetch_array();
            $_SESSION["user"] = $r["email"];
            echo json_encode(
                array("status" => true, "message" => "Success")
            );
        } else {
            echo json_encode(
                array("status" => false, "message" => "Incorrect Logins")
            );
        }
        $stmt->close();
    } else {
        echo json_encode(
            array("status" => false, "message" => "Incorrect Logins")
        );
    }
} else {
    echo json_encode(
        array("status" => false, "message" => "Incorrect Logins")
    );
}
