<?php
/**
 * NEMETH PUBLISHERS - Contact Form Handler
 * SMTP-based email routing with journal-specific email addresses
 * 
 * Requirements:
 * - PHP 7.4 or higher
 * - PHPMailer library (install via: composer require phpmailer/phpmailer)
 */

// Import PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// SMTP Configuration - UPDATE THESE VALUES
define('SMTP_HOST', 'smtp.gmail.com');
define('SMTP_PORT', 587);
define('SMTP_USERNAME', 'your-email@gmail.com');  // UPDATE THIS
define('SMTP_PASSWORD', 'your-app-password');      // UPDATE THIS (use App Password, not regular password)
define('SMTP_FROM_NAME', 'NEMETH PUBLISHERS Contact Form');

// Journal-specific email addresses - UPDATE THESE VALUES
$journalEmails = [
    'AJAST' => 'editor@ajast.net',           // UPDATE with actual email
    'IIJSR' => 'editor@iijsr.com',           // UPDATE with actual email
    'MEJAST' => 'editor@mejast.com',         // UPDATE with actual email
    'MJBAS' => 'editor@mjbas.com',           // UPDATE with actual email
    'AJBSR' => 'editor@ajbsr.net',           // UPDATE with actual email
];

// Default email for general inquiries
define('DEFAULT_EMAIL', 'nemethpublishers@gmail.com');

// Load PHPMailer autoloader
require 'vendor/autoload.php';

// Set JSON header for response
header('Content-Type: application/json');

/**
 * Sanitize input data
 */
function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    return $data;
}

/**
 * Validate email address
 */
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

/**
 * Send email using PHPMailer with SMTP
 */
function sendEmail($toEmail, $toName, $subject, $body, $replyTo, $replyToName) {
    $mail = new PHPMailer(true);
    
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USERNAME;
        $mail->Password   = SMTP_PASSWORD;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = SMTP_PORT;
        
        // Recipients
        $mail->setFrom(SMTP_USERNAME, SMTP_FROM_NAME);
        $mail->addAddress($toEmail, $toName);
        $mail->addReplyTo($replyTo, $replyToName);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = strip_tags($body);
        
        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Email sending failed: " . $mail->ErrorInfo);
        return false;
    }
}

/**
 * Main processing
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Validate and sanitize inputs
    $name = isset($_POST['name']) ? sanitizeInput($_POST['name']) : '';
    $email = isset($_POST['email']) ? sanitizeInput($_POST['email']) : '';
    $subject = isset($_POST['subject']) ? sanitizeInput($_POST['subject']) : '';
    $journal = isset($_POST['journal']) ? sanitizeInput($_POST['journal']) : '';
    $message = isset($_POST['message']) ? sanitizeInput($_POST['message']) : '';
    
    // Validation
    $errors = [];
    
    if (empty($name)) {
        $errors[] = 'Name is required';
    }
    
    if (empty($email)) {
        $errors[] = 'Email is required';
    } elseif (!validateEmail($email)) {
        $errors[] = 'Invalid email address';
    }
    
    if (empty($subject)) {
        $errors[] = 'Subject is required';
    }
    
    if (empty($message)) {
        $errors[] = 'Message is required';
    }
    
    // If validation fails
    if (!empty($errors)) {
        echo json_encode([
            'success' => false,
            'message' => 'Please fix the following errors: ' . implode(', ', $errors)
        ]);
        exit;
    }
    
    // Determine recipient email based on journal selection
    $recipientEmail = DEFAULT_EMAIL;
    $recipientName = 'NEMETH PUBLISHERS';
    
    if (!empty($journal) && isset($journalEmails[$journal])) {
        $recipientEmail = $journalEmails[$journal];
        $recipientName = $journal . ' Editorial Team';
    }
    
    // Prepare email body
    $emailBody = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #0c2340; color: white; padding: 20px; text-align: center; }
            .content { background: #f5f7fb; padding: 20px; margin: 20px 0; }
            .field { margin-bottom: 15px; }
            .label { font-weight: bold; color: #0c2340; }
            .footer { text-align: center; color: #6b7f96; font-size: 12px; padding: 20px; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>New Contact Form Submission</h2>
                <p>NEMETH PUBLISHERS</p>
            </div>
            <div class='content'>
                <div class='field'>
                    <span class='label'>From:</span> {$name}
                </div>
                <div class='field'>
                    <span class='label'>Email:</span> {$email}
                </div>
                <div class='field'>
                    <span class='label'>Subject:</span> {$subject}
                </div>
                <div class='field'>
                    <span class='label'>Journal of Interest:</span> " . (!empty($journal) ? $journal : 'General Inquiry') . "
                </div>
                <div class='field'>
                    <span class='label'>Message:</span><br>
                    <p>" . nl2br($message) . "</p>
                </div>
            </div>
            <div class='footer'>
                <p>This email was sent from the NEMETH PUBLISHERS contact form</p>
                <p>D.No. 51, Vinayagar Kovil Street, Velandipalayam, Coimbatore – 641025, Tamil Nadu, India</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    // Email subject line
    $emailSubject = "Contact Form: {$subject}" . (!empty($journal) ? " ({$journal})" : '');
    
    // Send email
    $emailSent = sendEmail(
        $recipientEmail,
        $recipientName,
        $emailSubject,
        $emailBody,
        $email,
        $name
    );
    
    // Response
    if ($emailSent) {
        echo json_encode([
            'success' => true,
            'message' => 'Thank you! Your message has been sent successfully. We will get back to you within 24-48 hours.'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Sorry, there was an error sending your message. Please try again or contact us directly at nemethpublishers@gmail.com'
        ]);
    }
    
} else {
    // Not a POST request
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method'
    ]);
}
?>
