<?php
/**
 * Newsletter Email Confirmation
 * Confirms subscriber email and marks as approved
 */

session_start();
require_once __DIR__ . '/config/db.php';

$conn = $connection;

if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

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

if (!empty($confirmation_token)) {
    // Validate token
    $sql = "SELECT id, email, full_name, confirmation_token_expiry, status FROM newsletter_subscribers 
            WHERE confirmation_token = ? AND status = 'pending' AND confirmation_token_expiry > NOW()";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $confirmation_token);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $subscriber_id = $row['id'];
        $email = $row['email'];
        
        // Update status to confirmed
        $update_sql = "UPDATE newsletter_subscribers SET status = 'confirmed', confirmed_at = NOW(), confirmation_token = NULL 
                       WHERE id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param('i', $subscriber_id);
        
        if ($update_stmt->execute()) {
            // Log the confirmation
            $log_sql = "INSERT INTO newsletter_approval_logs (subscriber_id, action) VALUES (?, 'confirmed')";
            $log_stmt = $conn->prepare($log_sql);
            $log_stmt->bind_param('i', $subscriber_id);
            $log_stmt->execute();
            $log_stmt->close();
            
            // Send confirmation to admin
            sendAdminNotification($subscriber_id, $email, $row['full_name'] ?? 'Unknown', 'new_subscriber');
            
            $success = true;
            $message = 'Email confirmed successfully! You are now subscribed to our newsletter.';
        } else {
            $message = 'Failed to confirm email. Please try again.';
        }
        
        $update_stmt->close();
    } else {
        $message = 'Invalid or expired confirmation token. Please subscribe again.';
    }
    
    $stmt->close();
} else {
    $message = 'No confirmation token provided.';
}

$conn->close();

function sendAdminNotification($subscriber_id, $email, $name, $action) {
    require_once __DIR__ . '/config/email.php';
    
    $subject = 'New Newsletter Subscriber - ' . $name;
    
    $message = "
    <html>
    <head>
        <style>
            body { font-family: 'DM Sans', Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: linear-gradient(180deg, #1a1a2e 0%, #16213e 100%); color: white; padding: 30px; text-align: center; border-radius: 5px 5px 0 0; }
            .header h1 { margin: 0; font-size: 24px; }
            .content { padding: 30px; background: #f8f9fa; border: 1px solid #e0e0e0; }
            .info-box { background: white; padding: 15px; border-left: 4px solid #FF833B; margin: 15px 0; }
            .button { background-color: #FF833B; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 10px 5px 10px 0; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>New Newsletter Subscriber</h1>
            </div>
            <div class='content'>
                <p>A new subscriber has confirmed their email address:</p>
                
                <div class='info-box'>
                    <p><strong>Name:</strong> " . htmlspecialchars($name) . "</p>
                    <p><strong>Email:</strong> " . htmlspecialchars($email) . "</p>
                    <p><strong>Subscriber ID:</strong> " . $subscriber_id . "</p>
                    <p><strong>Date:</strong> " . date('Y-m-d H:i:s') . "</p>
                </div>
                
                <p>This subscriber is now confirmed and can receive newsletters. You can manage them from your admin dashboard.</p>
                
                <center>
                    <a href='https://" . $_SERVER['HTTP_HOST'] . "/admin-dashboard.php' class='button'>View Dashboard</a>
                </center>
            </div>
        </div>
    </body>
    </html>";
    
    $headers = [
        'From' => 'Faren Design <noreply@farendesign.com>',
        'Content-Type' => 'text/html; charset=UTF-8',
    ];
    
    // Send to admin email
    $admin_email = 'iiidsumma@gmail.com'; // Change to your admin email
    
    try {
        if (file_exists(__DIR__ . '/vendor/autoload.php')) {
            require __DIR__ . '/vendor/autoload.php';
            $mail = new PHPMailer\PHPMailer\PHPMailer(true);
            $mail->isSMTP();
            $mail->Host = 'mail.zemaraimgroups.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'info@zemaraimgroups.com';
            $mail->Password = 'zemaraimgroups@123';
            $mail->SMTPSecure = 'PHPMailer::ENCRYPTION_SMTPS';
            $mail->Port = 465;
            $mail->setFrom('info@zemaraimgroups.com', 'Interior Design Solutions');
            $mail->addAddress($admin_email);
            $mail->Subject = $subject;
            $mail->isHTML(true);
            $mail->Body = $message;
            $mail->send();
        } else {
            $header_str = "MIME-Version: 1.0\r\nContent-type: text/html; charset=UTF-8\r\n";
            $header_str .= "From: Faren Design <noreply@farendesign.com>\r\n";
            mail($admin_email, $subject, $message, $header_str);
        }
    } catch (Exception $e) {
        // Silently fail if email doesn't send
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $success ? 'Subscription Confirmed' : 'Subscription Error'; ?> - Faren Design</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <style>
        body {
            font-family: 'DM Sans', Arial, sans-serif;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .confirmation-container {
            background: white;
            border-radius: 10px;
            padding: 60px 40px;
            max-width: 500px;
            width: 100%;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            text-align: center;
        }
        .icon {
            font-size: 60px;
            margin-bottom: 20px;
        }
        .success-icon {
            color: #28a745;
        }
        .error-icon {
            color: #dc3545;
        }
        h1 {
            color: #02000F;
            font-size: 28px;
            margin-bottom: 20px;
            font-weight: 600;
        }
        p {
            color: #6C6D71;
            font-size: 16px;
            line-height: 1.6;
            margin-bottom: 30px;
        }
        .btn {
            display: inline-block;
            padding: 12px 30px;
            border-radius: 5px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .btn-primary {
            background: #FF833B;
            color: white;
        }
        .btn-primary:hover {
            background: #E66D2A;
            color: white;
        }
        .btn-secondary {
            background: #6C6D71;
            color: white;
            margin-left: 10px;
        }
        .btn-secondary:hover {
            background: #5A5B5E;
            color: white;
        }
    </style>
</head>
<body>
    <div class="confirmation-container">
        <?php if ($success): ?>
            <div class="icon success-icon">✓</div>
            <h1>Subscription Confirmed!</h1>
            <p><?php echo $message; ?></p>
            <p>You'll now receive our latest interior design updates, project showcases, and special offers.</p>
            <a href="index.php" class="btn btn-primary">Back to Home</a>
        <?php else: ?>
            <div class="icon error-icon">✕</div>
            <h1>Confirmation Failed</h1>
            <p><?php echo $message; ?></p>
            <p>Please try subscribing again or contact support for assistance.</p>
            <a href="index.php" class="btn btn-primary">Back to Home</a>
            <a href="#" onclick="document.location.href='index.php#newsletter'" class="btn btn-secondary">Subscribe Again</a>
        <?php endif; ?>
    </div>
</body>
</html>
