<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
ob_start();
session_start();
if($_SESSION['sml_si_l']!=session_id()) {
    die();
}
require_once("../functions.php");
require_once("../../db/connection.php");
require_once("../../config/config.inc.php");
$action = $_POST['action'] ?? 'login';
$key_enc = PASSWORDS_ENCRYPT_KEY;
$sml_users_has_email = false;
$result_email_column = $mysqli->query("SHOW COLUMNS FROM sml_users LIKE 'email';");
if($result_email_column && $result_email_column->num_rows>0) {
    $sml_users_has_email = true;
}

function sml_backend_login_clear_cookies() {
    $cookieExpiration = time() - 3600;
    setcookie('sml_login', '', $cookieExpiration, "/");
    setcookie('sml_username', '', $cookieExpiration, "/");
    setcookie('sml_password', '', $cookieExpiration, "/");
    unset($_COOKIE['sml_autologin']);
    unset($_COOKIE['sml_username']);
    unset($_COOKIE['sml_password']);
}

function sml_backend_login_complete($row, $username, $password, $remember_me) {
    $_SESSION['id_user'] = $row['id'];
    unset($_SESSION['lang']);
    unset($_SESSION['sml_pending_email_user']);
    unset($_SESSION['sml_pending_email_username']);
    unset($_SESSION['sml_pending_email_password']);
    unset($_SESSION['sml_pending_email_remember']);
    if($remember_me==1) {
        $cookieExpiration = time() + (30 * 24 * 60 * 60);
        setcookie("sml_login", 1, $cookieExpiration, "/");
        setcookie("sml_username", encrypt_decrypt('encrypt',$username,'sml'), $cookieExpiration, "/");
        setcookie("sml_password", encrypt_decrypt('encrypt',$password,'sml'), $cookieExpiration, "/");
    } else {
        sml_backend_login_clear_cookies();
    }
}

if($action==='save_email') {
    $email = trim(strip_tags($_POST['email']));
    if(!$sml_users_has_email || empty($_SESSION['sml_pending_email_user']) || empty($email) || !filter_var($email,FILTER_VALIDATE_EMAIL) || strlen($email)>191 || sml_email_exists($email)) {
        ob_end_clean();
        echo json_encode(array("status"=>"error"));
        exit;
    }
    $id_user_pending = (int)$_SESSION['sml_pending_email_user'];
    $query = "SELECT * FROM sml_users WHERE id=? LIMIT 1;";
    if($smt = $mysqli->prepare($query)) {
        $smt->bind_param('i',$id_user_pending);
        $result = $smt->execute();
        if($result) {
            $result = get_result($smt);
            if(count($result)==1) {
                $row = array_shift($result);
                if($row['active'] && sml_is_backend_user_role($row['role']) && empty($row['email'])) {
                    $query_u = "UPDATE sml_users SET email=? WHERE id=?;";
                    if($smt_u = $mysqli->prepare($query_u)) {
                        $smt_u->bind_param('si',$email,$id_user_pending);
                        if($smt_u->execute()) {
                            $row['email'] = $email;
                            sml_backend_login_complete($row,$_SESSION['sml_pending_email_username'],$_SESSION['sml_pending_email_password'],(int)$_SESSION['sml_pending_email_remember']);
                            ob_end_clean();
                            echo json_encode(array("status"=>"ok"));
                            exit;
                        }
                    }
                }
            }
        }
    }
    ob_end_clean();
    echo json_encode(array("status"=>"error"));
    exit;
}

$username = strip_tags($_POST['username_sml']);
$password = strip_tags($_POST['password_sml']);
$remember_me = (int)$_POST['remember_sml'];
$autologin = (int)$_POST['autologin'];
$query = $sml_users_has_email ? "SELECT * FROM sml_users WHERE (username=? OR email=?) AND password=AES_ENCRYPT(?, ?) LIMIT 1;" : "SELECT * FROM sml_users WHERE username=? AND password=AES_ENCRYPT(?, ?) LIMIT 1;";
if($smt = $mysqli->prepare($query)) {
    if($sml_users_has_email) {
        $smt->bind_param('ssss',$username,$username,$password,$key_enc);
    } else {
        $smt->bind_param('sss',$username,$password,$key_enc);
    }
    $result = $smt->execute();
    if($result) {
        $result = get_result($smt);
        if(count($result)==1) {
            $row = array_shift($result);
            if(!sml_is_backend_user_role($row['role'])) {
                sml_backend_login_clear_cookies();
                ob_end_clean();
                echo json_encode(array("status"=>"blocked"));
                exit;
            }
            if($row['active']) {
                if($sml_users_has_email && empty($row['email'])) {
                    $_SESSION['sml_pending_email_user'] = (int)$row['id'];
                    $_SESSION['sml_pending_email_username'] = $username;
                    $_SESSION['sml_pending_email_password'] = $password;
                    $_SESSION['sml_pending_email_remember'] = $remember_me;
                    sml_backend_login_clear_cookies();
                    ob_end_clean();
                    echo json_encode(array("status"=>"missing_email"));
                    exit;
                }
                sml_backend_login_complete($row,$username,$password,$remember_me);
                ob_end_clean();
                echo json_encode(array("status"=>"ok"));
                exit;
            } else {
                sml_backend_login_clear_cookies();
                ob_end_clean();
                echo json_encode(array("status"=>"blocked"));
                exit;
            }
        } else {
            sml_backend_login_clear_cookies();
            ob_end_clean();
            echo json_encode(array("status"=>"incorrect"));
            exit;
        }
    } else {
        ob_end_clean();
        echo json_encode(array("status"=>"error"));
        exit;
    }
} else {
    ob_end_clean();
    echo json_encode(array("status"=>"error"));
    exit;
}
