<?php
/**
 * Newsletter Subscription Handler
 * Handles user newsletter subscriptions with email confirmation
 */

header('Content-Type: application/json');

require_once __DIR__ . '/config/db.php';

// Get request data - support both JSON and form data
$data = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if it's JSON
    if (strpos($_SERVER['CONTENT_TYPE'] ?? '', 'application/json') !== false) {
        $data = json_decode(file_get_contents('php://input'), true) ?? [];
    } else {
        // Form data (application/x-www-form-urlencoded or multipart/form-data)
        $data = $_POST;
    }
}

if (!isset($data['email'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Email is required']);
    exit;
}

$email = trim($data['email']);
$full_name = isset($data['full_name']) ? trim($data['full_name']) : '';
$phone = isset($data['phone']) ? trim($data['phone']) : '';
$source = isset($data['source']) ? trim($data['source']) : 'website';

// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid email address']);
    exit;
}

$conn = $connection;

if ($conn->connect_error) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

// Check if email already exists
$check_sql = "SELECT id, status FROM newsletter_subscribers WHERE email = ?";
$check_stmt = $conn->prepare($check_sql);

if (!$check_stmt) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
    exit;
}

$check_stmt->bind_param('s', $email);
$check_stmt->execute();
$result = $check_stmt->get_result();

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    if ($row['status'] === 'confirmed') {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'This email is already subscribed']);
        exit;
    } elseif ($row['status'] === 'unsubscribed') {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'This email has been unsubscribed and cannot re-subscribe']);
        exit;
    }
}

$check_stmt->close();

// Generate confirmation token
$confirmation_token = bin2hex(random_bytes(32));
$token_expiry = date('Y-m-d H:i:s', strtotime('+24 hours'));
$subscription_source = isset($_SERVER['HTTP_REFERER']) ? parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH) : 'website';
$ip_address = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

// Insert or update subscriber
$sql = "INSERT INTO newsletter_subscribers (email, full_name, phone, status, confirmation_token, confirmation_token_expiry, subscription_source, ip_address, user_agent) 
        VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
        full_name = VALUES(full_name),
        phone = VALUES(phone),
        status = 'pending',
        confirmation_token = VALUES(confirmation_token),
        confirmation_token_expiry = VALUES(confirmation_token_expiry),
        ip_address = VALUES(ip_address),
        user_agent = VALUES(user_agent),
        updated_at = NOW()";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
    exit;
}

$stmt->bind_param('ssssssss', $email, $full_name, $phone, $confirmation_token, $token_expiry, $subscription_source, $ip_address, $user_agent);

if (!$stmt->execute()) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to process subscription']);
    exit;
}

$subscriber_id = $stmt->insert_id;
$stmt->close();

// Log the subscription attempt
$log_sql = "INSERT INTO newsletter_approval_logs (subscriber_id, action) VALUES (?, 'pending')";
$log_stmt = $conn->prepare($log_sql);
$log_stmt->bind_param('i', $subscriber_id);
$log_stmt->execute();
$log_stmt->close();

// Send confirmation email
$confirmation_link = "https://" . $_SERVER['HTTP_HOST'] . "/newsletter-confirm.php?token=" . $confirmation_token;

// Email content
$subject = 'Confirm Your Newsletter Subscription - Faren Design';

$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: 28px; }
        .content { padding: 30px; background: #f8f9fa; border: 1px solid #e0e0e0; }
        .button { background-color: #FF833B; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 20px 0; font-weight: bold; }
        .footer { font-size: 12px; color: #666; margin-top: 20px; border-top: 1px solid #ddd; padding-top: 20px; text-align: center; }
        .warning { background: #fff3cd; padding: 15px; border-left: 4px solid #ffc107; margin: 15px 0; }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>Welcome to Faren Design</h1>
        </div>
        <div class='content'>
            <p>Hi " . htmlspecialchars($full_name ?: 'there') . ",</p>
            
            <p>Thank you for subscribing to our newsletter! We're excited to share updates about our latest interior design projects, services, and special promotions with you.</p>
            
            <p>To complete your subscription and start receiving our newsletters, please confirm your email address by clicking the button below:</p>
            
            <center>
                <a href='" . $confirmation_link . "' class='button'>Confirm Email Address</a>
            </center>
            
            <p>Or copy and paste this link in your browser:<br>
            <small>" . $confirmation_link . "</small></p>
            
            <div class='warning'>
                <strong>Note:</strong> This confirmation link will expire in 24 hours. If you didn't request this subscription, you can ignore this email.
            </div>
            
            <p>Once you confirm your email, you'll receive:</p>
            <ul>
                <li>✓ Exclusive interior design inspiration and trends</li>
                <li>✓ Project showcases and portfolio updates</li>
                <li>✓ Special offers and promotions</li>
                <li>✓ Interior design tips and advice</li>
                <li>✓ New service announcements</li>
            </ul>
            
            <p>Best regards,<br>
            <strong>Faren Design Team</strong></p>
        </div>
        <div class='footer'>
            <p>&copy; " . date('Y') . " Faren Design. All rights reserved.</p>
            <p>You received this email because you subscribed to our newsletter.</p>
        </div>
    </div>
</body>
</html>";

$headers = [
    'From' => 'Faren Design <noreply@farendesign.com>',
    'Reply-To' => 'noreply@farendesign.com',
    'Content-Type' => 'text/html; charset=UTF-8',
    'X-Mailer' => 'Newsletter System'
];

// Try to send email
$email_sent = sendEmailWithPHPMailer($email, $subject, $message);

if ($email_sent) {
    // Add to email queue for tracking
    $queue_sql = "INSERT INTO newsletter_email_queue (subscriber_email, subscriber_id, subject_line, email_content, status) 
                  VALUES (?, ?, ?, ?, 'sent')";
    $queue_stmt = $conn->prepare($queue_sql);
    $queue_stmt->bind_param('siss', $email, $subscriber_id, $subject, $message);
    $queue_stmt->execute();
    $queue_stmt->close();

    echo json_encode([
        'success' => true,
        'message' => 'Subscription successful! Please check your email to confirm your subscription.',
        'subscriber_id' => $subscriber_id
    ]);
} else {
    // Email sending failed but subscription created
    $queue_sql = "INSERT INTO newsletter_email_queue (subscriber_email, subscriber_id, subject_line, email_content, status, error_message) 
                  VALUES (?, ?, ?, ?, 'failed', 'Initial send failed')";
    $queue_stmt = $conn->prepare($queue_sql);
    $queue_stmt->bind_param('siss', $email, $subscriber_id, $subject, $message);
    $queue_stmt->execute();
    $queue_stmt->close();

    http_response_code(202);
    echo json_encode([
        'success' => true,
        'message' => 'Subscription created. Please check your email to confirm (confirmation email may take a few minutes).',
        'subscriber_id' => $subscriber_id
    ]);
}

$conn->close();

/**
 * Send email using PHPMailer
 */
function sendEmailWithPHPMailer($to, $subject, $message) {
    try {
        // Load PHPMailer from auth-system
        $exception_path = __DIR__ . '/auth-system/PHPMailer/src/Exception.php';
        $smtp_path = __DIR__ . '/auth-system/PHPMailer/src/SMTP.php';
        $phpmailer_path = __DIR__ . '/auth-system/PHPMailer/src/PHPMailer.php';
        
        if (!file_exists($phpmailer_path)) {
            error_log("PHPMailer path not found: " . $phpmailer_path);
            return sendEmailBasic($to, $subject, $message);
        }
        
        require_once $exception_path;
        require_once $smtp_path;
        require_once $phpmailer_path;
        
        $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
        
        // Server settings
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'mohamedhalith117@gmail.com';
        $mail->Password = 'arctfbzmhhddkfqr';
        $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        
        // Recipients
        $mail->setFrom('mohamedhalith117@gmail.com', 'Interior Design Solutions');
        $mail->addAddress($to);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $message;
        
        return $mail->send();
    } catch (\PHPMailer\PHPMailer\Exception $e) {
        error_log("PHPMailer Error: " . $e->getMessage());
        return sendEmailBasic($to, $subject, $message);
    } catch (Exception $e) {
        error_log("General Exception: " . $e->getMessage());
        return sendEmailBasic($to, $subject, $message);
    }
}

/**
 * Fallback basic email function
 */
function sendEmailBasic($to, $subject, $message) {
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";
    $headers .= "From: Faren Design <noreply@farendesign.com>\r\n";
    $headers .= "Reply-To: noreply@farendesign.com\r\n";
    
    return mail($to, $subject, $message, $headers);
}
?>

