<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
ob_start();
session_start();
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    die();
}
require_once("../../backend/functions.php");
require_once("../../db/connection.php");
$id_map = (int)$_POST['id_map'];
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$remember = (int)$_POST['remember'];
$settings = sml_get_viewer_auth_settings($id_map);
if((int)$settings['viewer_auth_mode']<=0) {
    ob_end_clean();
    echo json_encode(array("status"=>"error"));
    exit;
}
$user = sml_get_user_by_username_password($username,$password);
if($user!==false && (int)$user['active']!==1) {
    sml_clear_viewer_remember_token();
    ob_end_clean();
    echo json_encode(array("status"=>"inactive"));
    exit;
}
if($user!==false && (int)$user['active']===1 && sml_is_valid_user_role($user['role'])) {
    session_regenerate_id(true);
    $_SESSION['viewer_id_user'] = (int)$user['id'];
    if($remember===1) {
        sml_issue_viewer_remember_token((int)$user['id']);
    } else {
        sml_clear_viewer_remember_token();
    }
    $user_public = array("id"=>(int)$user['id'],"username"=>$user['username'],"role"=>$user['role']);
    if(isset($user['email'])) {
        $user_public['email'] = $user['email'];
    }
    $user_public['markers_total'] = 0;
    $user_public['markers_pending'] = 0;
    $query_markers = "SELECT COUNT(*) as total, SUM(CASE WHEN to_validate=1 THEN 1 ELSE 0 END) as pending FROM sml_markers WHERE id_map=? AND id_user=?;";
    if($smt_markers = $mysqli->prepare($query_markers)) {
        $smt_markers->bind_param('ii',$id_map,$user['id']);
        if($smt_markers->execute()) {
            $result_markers = get_result($smt_markers);
            if(count($result_markers)==1) {
                $row_markers = array_shift($result_markers);
                $user_public['markers_total'] = (int)$row_markers['total'];
                $user_public['markers_pending'] = (int)$row_markers['pending'];
            }
        }
    }
    ob_end_clean();
    echo json_encode(array("status"=>"ok","user"=>$user_public));
    exit;
}
sml_clear_viewer_remember_token();
ob_end_clean();
echo json_encode(array("status"=>"error"));
