<?php
if (isset($_GET['logout'])){session_start(); session_destroy();} //Logout
if (!file_exists(dirname(__FILE__).'/config/config.php')){
    header('location: install.php');
}
require_once 'functions.php';


if (!isset($_SESSION['user'])){

    if (isset($_POST['password'])){
        $db_conn = dbconn();
        $name = $_POST['user'];
        $user = dbw_query_fetch_array($db_conn,"SELECT * FROM USERS WHERE `Name`='$name' and `Enabled`=1");
        if ($user){
            $password = hash("sha256",$user['ID_U'].$_POST['password']);
            if ($user['Password'] == $password){
                $_SESSION['user'] = $user;
                header('location: admin.php');
            }else{
                sendmsg('error','Usuario o contraseña no válidas');
            }
        }else if (dbw_num_rows($db_conn,dbw_query($db_conn,"SELECT `Enabled` FROM USERS WHERE `Name`='$name' AND `Enabled`=0")) == 1 ){
            sendmsg('error','Usuario deshabilitado');
        }else{
            sendmsg('error','Usuario o contraseña no válidas');
        }
    }
    renderPage('login.twig',array());
}else{
    header('location: admin.php');
}