<?php 

include("_init.php");
$document->setTitle(trans('text_login_title'));

// Check, If User Login or Not
if ($user->isLogged()) {
  redirect(ADMINDIRNAME.'/dashboard.php');
}

function insert_error_log()
{
  $statement = db()->prepare("INSERT INTO `login_logs` SET `ip` = ?, `status` = ?");
  $statement->execute(array(get_real_ip(), 'error'));
}

if ($request->server['REQUEST_METHOD'] == 'POST' && $request->get['action_type'] == "LOGIN")
{
  try {

    // Check total try
    $from = date('Y-m-d H:i:s', strtotime('-'.(int)UNLOCK_ACCOUNT_AFTER.' minutes', time()));
    $to = date('Y-m-d H:i:s'); 
    $ip = get_real_ip();
    $statement = db()->prepare("SELECT `id` FROM `login_logs` WHERE `status` = ? AND `ip` = ? AND `created_at` >= ? AND `created_at` <= ?");
    $statement->execute(array('error', $ip, $from, $to));
    $total_try = $statement->rowCount();
    if ($total_try >= (int)TOTAL_LOGIN_TRY) {
      throw new Exception($language->get('error_login_attempts_exceeded') . '. Try after' . UNLOCK_ACCOUNT_AFTER . ' munute(s)');
    }

    // Validate Username
    if (!isset($request->post['username']) || !isset($request->post['username'])) {
      insert_error_log();
      throw new Exception(trans('error_username_or_password'));
    }
    if (!validateString($request->post['username'])) {
      insert_error_log();
      throw new Exception(trans('error_username'));
    }

    // Validate Password
    if (empty($request->post['password'])) {
      insert_error_log();
        throw new Exception(trans('error_password'));
    }

    $username = $request->post['username']; 
    $password = $request->post['password']; 

    // Attempt to Log In
    if ($user->login($username, $password)) {
        
      $statement = db()->prepare("INSERT INTO `login_logs` SET `user_id` = ?, `username` = ?, `ip` = ? , `created_at` = ?");
      $statement->execute(array(user_id(), $username, get_real_ip(), $to));

      $statement = db()->prepare("UPDATE `users` SET `last_login` = ? WHERE `id` = ?");
      $statement->execute(array(date_time(), user_id()));

      $statement = db()->prepare("DELETE FROM `login_logs` WHERE `ip` = ? AND `status` = ?");
      $statement->execute(array(get_real_ip(), 'error'));

      if (LOG) {
        $log_path = DIR_STORAGE . 'logs/v.txt';
        write_file($log_path, get_real_ip() . ' | ', 'a');
      }

      // Remember Me
      if(!empty($_POST["remember"])) {
        setcookie ("user_login",$_POST["username"],time()+ (10 * 365 * 24 * 60 * 60));
      } else {
        if(isset($_COOKIE["user_login"])) {
          setcookie ("user_login","");
        }
      }

      header('Content-Type: application/json; charset=UTF-8');
      echo json_encode(array('msg' => trans('login_success'), 'sessionUserId' => $session->data['id'], 'count_user_store' => count_user_store(), 'store_id' => $user->getSingleStoreId()));
      exit();
    }

    insert_error_log();
    throw new Exception(trans('error_invalid_username_password'));

  } catch (Exception $e) {

    header('HTTP/1.1 422 Unprocessable Entity');
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode(array('errorMsg' => $e->getMessage()));
    exit();
  }
}

// Sending Password Resetting Code Via Email
if ($request->server['REQUEST_METHOD'] == 'POST' && $request->get['action_type'] == "SEND_PASSWORD_RESET_CODE")
{
  try {

    if(DEMO) {
      throw new Exception(trans('error_disable_in_demo'));
    }

    // Validate Email Address
    if (!validateEmail($request->post['email'])) {
        throw new Exception(trans('error_email'));
    }

    $email = $request->post['email']; 

    // Check, If Email Address Exist In Database or Not
    $statement = db()->prepare("SELECT * FROM `users` LEFT JOIN `user_to_store` as `u2s` ON (`users`.`id` = `u2s`.`user_id`) WHERE `email` = ? AND `u2s`.`status` = ?");
    $statement->execute(array($email, 1));
    $the_user = $statement->fetch(PDO::FETCH_ASSOC);
    if (!$the_user) {
      throw new Exception(trans('error_user_not_found'));
    }

    // Check, If SMTP Server Is Enabled or Not
    $driver = get_preference('email_driver');
    if ($driver != 'smtp_server') {
      throw new Exception(trans('error_smtp_server'));
    }

    $subject        = trans('text_password_reset');
    $recipient_name = $the_user['username'];
    $from_name      = get_preference('email_from');
    $from_address   = get_preference('email_address');
    $smtp_host      = get_preference('smtp_host');
    $smtp_username  = get_preference('smtp_username');
    $smtp_password  = get_preference('smtp_password');
    $smtp_port      = get_preference('smtp_port');
    $ssl_tls        = get_preference('ssl_tls');

    // Email Start

    require_once('_inc/vendor/PHPMailer/PHPMailerAutoload.php');
    $mail = new PHPMailer;
    $mail->IsSMTP();    // Telling The Class To Use SMTP
    $mail->SMTPAuth = true;     // Enable SMTP Authentication
    $mail->SMTPSecure = $ssl_tls;     // Sets The Prefix To The Server
    $mail->Host = $smtp_host;     // Sets GMAIL as the SMTP server
    $mail->Port = $smtp_port;     // Set The SMTP Port For The GMAIL Server
    $mail->Username = $smtp_username;     // GMAIL Username
    $mail->Password = $smtp_password;     // GMAIL Password
    $mail->AddAddress($email, $recipient_name);
    $mail->SetFrom($smtp_username, $from_name);
    $mail->Subject = $subject;
    $mail->IsHTML(true);
    $template_name = 'password-reset';
    if (!file_exists(DIR_EMAIL_TEMPLATE . $template_name . '.php') || !is_file(DIR_EMAIL_TEMPLATE . $template_name . '.php')) {
        throw new Exception(trans('error_email_template_not_found'));
    }

    //Generate Unique String
    $uniqid_str = md5(uniqid(mt_rand()));
    $reset_pass_link = root_url() . '/password_reset.php?fp_code=' . $uniqid_str;

    ob_start();
    require('_inc/template/email/' . $template_name . '.php');
    $body = ob_get_contents();
    ob_end_clean();
    $mail->Body = $body;

    if (!$mail->Send()) {
        throw new Exception(trans('error_email_not_sent'));
    }

    // Email End

    // Update Users Password Reset Code
    $statement = db()->prepare("UPDATE `users` SET `pass_reset_code` = ?, `reset_code_time` = ? WHERE `id` = ?");
    $statement->execute(array($uniqid_str, date('Y-m-d H:i:s'), $the_user['id']));

    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode(array('msg' => trans('success_reset_code_sent')));
    exit();

  } catch (Exception $e) {

    header('HTTP/1.1 422 Unprocessable Entity');
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode(array('errorMsg' => $e->getMessage()));
    exit();
  }
} ?>
<!DOCTYPE html>
<html lang="<?php echo $document->langTag($active_lang);?>">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title><?php echo store('name') ? store('name') . ' | ' : ''; ?><?php echo trans('title_log_in');?></title>
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  
  <!--Set Favicon-->
  <?php if ($store->get('favicon')): ?>
      <link rel="shortcut icon" href="assets/itsolution24/img/logo-favicons/<?php echo $store->get('favicon'); ?>">
  <?php else: ?>
      <link rel="shortcut icon" href="assets/itsolution24/img/logo-favicons/nofavicon.png">
  <?php endif; ?>

  <!-- All CSS -->
  <?php if (DEMO || USECOMPILEDASSET) : ?>
    <!-- LOGIN COMBINED CSS -->
    <link type="text/css" href="assets/itsolution24/cssmin/login.css" rel="stylesheet">
  <?php else : ?>
    <!-- Bootstrap CSS -->
    <link type="text/css" href="assets/bootstrap/css/bootstrap.css" rel="stylesheet">
    <!-- Toastr CSS-->
    <link type="text/css" href="assets/toastr/toastr.min.css" rel="stylesheet">
    <!-- Theme CSS -->
    <link type="text/css" href="assets/itsolution24/css/theme.css" rel="stylesheet">
    <!-- Login CSS -->
    <link type="text/css" href="assets/itsolution24/css/login.css" rel="stylesheet">
  <?php endif; ?>

  <!-- ====== MODERN LOGIN OVERRIDES (sin romper tu theme) ====== -->
  <style>
    /* Fondo moderno */
    body.login-page {
      min-height: 100vh;
      background:
        radial-gradient(1200px 600px at 10% 10%, rgba(0, 123, 255, .18), transparent 60%),
        radial-gradient(900px 500px at 90% 20%, rgba(40, 167, 69, .14), transparent 55%),
        linear-gradient(135deg, #0b1320 0%, #0f1b2d 45%, #0b1320 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 24px 12px;
    }

    /* Caja tipo “card” */
    .login-box {
      width: 100%;
      max-width: 420px;
      margin: 0 auto;
    }

    .login-card {
      background: rgba(255,255,255,0.06);
      border: 1px solid rgba(255,255,255,0.10);
      border-radius: 18px;
      box-shadow: 0 18px 60px rgba(0,0,0,0.45);
      overflow: hidden;
      backdrop-filter: blur(10px);
    }

    /* Header superior */
    .login-card-header {
      padding: 22px 22px 14px 22px;
      border-bottom: 1px solid rgba(255,255,255,0.08);
      background: linear-gradient(135deg, rgba(0,123,255,0.18), rgba(40,167,69,0.10));
    }

    .brand-row {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .brand-badge {
      width: 42px;
      height: 42px;
      border-radius: 12px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      background: rgba(255,255,255,0.10);
      border: 1px solid rgba(255,255,255,0.12);
    }

    .brand-badge svg {
      width: 20px;
      height: 20px;
      opacity: .95;
    }

    .brand-title {
      margin: 0;
      font-size: 18px;
      font-weight: 700;
      color: #fff;
      letter-spacing: .2px;
      line-height: 1.15;
    }

    .brand-subtitle {
      margin: 2px 0 0 0;
      color: rgba(255,255,255,0.72);
      font-size: 12.5px;
    }

    /* Body */
    .login-card-body {
      padding: 18px 22px 22px 22px;
    }

    .login-box-msg {
      margin: 0 0 14px 0;
      color: rgba(255,255,255,0.9);
      font-weight: 600;
      text-align: left;
    }

    /* Inputs modernos (Bootstrap 3 friendly) */
    .login-card .form-control {
      height: 44px;
      border-radius: 12px;
      background: rgba(255,255,255,0.08);
      border: 1px solid rgba(255,255,255,0.10);
      color: #fff;
      box-shadow: none;
    }

    .login-card .form-control::placeholder { color: rgba(255,255,255,0.55); }

    .login-card .form-control:focus {
      border-color: rgba(0,123,255,0.55);
      box-shadow: 0 0 0 3px rgba(0,123,255,0.18);
      background: rgba(255,255,255,0.10);
    }

    .login-card .input-group-addon {
      border-radius: 12px 0 0 12px;
      border: 1px solid rgba(255,255,255,0.10);
      border-right: none;
      background: rgba(255,255,255,0.08);
      color: rgba(255,255,255,0.85);
    }

    .login-card .input-group .form-control {
      border-left: none;
      border-radius: 0 12px 12px 0;
    }

    .login-card .svg-icon {
      width: 18px;
      height: 18px;
      vertical-align: middle;
      opacity: .95;
    }

    /* Botón moderno */
    .btn-login {
      height: 46px;
      border-radius: 12px;
      font-weight: 700;
      letter-spacing: .2px;
      border: 0;
      background: linear-gradient(135deg, #1f7cff 0%, #19b36b 100%);
      box-shadow: 0 10px 26px rgba(0,0,0,0.35);
      transition: transform .08s ease, filter .2s ease;
    }

    .btn-login:hover { filter: brightness(1.05); }
    .btn-login:active { transform: translateY(1px); }

    /* Helpers */
    .login-meta {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      margin-top: 10px;
    }

    .login-meta label {
      margin: 0;
      font-weight: 500;
      color: rgba(255,255,255,0.75);
      user-select: none;
    }

    .login-meta a {
      color: rgba(255,255,255,0.82);
      text-decoration: none;
    }
    .login-meta a:hover { color: #fff; text-decoration: underline; }

    /* Alert arriba */
    .login-alert {
      margin: 14px 0 0 0;
      border-radius: 12px;
      border: 1px solid rgba(255,255,255,0.10);
    }

    /* Footer */
    .copyright {
      margin-top: 12px;
      color: rgba(255,255,255,0.55);
      font-size: 12px;
    }
    .copyright a { color: rgba(255,255,255,0.72); }
    .copyright a:hover { color: #fff; }

    /* Modal (forgot) un poco más prolijo */
    .modal-content { border-radius: 14px; }
    .modal-header { border-top-left-radius: 14px; border-top-right-radius: 14px; }
  </style>
  <!-- ====== /MODERN LOGIN OVERRIDES ====== -->

  <!-- JS -->
  <script type="text/javascript">
    var isDemo = false;
  <?php if(DEMO) : ?>
    var isDemo = true;
  <?php endif;?>
  </script>

  <script type="text/javascript">
    var baseUrl = "<?php echo root_url(); ?>";
    var adminDir = "<?php echo ADMINDIRNAME; ?>";
    var refUrl = "<?php echo isset($request->get['redirect_to']) ? $request->get['redirect_to'] : ''?>";
  </script>

  <?php if (DEMO || USECOMPILEDASSET) : ?>
    <!-- Login Combined JS -->
    <script src="assets/itsolution24/jsmin/login.js"></script>
  <?php else : ?>
    <!-- jQuery JS -->
    <script src="assets/jquery/jquery.min.js" type="text/javascript"></script>
    <!-- Bootstrap JS -->
    <script src="assets/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
    <!-- Toastr JS -->
    <script src="assets/toastr/toastr.min.js" type="text/javascript"></script>
    <!-- Common JS -->
    <script src="assets/itsolution24/js/common.js"></script>
    <!-- Login JS -->
    <script src="assets/itsolution24/js/login.js"></script>
  <?php endif; ?>

</head>
<body class="login-page">
<div class="hidden"><?php include('assets/itsolution24/img/iconmin/membership/membership.svg');?></div>

  <section class="login-box">
    <div class="login-card">

      <div class="login-card-header">
        <div class="brand-row">
          <div class="brand-badge" aria-hidden="true">
            <!-- icon: reuse tu svg -->
            <svg class="svg-icon"><use href="#icon-avatar"></use></svg>
          </div>
          <div class="brand-text">
            <p class="brand-title"><?php echo store('name'); ?></p>
            <p class="brand-subtitle"><?php echo trans('Acceso al sistema'); ?></p>
          </div>
        </div>
      </div>

      <?php if (isset($error_message)) : ?>
        <div class="alert alert-danger login-alert">
          <p style="margin:0;"><span class="fa fa-fw fa-warning"></span> <?php echo $error_message ; ?></p>
        </div>
      <?php endif; ?>

      <div class="login-card-body" ng-controller="LoginController">
        <p class="login-box-msg">
          <strong><?php echo trans('Iniciar sesión'); ?></strong>
        </p>

        <form id="login-form" action="login.php" method="post">

          <div class="form-group">
            <div class="input-group">
              <div class="input-group-addon input-sm">
                <svg class="svg-icon"><use href="#icon-avatar"></use></svg>
              </div>
              <input
                type="text"
                class="form-control"
                value="<?php echo isset($_COOKIE['user_login']) ? htmlspecialchars($_COOKIE['user_login']) : ''; ?>"
                placeholder="Usuario o Email"
                name="username"
                autocomplete="username"
                required>
            </div>
          </div>

          <div class="form-group">
            <div class="input-group">
              <div class="input-group-addon input-sm">
                <svg class="svg-icon"><use href="#icon-password"></use></svg>
              </div>
              <input
                type="password"
                class="form-control"
                value=""
                placeholder="Contraseña"
                name="password"
                autocomplete="current-password"
                required>
            </div>
          </div>

          <button type="submit" id="login-btn" class="btn btn-login btn-block" data-loading-text="Cargando...">
            <i class="fa fa-fw fa-sign-in"></i>
            <?php echo trans('Entrar'); ?>
          </button>

          <div class="login-meta">
            <label class="checkbox-inline" style="color: rgba(255,255,255,0.75);">
              <input type="checkbox" name="remember" value="1" <?php echo isset($_COOKIE['user_login']) && $_COOKIE['user_login'] ? 'checked' : ''; ?>>
              Recordarme
            </label>

            <?php if (!DEMO) : ?>
              <a href="#" data-toggle="modal" data-target="#forgotPasswordModal">
                ¿Olvidaste tu contraseña?
              </a>
            <?php endif; ?>
          </div>

        </form>
      </div>
    </div>

    <div class="copyright text-center">
      <p style="margin:0;">
        &copy; <a href="#" onclick="return false;">Soluciones Informaticas DC - para TERRAPRO</a>
      </p>
    </div>
  </section>

  <?php if (!DEMO) : ?>
    <!--Forgot Password Modal Start -->
    <div id="forgotPasswordModal" class="modal fade" aria-hidden="false" aria-labelledby="forgotPasswordModal" role="dialog" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <form action="#" method="post" accept-charset="utf-8">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
              <h4 class="modal-title"><?php echo trans('title_forgot_password'); ?></h4>
            </div>
            <div class="modal-body">
              <label for="email"><?php echo trans('text_forgot_password_instruction'); ?></label>
              <input id="email" type="email" name="email" placeholder="Email" autocomplete="off" class="form-control">
            </div>
            <div class="modal-footer">
              <button data-dismiss="modal" class="btn btn-warning pull-left" type="button"><?php echo trans('Cerrar'); ?></button>
              <button id="reset-btn" name="reset-btn" class="btn btn-success" type="submit" data-loading-text="Enviando email...">
                <?php echo trans('Enviar'); ?>
              </button>
            </div>
          </form> 
        </div>
      </div>
    </div>
    <!-- Forgot Password Modal End -->
  <?php endif; ?>

<noscript>You need to have javascript enabled in order to use <strong><?php echo store('name');?></strong>.</noscript>
</body>
</html>
