<?php
/**
 * Standalone Contact Form Handler
 * Direct endpoint for contact form submissions
 */

// Include email configuration
require_once __DIR__ . '/config/email.php';

// Set JSON response headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

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

try {
    // Get input data
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON format');
    }
    
    // Validate required fields
    $errors = [];
    
    if (empty($data['name'])) {
        $errors['name'] = 'Name is required';
    } elseif (strlen($data['name']) > 100) {
        $errors['name'] = 'Name must be less than 100 characters';
    }
    
    if (empty($data['email'])) {
        $errors['email'] = 'Email is required';
    } elseif (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Invalid email format';
    } elseif (strlen($data['email']) > 150) {
        $errors['email'] = 'Email must be less than 150 characters';
    }
    
    // Optional field validation
    if (!empty($data['phone']) && strlen($data['phone']) > 20) {
        $errors['phone'] = 'Phone number must be less than 20 characters';
    }
    
    if (!empty($data['service']) && strlen($data['service']) > 50) {
        $errors['service'] = 'Service must be less than 50 characters';
    }
    
    if (!empty($data['message']) && strlen($data['message']) > 1000) {
        $errors['message'] = 'Message must be less than 1000 characters';
    }
    
    // Return validation errors
    if (!empty($errors)) {
        http_response_code(422);
        echo json_encode([
            'success' => false,
            'message' => 'Validation failed',
            'data' => ['errors' => $errors]
        ]);
        exit();
    }
    
    // Sanitize data
    $name = htmlspecialchars(trim($data['name']), ENT_QUOTES, 'UTF-8');
    $email = htmlspecialchars(trim($data['email']), ENT_QUOTES, 'UTF-8');
    $phone = !empty($data['phone']) ? htmlspecialchars(trim($data['phone']), ENT_QUOTES, 'UTF-8') : '';
    $service = !empty($data['service']) ? htmlspecialchars(trim($data['service']), ENT_QUOTES, 'UTF-8') : '';
    $message = !empty($data['message']) ? htmlspecialchars(trim($data['message']), ENT_QUOTES, 'UTF-8') : '';
    $source = htmlspecialchars($data['source'] ?? 'website', ENT_QUOTES, 'UTF-8');
    
    // For now, we'll save to a simple file or send email
    // In production, you might want to save to database
    
    // Create contact data array
    $contactData = [
        'name' => $name,
        'email' => $email,
        'phone' => $phone,
        'service' => $service,
        'message' => $message,
        'source' => $source,
        'timestamp' => date('Y-m-d H:i:s'),
        'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ];
    
    // Save to file (you can modify this to save to database)
    $logFile = __DIR__ . '/logs/contact_inquiries.log';
    $logDir = dirname($logFile);
    
    // Create logs directory if it doesn't exist
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    // Save contact inquiry
    $logEntry = date('Y-m-d H:i:s') . " - Contact Inquiry:\n";
    $logEntry .= "Name: $name\n";
    $logEntry .= "Email: $email\n";
    $logEntry .= "Phone: $phone\n";
    $logEntry .= "Service: $service\n";
    $logEntry .= "Message: $message\n";
    $logEntry .= "Source: $source\n";
    $logEntry .= "IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . "\n";
    $logEntry .= "User Agent: " . ($_SERVER['HTTP_USER_AGENT'] ?? 'unknown') . "\n";
    $logEntry .= str_repeat('-', 50) . "\n\n";
    
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    
    // Send email notification to spa using SMTP
    $emailSent = sendSMTPEmail($name, $email, $phone, $service, $message);
    
    // Success response
    http_response_code(201);
    echo json_encode([
        'success' => true,
        'message' => 'Contact inquiry submitted successfully',
        'data' => [
            'inquiry_id' => uniqid('contact_', true),
            'email_sent' => $emailSent
        ]
    ]);
    
} catch (Exception $e) {
    // Log error
    error_log("Contact form error: " . $e->getMessage());
    
    // Error response
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Sorry, there was an error processing your request. Please try again later.'
    ]);
}

/**
 * Send email using SMTP with authentication
 */
function sendSMTPEmail($name, $email, $phone, $service, $message) {
    // Get email configuration
    $config = getEmailConfig();
    
    // Email content
    $subject = $config['subject_template'];
    $emailBody = "New contact inquiry received:\n\n";
    $emailBody .= "Name: $name\n";
    $emailBody .= "Email: $email\n";
    $emailBody .= "Phone: " . ($phone ?: 'Not provided') . "\n";
    $emailBody .= "Service Interested: " . ($service ?: 'Not specified') . "\n";
    $emailBody .= "Message: " . ($message ?: 'No message provided') . "\n\n";
    $emailBody .= "Submitted on: " . date('Y-m-d H:i:s') . "\n";
    $emailBody .= "From: Website Contact Form";
    
    $emailSent = false;
    
    // Try SMTP first, fallback to basic mail()
    try {
        // Validate configuration
        validateEmailConfig();
        
        // Check if we can use sockets for SMTP
        if (function_exists('fsockopen')) {
            $emailSent = sendViaSMTP($config, $email, $subject, $emailBody);
        } else {
            throw new Exception("fsockopen function not available");
        }
    } catch (Exception $e) {
        error_log("SMTP Error: " . $e->getMessage());
        
        // Fallback to basic mail() if enabled
        if ($config['fallback_to_basic_mail']) {
            $emailSent = sendViaBasicMail($config, $email, $subject, $emailBody);
        }
    }
    
    // Send auto-reply if enabled and email was sent successfully
    if ($emailSent && $config['send_auto_reply']) {
        try {
            sendAutoReply($config, $email, $name);
        } catch (Exception $e) {
            error_log("Auto-reply error: " . $e->getMessage());
        }
    }
    
    return $emailSent;
}

/**
 * Send email via SMTP using sockets
 */
function sendViaSMTP($config, $replyToEmail, $subject, $body) {
    // Create SSL context
    $context = stream_context_create([
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        ]
    ]);
    
    // Connect to SMTP server
    $connection = stream_socket_client(
        $config['smtp_security'] . "://" . $config['smtp_server'] . ":" . $config['smtp_port'], 
        $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context
    );
    
    if (!$connection) {
        throw new Exception("Failed to connect to SMTP server: $errstr ($errno)");
    }
    
    // Read server response
    $response = fgets($connection, 515);
    if (substr($response, 0, 3) != '220') {
        throw new Exception("SMTP server not ready: $response");
    }
    
    // SMTP commands
    $commands = [
        "EHLO zenzone.rw\r\n",
        "AUTH LOGIN\r\n",
        base64_encode($config['smtp_username']) . "\r\n",
        base64_encode($config['smtp_password']) . "\r\n",
        "MAIL FROM: <" . $config['from_email'] . ">\r\n",
        "RCPT TO: <" . $config['to_email'] . ">\r\n",
        "DATA\r\n"
    ];
    
    // Execute SMTP commands
    foreach ($commands as $command) {
        fwrite($connection, $command);
        $response = fgets($connection, 515);
        
        // Check for errors (simplified error checking)
        if (in_array(substr($response, 0, 3), ['500', '501', '502', '503', '504', '550', '551', '552', '553', '554'])) {
            fclose($connection);
            throw new Exception("SMTP Error: $response");
        }
    }
    
    // Generate RFC 5322 compliant headers
    $messageId = '<' . uniqid() . '@zenzone.rw>';
    $date = date('r'); // RFC 2822 formatted date
    
    // Send RFC 5322 compliant email headers and body
    $headers = "Message-ID: $messageId\r\n";
    $headers .= "Date: $date\r\n";
    $headers .= "From: " . $config['from_name'] . " <" . $config['from_email'] . ">\r\n";
    $headers .= "Reply-To: $replyToEmail\r\n";
    $headers .= "To: <" . $config['to_email'] . ">\r\n";
    $headers .= "Subject: $subject\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $headers .= "Content-Transfer-Encoding: 8bit\r\n";
    $headers .= "X-Mailer: Zen Zone Spa Contact Form\r\n";
    $headers .= "\r\n";
    
    fwrite($connection, $headers . $body . "\r\n.\r\n");
    $response = fgets($connection, 515);
    
    // Send QUIT
    fwrite($connection, "QUIT\r\n");
    fclose($connection);
    
    // Check if email was accepted
    return substr($response, 0, 3) == '250';
}

/**
 * Fallback: Send email using basic PHP mail()
 */
function sendViaBasicMail($config, $replyToEmail, $subject, $body) {
    // Generate RFC 5322 compliant headers
    $messageId = '<' . uniqid() . '@zenzone.rw>';
    $date = date('r'); // RFC 2822 formatted date
    
    $headers = "Message-ID: $messageId\r\n";
    $headers .= "Date: $date\r\n";
    $headers .= "From: " . $config['from_name'] . " <" . $config['from_email'] . ">\r\n";
    $headers .= "Reply-To: $replyToEmail\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $headers .= "Content-Transfer-Encoding: 8bit\r\n";
    $headers .= "X-Mailer: Zen Zone Spa Contact Form\r\n";
    
    return @mail($config['to_email'], $subject, $body, $headers);
}

/**
 * Send auto-reply confirmation to customer
 */
function sendAutoReply($config, $customerEmail, $customerName) {
    $subject = $config['auto_reply_subject'];
    $body = "Dear $customerName,\n\n";
    $body .= "Thank you for contacting Zen Zone Spa! We have received your inquiry and will get back to you within 24 hours.\n\n";
    $body .= "In the meantime, feel free to call us at +250 730 000 016 if you have any urgent questions.\n\n";
    $body .= "We look forward to helping you relax and rejuvenate!\n\n";
    $body .= "Best regards,\n";
    $body .= "Zen Zone Spa Team\n";
    $body .= "zenzonerw@gmail.com\n";
    $body .= "+250 730 000 016";
    
    // Try to send auto-reply
    try {
        // Create temporary config for auto-reply (send to customer instead of spa)
        $autoReplyConfig = $config;
        $autoReplyConfig['to_email'] = $customerEmail;
        
        if (function_exists('fsockopen')) {
            return sendViaSMTPWithCompliantHeaders($autoReplyConfig, $config['from_email'], $subject, $body);
        } else {
            return sendViaBasicMailWithCompliantHeaders($autoReplyConfig, $config['from_email'], $subject, $body);
        }
    } catch (Exception $e) {
        error_log("Auto-reply failed: " . $e->getMessage());
        return false;
    }
}

/**
 * Send email via SMTP with RFC 5322 compliant headers (for auto-reply)
 */
function sendViaSMTPWithCompliantHeaders($config, $replyToEmail, $subject, $body) {
    // Create SSL context
    $context = stream_context_create([
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        ]
    ]);
    
    // Connect to SMTP server
    $connection = stream_socket_client(
        $config['smtp_security'] . "://" . $config['smtp_server'] . ":" . $config['smtp_port'], 
        $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context
    );
    
    if (!$connection) {
        throw new Exception("Failed to connect to SMTP server: $errstr ($errno)");
    }
    
    // Read server response
    $response = fgets($connection, 515);
    if (substr($response, 0, 3) != '220') {
        throw new Exception("SMTP server not ready: $response");
    }
    
    // SMTP commands
    $commands = [
        "EHLO zenzone.rw\r\n",
        "AUTH LOGIN\r\n",
        base64_encode($config['smtp_username']) . "\r\n",
        base64_encode($config['smtp_password']) . "\r\n",
        "MAIL FROM: <" . $config['from_email'] . ">\r\n",
        "RCPT TO: <" . $config['to_email'] . ">\r\n",
        "DATA\r\n"
    ];
    
    // Execute SMTP commands
    foreach ($commands as $command) {
        fwrite($connection, $command);
        $response = fgets($connection, 515);
        
        // Check for errors
        if (in_array(substr($response, 0, 3), ['500', '501', '502', '503', '504', '550', '551', '552', '553', '554'])) {
            fclose($connection);
            throw new Exception("SMTP Error: $response");
        }
    }
    
    // Generate RFC 5322 compliant headers
    $messageId = '<' . uniqid() . '@zenzone.rw>';
    $date = date('r');
    
    $headers = "Message-ID: $messageId\r\n";
    $headers .= "Date: $date\r\n";
    $headers .= "From: " . $config['from_name'] . " <" . $config['from_email'] . ">\r\n";
    $headers .= "Reply-To: $replyToEmail\r\n";
    $headers .= "To: <" . $config['to_email'] . ">\r\n";
    $headers .= "Subject: $subject\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $headers .= "Content-Transfer-Encoding: 8bit\r\n";
    $headers .= "X-Mailer: Zen Zone Spa Contact Form\r\n";
    $headers .= "\r\n";
    
    fwrite($connection, $headers . $body . "\r\n.\r\n");
    $response = fgets($connection, 515);
    
    // Send QUIT
    fwrite($connection, "QUIT\r\n");
    fclose($connection);
    
    // Check if email was accepted
    return substr($response, 0, 3) == '250';
}

/**
 * Send email via basic mail() with RFC 5322 compliant headers (for auto-reply)
 */
function sendViaBasicMailWithCompliantHeaders($config, $replyToEmail, $subject, $body) {
    // Generate RFC 5322 compliant headers
    $messageId = '<' . uniqid() . '@zenzone.rw>';
    $date = date('r');
    
    $headers = "Message-ID: $messageId\r\n";
    $headers .= "Date: $date\r\n";
    $headers .= "From: " . $config['from_name'] . " <" . $config['from_email'] . ">\r\n";
    $headers .= "Reply-To: $replyToEmail\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $headers .= "Content-Transfer-Encoding: 8bit\r\n";
    $headers .= "X-Mailer: Zen Zone Spa Contact Form\r\n";
    
    return @mail($config['to_email'], $subject, $body, $headers);
}
?> 