<?php
/**
 * Email service using PHP built-in mail() function
 */
require_once 'config_loader.php';
require_once 'Logger.php';

class EmailService {
    
    public function __construct() {
        // No special initialization needed for mail() function
    }
    
    public function sendContactForm($name, $email, $message, $subject = null) {
        try {
            $toEmail = env('MAIL_TO_EMAIL', 'm.geden01@markstechsolution.com');
            $fromEmail = env('MAIL_FROM_EMAIL', 'noreply@markstechsolution.com');
            $fromName = env('MAIL_FROM_NAME', "Mark's Tech Solution");
            
            // Debug: Log email configuration
            Logger::debug('Email service configuration', [
                'to_email' => $toEmail,
                'from_email' => $fromEmail,
                'from_name' => $fromName,
                'php_mail_enabled' => ini_get('mail.add_x_header'),
                'sendmail_path' => ini_get('sendmail_path'),
                'smtp_port' => ini_get('smtp_port')
            ]);
            
            $subject = $subject ?: 'New Contact Form Submission from ' . $name;
            
            $emailBody = "You have received a new contact form submission:\n\n";
            $emailBody .= "Name: " . $this->sanitizeInput($name) . "\n";
            $emailBody .= "Email: " . $this->sanitizeInput($email) . "\n";
            $emailBody .= "Date: " . date('Y-m-d H:i:s') . "\n\n";
            $emailBody .= "Message:\n" . $this->sanitizeInput($message) . "\n";
            
            $headers = [
                'From: ' . $fromName . ' <' . $fromEmail . '>',
                'Reply-To: ' . $name . ' <' . $email . '>',
                'X-Mailer: PHP/' . phpversion(),
                'MIME-Version: 1.0',
                'Content-Type: text/plain; charset=UTF-8'
            ];
            
            $headersString = implode("\r\n", $headers);
            
            // Debug: Log the exact mail() call
            Logger::debug('Attempting to send email', [
                'to' => $toEmail,
                'subject' => $subject,
                'headers' => $headersString
            ]);
            
            $result = mail($toEmail, $subject, $emailBody, $headersString);
            
            // Debug: Log the result
            Logger::debug('Mail function result', [
                'result' => $result,
                'error' => error_get_last()
            ]);
            
            if (!$result) {
                $error = error_get_last();
                throw new Exception('mail() function returned false. Last error: ' . ($error['message'] ?? 'Unknown'));
            }
            
            Logger::info('Contact form email sent successfully', ['email' => $email]);
            
            return true;
        } catch (Exception $e) {
            Logger::error('Failed to send contact form email', [
                'error' => $e->getMessage(),
                'email' => $email,
                'trace' => $e->getTraceAsString()
            ]);
            throw new Exception('Failed to send email. Please try again later.');
        }
    }
    
    private function sanitizeInput($input) {
        return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
    }
}