<?php
// Define BASE_PATH se não estiver definido
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__FILE__)));
}

require_once BASE_PATH . '/includes/config.php';
require_once BASE_PATH . '/includes/db.php';
require_once BASE_PATH . '/includes/functions.php';

$token = isset($_GET['token']) ? trim($_GET['token']) : '';
$message = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm'])) {
    $token = $_POST['token'];
    
    try {
        $db->query("UPDATE newsletter_subscribers SET 
                   status = 'unsubscribed',
                   updated_at = NOW() 
                   WHERE unsubscribe_token = :token AND status != 'unsubscribed'");
        $db->bind(':token', $token);
        $db->execute();
        
        if ($db->rowCount() > 0) {
            $success = true;
            $message = 'Te has dado de baja exitosamente del boletín.';
        } else {
            $message = 'Token inválido o ya te habías dado de baja anteriormente.';
        }
    } catch (Exception $e) {
        $message = 'Error al procesar la solicitud.';
        logError("Erro no unsubscribe: " . $e->getMessage());
    }
}

// Verificar se o token é válido
$subscriber = null;
if (!empty($token)) {
    try {
        $db->query("SELECT email, name, status FROM newsletter_subscribers WHERE unsubscribe_token = :token");
        $db->bind(':token', $token);
        $subscriber = $db->single();
    } catch (Exception $e) {
        logError("Erro ao buscar subscriber: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Darse de Baja - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .unsubscribe-card {
            max-width: 500px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .card-header {
            background: linear-gradient(135deg, #4F46E5, #7C3AED);
            color: white;
            text-align: center;
            padding: 2rem;
        }
        .card-body {
            padding: 2rem;
        }
        .btn-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            border: none;
        }
        .btn-secondary {
            background: #6b7280;
            border: none;
        }
    </style>
</head>
<body>
    <div class="unsubscribe-card">
        <div class="card-header">
            <h2 class="mb-0">
                <i class="fas fa-envelope-open-text"></i>
                Darse de Baja
            </h2>
            <p class="mb-0 mt-2 opacity-75"><?php echo SITE_NAME; ?></p>
        </div>
        <div class="card-body">
            <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle me-2"></i>
                    <?php echo $message; ?>
                </div>
                <div class="text-center">
                    <p>Lamentamos verte partir. Si cambias de opinión, siempre puedes volver a suscribirte en nuestro sitio web.</p>
                    <a href="<?php echo SITE_URL; ?>" class="btn btn-primary">
                        <i class="fas fa-home me-2"></i>Volver al sitio
                    </a>
                </div>
            <?php elseif (!empty($message)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    <?php echo $message; ?>
                </div>
            <?php elseif (!$subscriber): ?>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Token inválido o expirado.
                </div>
            <?php else: ?>
                <h4>Confirmar baja del boletín</h4>
                <p><strong>Email:</strong> <?php echo htmlspecialchars($subscriber['email']); ?></p>
                
                <?php if ($subscriber['status'] === 'unsubscribed'): ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        Este email ya está dado de baja del boletín.
                    </div>
                <?php else: ?>
                    <p>¿Estás seguro de que quieres darte de baja de nuestro boletín? Dejarás de recibir:</p>
                    <ul>
                        <li>Notificaciones sobre nuevos cursos gratuitos</li>
                        <li>Contenido exclusivo y tips</li>
                        <li>Ofertas especiales y descuentos</li>
                    </ul>
                    
                    <form method="POST" class="mt-4">
                        <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
                        <div class="d-grid gap-2">
                            <button type="submit" name="confirm" class="btn btn-danger">
                                <i class="fas fa-times me-2"></i>Sí, darme de baja
                            </button>
                            <a href="<?php echo SITE_URL; ?>" class="btn btn-secondary">
                                <i class="fas fa-arrow-left me-2"></i>Cancelar
                            </a>
                        </div>
                    </form>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js"></script>
</body>
</html>