<?php
declare(strict_types=1);
ob_start();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Configuración: Errores ocultos al público
ini_set('display_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);

// RUTAS (Verificamos existencia pero NO ponemos fallbacks con nombres propios)
$dbPath = __DIR__ . '/db/db_connection.php';
$brandPath = __DIR__ . '/brand/branding.php';

if (file_exists($dbPath)) require_once $dbPath;
if (file_exists($brandPath)) require_once $brandPath;

// Validación de sesión
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
    header('Location: dashboard');
    exit();
}

// Inicialización de variables NEUTRALES
$mensaje = '';
$clase_mensaje = '';
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$domain = $_SERVER['HTTP_HOST'] ?? 'localhost';
$baseUrl = $protocol . "://" . $domain;

// Definición del Nombre del Negocio (Jerarquía de Marca Blanca)
// 1. Por defecto: El dominio (lo más seguro y neutral)
$businessName = $domain;

// 2. Si existe configuración de marca, la usamos
if (isset($branding['biz_name']) && !empty($branding['biz_name'])) {
    $businessName = $branding['biz_name'];
}

// 3. Si la base de datos tiene un nombre, ese manda (es lo que el cliente configuró)
if (isset($pdo)) {
    try {
        $stmtInfo = $pdo->prepare("SELECT company_name, logo_url FROM business_info ORDER BY id DESC LIMIT 1");
        $stmtInfo->execute();
        $dbInfo = $stmtInfo->fetch(PDO::FETCH_ASSOC);
        
        if (!empty($dbInfo['company_name'])) {
            $businessName = htmlspecialchars($dbInfo['company_name']);
        }
        
        // Lógica del Logo: DB > Branding > Vacío
        if (!empty($dbInfo['logo_url'])) {
            $logoUrl = $dbInfo['logo_url'];
        } else {
            $logoUrl = $branding['flow-logo'] ?? '';
        }

    } catch (Exception $e) {
        // Si falla la DB, mantenemos el nombre que ya calculamos (Branding o Dominio)
        error_log("Error obteniendo info de negocio: " . $e->getMessage());
    }
}

// Asegurar URL absoluta del logo para el correo
$logoFullUrl = '';
if (!empty($logoUrl)) {
    // Si ya tiene http, lo dejamos, si no, le pegamos el dominio
    $logoFullUrl = str_starts_with($logoUrl, 'http') ? $logoUrl : $baseUrl . '/' . ltrim($logoUrl, '/');
}

// --- PROCESAMIENTO DEL FORMULARIO ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $email = filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : null;

    if (!$email) {
        $mensaje = 'Por favor, introduce un correo electrónico válido.';
        $clase_mensaje = 'bg-red-100 text-red-700';
    } else {
        try {
            if (isset($pdo)) {
                $stmt = $pdo->prepare("SELECT user_id, full_name FROM users WHERE email = ? LIMIT 1");
                $stmt->execute([$email]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($user) {
                    $token = bin2hex(random_bytes(32));
                    $expiry = date("Y-m-d H:i:s", time() + 3600);

                    $updateStmt = $pdo->prepare("UPDATE users SET reset_token = ?, reset_token_expiry = ? WHERE user_id = ?");
                    $updateStmt->execute([$token, $expiry, $user['user_id']]);

                    $resetLink = $baseUrl . "/reset_password.php?token=" . $token;
                    
                    $subject = "Restablecimiento de Clave - " . $businessName;
                    $headers  = "MIME-Version: 1.0" . "\r\n";
                    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                    $headers .= 'From: ' . $businessName . ' <no-reply@' . $domain . '>' . "\r\n";

                    // Template Neutral
                    $imgTag = !empty($logoFullUrl) ? "<img src='{$logoFullUrl}' alt='Logo' style='max-width: 150px; height: auto; display: block; margin: 0 auto;'>" : "";
                    
                    $emailBody = "
                    <html>
                    <head>
                        <style>@import url('https://fonts.googleapis.com/css2?family=Barlow:wght@400;600;800&display=swap');</style>
                    </head>
                    <body style='font-family: \"Barlow\", Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>
                        <div style='max-width: 600px; margin: 0 auto; background-color: #ffffff; padding: 20px; border-radius: 8px; border-top: 5px solid #9e1428; box-shadow: 0 4px 8px rgba(0,0,0,0.05);'>
                            <p style='text-align: center; margin-bottom: 20px;'>
                                {$imgTag}
                            </p>
                            <h2 style='color: #07162d; text-align: center; font-weight: 800; font-size: 24px; margin-top: 0;'>
                                Recuperar Acceso<br><span style='color: #9e1428;'>{$businessName}</span>
                            </h2>
                            <p style='color: #333; line-height: 1.6;'>Hola <strong>" . htmlspecialchars($user['full_name']) . "</strong>,</p>
                            <p style='color: #333; line-height: 1.6;'>Hemos recibido una solicitud para restablecer tu contraseña. Haz clic en el siguiente botón:</p>
                            <p style='text-align: center; margin: 30px 0;'>
                                <a href='{$resetLink}' style='display: inline-block; padding: 12px 25px; background-color: #9e1428; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: bold; font-size: 16px;'>Establecer Nueva Contraseña</a>
                            </p>
                            <p style='font-size: 12px; color: #777; text-align: center;'>Este enlace es válido por 1 hora. Si no solicitaste este cambio, ignora este mensaje.</p>
                        </div>
                    </body>
                    </html>";

                    mail($email, $subject, $emailBody, $headers);
                }
            }
            $mensaje = 'Si el correo existe en el sistema, recibirás el enlace en breve.';
            $clase_mensaje = 'bg-green-100 text-green-700';

        } catch (Exception $e) {
            error_log("Error Reset: " . $e->getMessage());
            $mensaje = 'Error al procesar la solicitud.';
            $clase_mensaje = 'bg-red-100 text-red-700';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Recuperar Contraseña | <?php echo htmlspecialchars($branding['full_title'] ?? 'Acceso CRM'); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" 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 if(file_exists('files/gtm-head.php')) include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="style.css"> 
    <?php if(file_exists('files/header-manager.js')) echo '<script src="files/header-manager.js"></script>'; ?>

  <style>
    /* Estilos base neutros por si falla CSS externo */
    :root {
        --color-primary: #07162d;
        --color-secondary: #9e1428;
        --color-highlight: #eab308;
    }
    input[type="checkbox"]{ accent-color: var(--color-secondary); }
    a { text-decoration: none; }
    a:hover { text-decoration: none; color: var(--color-secondary); }
    
    .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 if(file_exists('files/gtm-body.php')) include 'files/gtm-body.php'; ?>

  <main class="w-full md:w-1/2 flex items-center justify-center p-6 sm:p-10 mx-auto overflow-y-auto">
    <div class="w-full max-w-md">

      <section class="md:hidden relative w-full h-48 mb-8 rounded-xl overflow-hidden shadow-md">
        <img src="<?php echo htmlspecialchars($branding['login-bg'] ?? ''); ?>" alt="" 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 w-auto drop-shadow-lg">
        </div>
      </section>

      <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)]">RECUPERAR</span>
          <span class="text-[var(--color-secondary)]">CLAVE</span>
        </h2>
        <p class="mt-3 text-sm font-semibold tracking-wide text-gray-500 uppercase">
          Introduce Tu Email Para Recibir Un Enlace De Restablecimiento De Contraseña
        </p>
      </header>

      <?php if (!empty($mensaje)): ?>
        <div class="mb-4 p-3 rounded-lg border-l-4 border-[var(--color-secondary)] flex items-center gap-2 <?php echo $clase_mensaje; ?>">
          <i data-lucide="<?php echo strpos($clase_mensaje, 'red') !== false ? 'alert-triangle' : 'check-circle'; ?>" class="w-6 h-6 shrink-0"></i>
          <span class="font-bold text-sm"><?php echo htmlspecialchars($mensaje); ?></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>

        <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="send" class="w-5 h-5"></i>
          <span>Enviar Link</span>
        </button>
      </form>

      <p class="mt-6 text-center text-gray-600">
        <a href="login.php"
           class="font-black uppercase text-sm text-[var(--color-primary)] hover:text-[var(--color-secondary)] transition-colors inline-flex items-center gap-2">
           <i data-lucide="arrow-left" class="w-4 h-4"></i> Volver Al Inicio
        </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($businessName); ?>
            </p>
            <?php if(isset($branding['name'])): ?>
            <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>
            <?php endif; ?>
        </div>
       </div>

    </div>
  </main>

  <aside class="hidden md:flex w-1/2 relative">
    <img src="<?php echo htmlspecialchars($branding['login-bg'] ?? ''); ?>" alt="" 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 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>

  <script>
    lucide.createIcons();
  </script>
  <?php if(file_exists('files/toast.js')) echo '<script src="files/toast.js"></script>'; ?>
</body>
</html>