<?php
session_start();
include_once('db_config.php');

$_SESSION["user"] = $User = isset($_POST['fuser']) ? $_POST["fuser"]  : ""; 
$_SESSION["passwd"] = $Passwd = isset($_POST['fname']) ? $_POST['fname'] : "";
$Remember = isset($_POST['fremember']) ? $_POST['fremember'] : "";

if( $User != "" && $Passwd != "" ) {
   $sql = "select sql_no_cache usuario, clave, admin, cliente from usuarios where usuario='" . $User . "' and clave='" . $Passwd . "'";
   $result = $conn->query($sql);
   if ($result->num_rows > 0) {
      if( $Remember == true ) {
         setcookie("012829", $User,  time() + (86400 * 365), "/" );
         setcookie("012830", $Passwd,  time() + (86400 * 365), "/" );
      }
      
      if($row = $result->fetch_assoc()) {
         if( $row["admin"] == 1 )
            $_SESSION["admin"] = true;
         else $_SESSION["admin"] = false;

         $_SESSION["cliente"] = $row["cliente"];
      }
      mysql_free_result( $result );

      $sql = "insert into log(`Id`,`fecha`,`operador`,`username`,`nombre`,`operacion`,`log`,`cliente` ) values(0,Now(),'','" . $User . "','','Login','',1)";
//      echo $sql;
      $result = $conn->query($sql);
   
      mysqli_close($conn);
      if( $_SESSION["admin"] == true )
           header("Location: llamados.php");
      else {
        if( $_SESSION["cliente"] == 3 )
            header("Location: showmatch.php"); 
        else header("Location: diario.php"); 
      }        
   }
   else {
      setcookie("012829", "", time() - 3600);
      setcookie("012830", "", time() - 3600);
      session_unset(); 
      mysqli_close($conn);
      header("Location: index.php");
   }
} 
else {
   setcookie("012829", "", time() - 3600);
   setcookie("012830", "", time() - 3600);
   session_unset(); 
   mysqli_close($conn);
   header("Location: index.php");
}
?>

