<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }

$error_message = '';
$dashboard_url = 'dashboard.php';

try {
    include_once __DIR__ . '/db/db_connection.php';
    include_once __DIR__ . '/brand/branding.php';

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

        if (empty($email) || empty($password)) {
            $error_message = 'Por favor, introduce tu correo y contraseña.';
        } else {
            $stmt = $pdo->prepare("SELECT user_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['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_message = 'Correo o contraseña incorrectos.';
            }
        }
    }
} catch (PDOException $e) {
    error_log("Login Error: " . $e->getMessage());
    $error_message = 'Error al intentar acceder. Inténtalo más tarde.';
}

if (isset($_GET['logout']) && $_GET['logout'] == 'true') {
    unset($_SESSION['loggedin']);
    session_destroy();
    header("Location: /login.php");
    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 <?php echo htmlspecialchars($branding['full_title'] ?? 'CRM'); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon'] ?? ''); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon'] ?? ''); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
  <style>
    a { text-decoration: none; }
    a:hover { text-decoration: none; color: var(--color-secondary); }
    .link { color: var(--color-secondary); font-weight: 600; }

    .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'; ?>

  <section class="md:hidden relative w-full h-48">
    <img src="<?php echo htmlspecialchars($branding['login-bg'] ?? ''); ?>" alt="CRM Background" class="absolute inset-0 w-full h-full object-cover">
    <div class="absolute inset-0 bg-gradient-to-tr from-[var(--color-primary)]/70 via-[var(--color-primary)]/40 to-[var(--color-secondary)]/40"></div>
    <div class="relative z-10 h-full flex items-center justify-center">
          <img src="<?php echo htmlspecialchars($branding['flow-logo'] ?? ''); ?>" alt="Logo" class="h-16 xl:h-20 w-auto">
    </div>
  </section>

  <aside class="hidden md:flex w-1/2 relative">
    <img src="<?php echo htmlspecialchars($branding['login-bg'] ?? ''); ?>" alt="Fondo Login" class="absolute inset-0 w-full h-full object-cover">
    <div class="absolute inset-0 bg-gradient-to-tr from-[var(--color-primary)]/10 to-[var(--color-secondary)]/10"></div>

    <div class="relative z-10 flex flex-col justify-between w-full p-10">
      <div class="flex items-center gap-3">
        <img src="<?php echo htmlspecialchars($branding['favicon'] ?? ''); ?>" class="h-9 w-9 rounded-lg" alt="Logo">
        <span class="text-white/90 font-semibold tracking-wide"><?php echo htmlspecialchars($branding['biz_name'] ?? ''); ?></span>
      </div>

      <div class="text-white">
        <div class="flex justify-start mb-6">
          <img src="<?php echo htmlspecialchars($branding['flow-logo'] ?? ''); ?>" alt="Logo" class="h-16 xl:h-20 w-auto">
        </div>

        <p class="mt-3 text-white/85 max-w-xl text-lg font-black">
          La Plataforma #1 <span class="text-[var(--color-highlight)]">Para Impulsar Tu Negocio</span>
        </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>

  <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">

      <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  <span class="text-[var(--color-primary)]">
                    <?php echo htmlspecialchars($branding['name'] ?? ''); ?><span class="text-[var(--color-secondary)] font-black"><?php echo htmlspecialchars($branding['crm'] ?? ''); ?></span>™
                </span> con tus credenciales
        </p>
      </header>

      <?php if (!empty($error_message)): ?>
        <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_message); ?></span>
        </div>
      <?php endif; ?>

      <form action="" method="POST" class="space-y-5">
        <div class="fld relative">
          <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" class="absolute left-3.5 top-0.5 text-xs text-gray-500 transition-all peer-placeholder-shown:top-4 peer-placeholder-shown:text-base peer-focus:top-0.5 peer-focus:text-xs">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>

        <div class="fld relative">
          <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" class="absolute left-3.5 top-0.5 text-xs text-gray-500 transition-all peer-placeholder-shown:top-4 peer-placeholder-shown:text-base peer-focus:top-0.5 peer-focus:text-xs">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>

        <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 text-[var(--color-primary)] focus:ring-[var(--color-secondary)]">
            <span class="text-sm font-semibold text-gray-700">Recordarme</span>
          </label>
          <a href="forgot_password.php" class="text-sm font-semibold text-[var(--color-primary)] hover:text-[var(--color-secondary)] transition-colors">¿Olvidaste Tu Contraseña?</a>
        </div>

        <button type="submit"
                class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase flex items-center justify-center gap-2 shadow-lg transition-transform transform hover:-translate-y-0.5">
          <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 font-bold">
        ¿No Tienes Una Cuenta?
        <a href="https://tunegociolocal.com/" target="_blank" rel="noopener noreferrer"
           class="font-black uppercase text-[var(--color-secondary)] hover:text-[var(--color-primary)] transition-colors">
           Crear Una Cuenta
        </a>
      </p>

      <div class="mt-12 text-center">
        <div class="max-w-7xl mx-auto px-6 lg:px-10 text-center">
            <p class="text-base font-semibold text-black">
                © <?php echo date('Y'); ?> <?php echo htmlspecialchars($branding['biz_name'] ?? ''); ?><br /><span class="text-base font-thin text-black">All Rights Reserved</span>
            </p>
            
            <div class="mt-4 pt-2 mx-auto max-w-sm">
                <p class="font-thin text-sm text-black flex items-center justify-center gap-1.5">
                    Powered by <i data-lucide="shield-check" class="w-4 h-4 text-green-700"></i>
                    <span class="font-black text-[var(--color-secondary)] tracking-wide">
                        <?php echo htmlspecialchars($branding['name'] ?? ''); ?><span class="font-black text-black tracking-wide"><?php echo htmlspecialchars($branding['crm'] ?? ''); ?></span>™
                    </span>
                </p>
            </div>
        </div>
      </div>
       
    </div>
  </main>

  <script>
    lucide.createIcons();
    const toggleBtn = document.getElementById('togglePass');
    const passInput = document.getElementById('password');
    let visible = false;
    if(toggleBtn){
        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>
  <script src="files/toast.js"></script>
</body>
</html>