<?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 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;
      }
      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);
  
      $sql = "select sql_no_cache id, Nombre_Empresa, date(FechaInicio) as d, DescripcionEjercicio, date(FechaFin) as h, db_name, month(fecha) as m, year(fecha) as y from ejercicios where Activa='1' limit 1";
//      echo  $sql . "<br/>";

      $result = $conn->query($sql);
      if ($result->num_rows > 0) {
         if($row = $result->fetch_assoc()) {
            $_SESSION["id_empresa"] = $row["id"];
            $_SESSION["db_name"] = $row["db_name"];

            $Desde = $row["d"]; 
            $Hasta = $row["h"]; 
            $D = substr( $Desde, 8, 2 ) . "/" . substr( $Desde, 5, 2 ) . "/" . substr( $Desde, 0, 4 ); 
            $H = substr( $Hasta, 8, 2 ) . "/" . substr( $Hasta, 5, 2 ) . "/" . substr( $Hasta, 0, 4 ); 

            $_SESSION["desde"] = $_SESSION["inicio"] = $D;
            $_SESSION["hasta"] = $_SESSION["fin"] = $H;
            $_SESSION["Desde"] = $_SESSION["inicio"] = $D;
            $_SESSION["Hasta"] = $_SESSION["fin"] = $H;
            $_SESSION["empresa"] = $row["Nombre_Empresa"];
            $_SESSION["Descripcion_Ejercicio"] = $row["DescripcionEjercicio"];
            $fecha = $row["fecha"];
            $_SESSION["Year"] = $row["y"];
            $_SESSION["Month"] = $row["m"];
            $_SESSION["ID_Ejercicio"] = $row["id"];

         }
      }
      mysqli_close($conn);
      header("Location: contableEjercicios.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");
}
?>

