<?php
// Ensure no output before session_start
if (ob_get_level()) { ob_end_clean(); }
ob_start();
session_start();
require_once 'config.php';
require_once 'app/classes/NotificationManager.php';
require_once 'app/classes/ContactConfig.php';

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Get form data
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$subject = isset($_POST['subject']) ? trim($_POST['subject']) : '';
$message = isset($_POST['message']) ? trim($_POST['message']) : '';

// Validate input
if (empty($email) || empty($subject) || empty($message)) {
    echo json_encode(['success' => false, 'message' => 'Please fill in all required fields.']);
    exit;
}

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Please enter a valid email address.']);
    exit;
}

// Sanitize input
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$subject = htmlspecialchars($subject, ENT_QUOTES, 'UTF-8');
$message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');

try {
    // Get admin email from ContactConfig (from payment_config table)
    $contactConfig = new ContactConfig($conn);
    $adminEmail = $contactConfig->getContactEmail();
    
    if (empty($adminEmail)) {
        error_log("Contact form error: Admin email not configured in payment_config table");
        echo json_encode(['success' => false, 'message' => 'Email configuration error. Please contact the administrator.']);
        exit;
    }
    
    // Get configured email settings from notification_config table
    $fromEmail = '';
    $fromName = '';
    $smtpHost = '';
    $smtpPort = 587;
    $smtpUsername = '';
    $smtpPassword = '';
    $emailEnabled = false;
    
    $emailResult = mysqli_query($conn, "SELECT * FROM notification_config WHERE type = 'email'");
    if ($emailResult && mysqli_num_rows($emailResult) > 0) {
        $emailData = mysqli_fetch_assoc($emailResult);
        $emailConfigData = json_decode($emailData['config_data'], true) ?: [];
        
        $fromEmail = !empty($emailConfigData['from_email']) ? $emailConfigData['from_email'] : '';
        $fromName = !empty($emailConfigData['from_name']) ? $emailConfigData['from_name'] : '';
        $smtpHost = !empty($emailConfigData['smtp_host']) ? $emailConfigData['smtp_host'] : '';
        $smtpPort = !empty($emailConfigData['smtp_port']) ? intval($emailConfigData['smtp_port']) : 587;
        $smtpUsername = !empty($emailConfigData['smtp_username']) ? $emailConfigData['smtp_username'] : '';
        $smtpPassword = !empty($emailConfigData['smtp_password']) ? $emailConfigData['smtp_password'] : '';
        $emailEnabled = isset($emailConfigData['enabled']) ? (bool)$emailConfigData['enabled'] : false;
    }
    
    // Validate that from_email and from_name are configured
    if (empty($fromEmail) || empty($fromName)) {
        error_log("Contact form error: From email or from name not configured in notification_config table");
        echo json_encode(['success' => false, 'message' => 'Email configuration incomplete. Please contact the administrator.']);
        exit;
    }
    
    // Get user IP and user agent for context
    $userIP = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'Unknown';
    $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Unknown';
    $submissionTime = date('Y-m-d H:i:s');
    
    // Create email subject
    $emailSubject = "Contact Form: " . $subject;
    
    // Create email body with HTML formatting
    $emailBody = "
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white; padding: 20px; border-radius: 8px 8px 0 0; }
        .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
        .info-box { background: white; border-left: 4px solid #3b82f6; padding: 15px; margin: 15px 0; border-radius: 4px; }
        .info-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #e5e7eb; }
        .info-label { font-weight: 600; color: #6b7280; }
        .info-value { color: #111827; }
        .message-box { background: white; border: 1px solid #e5e7eb; padding: 20px; margin: 15px 0; border-radius: 4px; }
        .footer { text-align: center; margin-top: 20px; color: #6b7280; font-size: 12px; }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h2 style='margin: 0;'>📧 New Contact Form Submission</h2>
        </div>
        <div class='content'>
            <p>You have received a new message from the login page contact form.</p>
            
            <div class='info-box'>
                <div class='info-row'>
                    <span class='info-label'>From Email:</span>
                    <span class='info-value'>{$email}</span>
                </div>
                <div class='info-row'>
                    <span class='info-label'>Subject:</span>
                    <span class='info-value'>{$subject}</span>
                </div>
                <div class='info-row'>
                    <span class='info-label'>Submitted:</span>
                    <span class='info-value'>{$submissionTime}</span>
                </div>
                <div class='info-row'>
                    <span class='info-label'>IP Address:</span>
                    <span class='info-value'>{$userIP}</span>
                </div>
            </div>
            
            <div class='message-box'>
                <h3 style='margin-top: 0; color: #111827;'>Message:</h3>
                <p style='white-space: pre-wrap; color: #374151;'>{$message}</p>
            </div>
            
            <div class='footer'>
                <p>This is an automated message from D-Bundles Stores Contact Form.</p>
                <p>© " . date('Y') . " D-Bundles Stores. All rights reserved.</p>
            </div>
        </div>
    </div>
</body>
</html>";
    
    // Use NotificationManager to send email (system already uses this)
    $notificationManager = new NotificationManager($conn);
    $emailSent = $notificationManager->sendEmail($adminEmail, $emailSubject, $emailBody);
    
    if ($emailSent) {
        error_log("Contact form submission sent successfully from: {$email} to: {$adminEmail}");
        echo json_encode(['success' => true, 'message' => 'Your message has been sent successfully! We will get back to you soon.']);
    } else {
        // Check error log for Gmail limit errors
        $errorLogFile = __DIR__ . '/error.log';
        $gmailLimitDetected = false;
        
        if (file_exists($errorLogFile)) {
            $errorLogContent = file_get_contents($errorLogFile);
            // Check last few lines for Gmail limit error
            $lines = explode("\n", $errorLogContent);
            $recentLines = array_slice($lines, -5); // Check last 5 lines
            foreach ($recentLines as $line) {
                if (strpos($line, '550-5.4.5') !== false || 
                    strpos($line, 'Daily user sending limit exceeded') !== false ||
                    strpos($line, 'DATA command failed') !== false && strpos($line, '550') !== false) {
                    $gmailLimitDetected = true;
                    break;
                }
            }
        }
        
        if ($gmailLimitDetected) {
            error_log("Gmail daily sending limit detected. Contact form from: {$email} to: {$adminEmail}");
            echo json_encode([
                'success' => false, 
                'message' => 'Email service temporarily unavailable due to daily sending limit. Please try again tomorrow or contact us directly.'
            ]);
        } else {
            error_log("Failed to send contact form submission from: {$email} to: {$adminEmail}");
            echo json_encode([
                'success' => false, 
                'message' => 'Failed to send message. Please try again later or contact us directly.'
            ]);
        }
    }
    
} catch (Exception $e) {
    error_log("Contact form error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'An error occurred. Please try again later.']);
}

exit;
?>

