<?php
/**
 * Newsletter Signup API Endpoint
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/email.php';
require_once __DIR__ . '/../config/security.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

$email = sanitizeInput($input['email'] ?? '');

if (empty($email) || !validateEmail($email)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Valid email is required']);
    exit;
}

try {
    $pdo = getDBConnection();
    
    // Check if already subscribed
    $stmt = $pdo->prepare("SELECT id FROM newsletter_subscribers WHERE email = :email");
    $stmt->execute([':email' => $email]);
    
    if ($stmt->fetch()) {
        echo json_encode(['success' => true, 'message' => 'You are already subscribed!']);
        exit;
    }
    
    // Insert subscriber
    $stmt = $pdo->prepare("
        INSERT INTO newsletter_subscribers (email, subscribed_at, status)
        VALUES (:email, NOW(), 'active')
    ");
    
    $stmt->execute([':email' => $email]);
    
    // Send confirmation email
    $subject = 'Welcome to Horizon Drilling Newsletter';
    $body = "
    <html>
    <body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333;'>
        <div style='max-width: 600px; margin: 0 auto; padding: 20px;'>
            <h2 style='color: #FF6B35;'>Thank you for subscribing!</h2>
            <p>You will now receive monthly updates about water and solar solutions.</p>
            <p>Best regards,<br>Horizon Drilling Team</p>
        </div>
    </body>
    </html>
    ";
    
    sendEmail($email, $subject, $body);
    
    echo json_encode(['success' => true, 'message' => 'Successfully subscribed to newsletter!']);
    
} catch (Exception $e) {
    error_log("Newsletter signup error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'An error occurred. Please try again.']);
}

