<?php
// --- login.php (LÓGICA INTACTA) ---
if (session_status() === PHP_SESSION_NONE) { session_start(); }
include_once __DIR__ . '/db/db_connection.php';

$error_mensaje = '';
$dashboard_url = 'dashboard';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($email) || empty($password)) {
        $error_mensaje = 'Por favor, introduce tu correo y contraseña.';
    } else {
        try {
            $stmt = $pdo->prepare("SELECT id, full_name, email, password_hash FROM users WHERE email = ?");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && password_verify($password, $user['password_hash'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_email'] = $user['email'];
                $_SESSION['user_full_name'] = htmlspecialchars(trim($user['full_name']));
                $_SESSION['loggedin'] = true;
                session_regenerate_id(true);
                header('Location: ' . $dashboard_url);
                exit();
            } else {
                $error_mensaje = 'Correo o contraseña incorrectos.';
            }
        } catch (PDOException $e) {
            error_log("Error en login.php: " . $e->getMessage());
            $error_mensaje = 'Error al intentar acceder. Inténtalo más tarde.';
        }
    }
}

if (isset($_GET['logout']) && $_GET['logout'] == 'true') {
    unset($_SESSION['loggedin']);
    session_destroy();
    header("Location: /login");
    exit;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Bienvenidos A FlowCRM™  De OrozDesign Powered By OrozCO</title>
  <meta name="robots" content="noindex, nofollow">

  <link rel="icon" type="image/png" href="img/favicon.png">
  <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

  <?php include 'files/gtm-head.php'; ?>

  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://unpkg.com/lucide@latest"></script>
  <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@400;600;800;900&display=swap" rel="stylesheet">

  <style>
    body { font-family: 'Barlow', sans-serif; }
    :root{
      --color-primary:#07162d; --color-secondary:#9e1428; --color-highlight:#ffc857;
      --glass-bg: rgba(255,255,255,0.9);
    }
    input[type="checkbox"]{ accent-color: var(--color-secondary); }
    .btn-primary{ background: linear-gradient(90deg, var(--color-secondary), #b91c2a); color:#fff; }
    .btn-primary:hover{ filter: brightness(1.05); }
    /* Links */
a {
  text-decoration: none; /* sin subrayado */
}
a:hover {
  text-decoration: none; /* asegúrate de que no aparezca */
  color: var(--color-secondary); /* mantiene tu rojo de marca en hover */
}
.link {
  color: var(--color-secondary);
  font-weight: 600;
}


    /* Floating labels */
    .fld{ position:relative; }
    .fld input{ padding-top:1.35rem; }
    .fld label{
      position:absolute; left:0.875rem; top:0.95rem;
      font-size:.95rem; color:#6b7280; transition:all .18s ease; pointer-events:none;
    }
    .fld:focus-within label,
    .fld input:not(:placeholder-shown) + label{
      top:.35rem; font-size:.75rem; color:var(--color-primary);
    }
  </style>
</head>
<body class="h-screen flex flex-col md:flex-row overflow-hidden bg-gray-50">
    
<?php include 'files/gtm-body.php'; ?>

  <!-- HERO MÓVIL (logo + imagen de fondo) -->
  <section class="md:hidden relative w-full h-48">
    <img src="img/BG-FlowCRM.webp" alt="Flow CRM Background"
         class="absolute inset-0 w-full h-full object-cover">
    <div class="absolute inset-0 bg-gradient-to-tr from-[#07162d]/70 via-[#07162d]/40 to-[#9e1428]/40"></div>
    <div class="relative z-10 h-full flex items-center justify-center">
      <img src="img/LogoFlowCRM.webp"
      
           alt="Logo FlowCRM" class="h-16 w-auto drop-shadow">
    </div>
  </section>

  <!-- IZQUIERDA (desktop ≥ md): Imagen + features -->
  <aside class="hidden md:flex w-1/2 relative">
    <img src="img/BG-FlowCRM.webp" alt="Fondo Login" class="absolute inset-0 w-full h-full object-cover">
    <div class="absolute inset-0 bg-gradient-to-tr from-[#07162d]/70 via-[#07162d]/40 to-[#9e1428]/40"></div>

    <div class="relative z-10 flex flex-col justify-between w-full p-10">
      <div class="flex items-center gap-3">
        <img src="img/favicon.png" class="h-9 w-9 rounded-lg" alt="Logo">
        <span class="text-white/90 font-semibold tracking-wide">OrozDesign Multimedia</span>
      </div>

      <div class="text-white">
        <div class="flex justify-start mb-6">
          <img src="img/LogoFlowCRM.webp" alt="Logo FlowCRM" class="h-16 xl:h-20 w-auto">
        </div>

        <p class="mt-3 text-white/85 max-w-xl">
          Tu Centro de Control para Gestionar el Crecimiento de tu Negocio
        </p>

        <ul class="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-3 text-white/90 max-w-2xl">
          <li class="flex items-center gap-3"><i data-lucide="users" class="w-5 h-5"></i> Gestión De Prospectos y Clientes</li>
          <li class="flex items-center gap-3"><i data-lucide="workflow" class="w-5 h-5"></i> Pipeline Visual y Seguimiento</li>
          <li class="flex items-center gap-3"><i data-lucide="calendar-clock" class="w-5 h-5"></i> Agenda, Citas y Recordatorios</li>
          <li class="flex items-center gap-3"><i data-lucide="file-text" class="w-5 h-5"></i> Cotizaciones y Finanzas</li>
        </ul>
      </div>
    </div>
  </aside>

  <!-- DERECHA: Formulario -->
  <main class="w-full md:w-1/2 flex items-center justify-center p-6 sm:p-10">
    <div class="w-full max-w-md">

      <!-- Título -->
      <header class="mb-6 text-center md:text-left">
        <h2 class="text-4xl md:text-5xl font-black leading-none uppercase">
          <span class="text-[var(--color-primary)]">INICIAR</span>
          <span class="text-[var(--color-secondary)]">SESIÓN</span>
        </h2>
        <p class="mt-3 text-xs font-semibold tracking-widest text-gray-500 uppercase">
          Accede a FlowCRM™ con tus credenciales
        </p>
      </header>

      <?php if (!empty($error_mensaje)): ?>
        <div class="mb-4 p-3 rounded bg-red-100 text-red-700 flex items-center gap-2">
          <i data-lucide="alert-triangle" class="w-5 h-5"></i>
          <span><?php echo htmlspecialchars($error_mensaje); ?></span>
        </div>
      <?php endif; ?>

      <form action="/login.php" method="POST" class="space-y-5">
        <!-- Email -->
        <div class="fld">
          <input
            type="email" id="email" name="email" placeholder=" " required autocomplete="email" autofocus
            class="w-full peer rounded-xl border border-gray-300 bg-white/90 px-3.5 pt-5 pb-2.5 text-[15px] leading-tight outline-none transition focus:border-[var(--color-secondary)] focus:ring-2 focus:ring-[var(--color-highlight)]/50"
          />
          <label for="email">Correo Electrónico</label>
          <i data-lucide="mail" class="absolute right-3 top-3.5 w-5 h-5 text-gray-400 pointer-events-none"></i>
        </div>

        <!-- Password -->
        <div class="fld">
          <input
            type="password" id="password" name="password" placeholder=" " required autocomplete="current-password"
            class="w-full peer rounded-xl border border-gray-300 bg-white/90 px-3.5 pt-5 pb-2.5 text-[15px] leading-tight outline-none transition focus:border-[var(--color-secondary)] focus:ring-2 focus:ring-[var(--color-highlight)]/50"
          />
          <label for="password">Contraseña</label>
          <button type="button" id="togglePass" aria-label="Mostrar u ocultar contraseña"
                  class="absolute right-3 top-3.5 p-1 rounded-md text-gray-500 hover:text-gray-700 focus:outline-none">
            <i data-lucide="eye" class="w-5 h-5"></i>
          </button>
        </div>

        <!-- Recordarme + Olvidé -->
        <div class="flex items-center justify-between">
          <label class="inline-flex items-center gap-2 select-none">
            <input type="checkbox" name="remember" id="remember" class="h-4 w-4 rounded border-gray-300">
            <span class="text-sm font-semibold text-gray-700">Recordarme</span>
          </label>
          <a href="forgot_password.php" class="text-sm font-semibold link">¿Olvidaste Tu Contraseña?</a>
        </div>

        <!-- Botón -->
        <button type="submit"
                class="btn-primary w-full inline-flex items-center justify-center gap-2 rounded-xl px-4 py-3.5 font-bold uppercase tracking-wide">
          <i data-lucide="log-in" class="w-5 h-5"></i>
          <span>Iniciar Sesión</span>
        </button>
      </form>

<p class="mt-6 text-center text-gray-600">
  ¿No Tienes Una Cuenta FlowCRM™?<br />
  <a href="https://tunegociolocal.com/" target="_blank" rel="noopener noreferrer"
     class="font-bold text-[var(--color-secondary)] hover:text-[var(--color-primary)] transition-colors">
     Crear Una Cuenta
  </a>
</p>

    </div>
  </main>

  <script>
    lucide.createIcons();
    const toggleBtn = document.getElementById('togglePass');
    const passInput = document.getElementById('password');
    let visible = false;
    toggleBtn?.addEventListener('click', () => {
      visible = !visible;
      passInput.type = visible ? 'text' : 'password';
      toggleBtn.innerHTML = visible
        ? '<i data-lucide="eye-off" class="w-5 h-5"></i>'
        : '<i data-lucide="eye" class="w-5 h-5"></i>';
      lucide.createIcons();
      passInput.focus();
    });
  </script>
</body>
</html>
