<?php
/**
 * Email Handler for Contact Form
 */

// Prevent direct access
if (!defined('EMAIL_HANDLER_ALLOWED')) {
    http_response_code(403);
    die('Direct access forbidden');
}

class SecureEmailHandler {
    
    private const MAX_MESSAGE_LENGTH = 5000;
    private const MAX_SUBJECT_LENGTH = 200;
    private const MAX_NAME_LENGTH = 100;
    private const RATE_LIMIT_WINDOW = 300; // 5 minutes
    private const MAX_REQUESTS_PER_WINDOW = 3;
    
    private string $recipientEmail;
    private array $errors = [];
    
    public function __construct(string $recipientEmail) {
        $this->recipientEmail = filter_var($recipientEmail, FILTER_VALIDATE_EMAIL);
        if (!$this->recipientEmail) {
            throw new InvalidArgumentException('Invalid recipient email address');
        }
    }
    
    /**
     * Process contact form submission with comprehensive security checks
     * 
     * @return array Response array with success status and message
     */
    public function processContactForm(): array {
        try {
            $this->checkRequestMethod();
            $this->checkRateLimit();
            $this->checkCSRFToken();
            
            $sanitizedData = $this->validateAndSanitizeInput();
            $emailSent = $this->sendEmail($sanitizedData);
            
            if ($emailSent) {
                $this->logSuccess($sanitizedData['email']);
                return [
                    'success' => true,
                    'message' => t('contact_form.success_message', 'Your message has been sent successfully! We will contact you soon.')
                ];
            } else {
                $this->logError('Email delivery failed', $sanitizedData['email']);
                return [
                    'success' => false,
                    'message' => t('contact_form.error_message', 'An error occurred while sending your message. Please try again.')
                ];
            }
            
        } catch (Exception $e) {
            $this->logError($e->getMessage(), $_POST['email'] ?? 'unknown');
            return [
                'success' => false,
                'message' => t('contact_form.error_message', 'An error occurred while sending your message. Please try again.')
            ];
        }
    }
    
    /**
     * Validate HTTP request method is POST
     * 
     * @throws Exception If request method is not POST
     */
    private function checkRequestMethod(): void {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            throw new Exception('Invalid HTTP request method. Only POST requests are allowed.');
        }
    }
    
    /**
     * Implement rate limiting to prevent spam and abuse
     * Uses file-based storage for simplicity (Redis/Memcached recommended for production)
     * 
     * @throws Exception If rate limit is exceeded
     */
    private function checkRateLimit(): void {
        $clientIP = $this->getClientIP();
        $rateLimitKey = 'contact_rate_limit_' . md5($clientIP);
        $rateLimitFile = sys_get_temp_dir() . '/' . $rateLimitKey;
        
        $currentTime = time();
        $requestData = ['requests' => [$currentTime]];
        
        if (file_exists($rateLimitFile)) {
            $existingData = json_decode(file_get_contents($rateLimitFile), true);
            
            $validRequests = array_filter($existingData['requests'] ?? [], function($timestamp) use ($currentTime) {
                return ($currentTime - $timestamp) < self::RATE_LIMIT_WINDOW;
            });
            
            if (count($validRequests) >= self::MAX_REQUESTS_PER_WINDOW) {
                throw new Exception('Rate limit exceeded. Please wait before submitting another message.');
            }
            
            $validRequests[] = $currentTime;
            $requestData = ['requests' => array_values($validRequests)];
        }
        
        file_put_contents($rateLimitFile, json_encode($requestData), LOCK_EX);
    }
    
    /**
     * Validate CSRF token to prevent cross-site request forgery attacks
     * 
     * @throws Exception If CSRF token is invalid or missing
     */
    private function checkCSRFToken(): void {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        $submittedToken = $_POST['csrf_token'] ?? '';
        $sessionToken = $_SESSION['csrf_token'] ?? '';
        
        if (empty($submittedToken) || empty($sessionToken)) {
            throw new Exception('CSRF token is missing. Please refresh the page and try again.');
        }
        
        if (!hash_equals($sessionToken, $submittedToken)) {
            throw new Exception('Invalid CSRF token. Please refresh the page and try again.');
        }
    }
    
    /**
     * Validate and sanitize all form input data with comprehensive checks
     * 
     * @return array Sanitized and validated form data
     * @throws Exception If validation fails
     */
    private function validateAndSanitizeInput(): array {
        $sanitizedData = [];
        $this->errors = []; // Reset errors array
        
        $firstName = trim($_POST['firstName'] ?? '');
        $this->validateName($firstName, 'First name', 'firstName');
        $sanitizedData['firstName'] = htmlspecialchars($firstName, ENT_QUOTES, 'UTF-8');
        
        $lastName = trim($_POST['lastName'] ?? '');
        $this->validateName($lastName, 'Last name', 'lastName');
        $sanitizedData['lastName'] = htmlspecialchars($lastName, ENT_QUOTES, 'UTF-8');
        
        $email = trim($_POST['email'] ?? '');
        $this->validateEmail($email);
        $sanitizedData['email'] = filter_var($email, FILTER_SANITIZE_EMAIL);
        
        $subject = trim($_POST['subject'] ?? '');
        $this->validateSubject($subject);
        $sanitizedData['subject'] = htmlspecialchars($subject, ENT_QUOTES, 'UTF-8');
        
        $message = trim($_POST['message'] ?? '');
        $this->validateMessage($message);
        $sanitizedData['message'] = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
        
        if (!empty($this->errors)) {
            throw new Exception('Validation failed: ' . implode(', ', $this->errors));
        }
        
        return $sanitizedData;
    }
    
    /**
     * Validate name fields (first name, last name)
     */
    private function validateName(string $name, string $fieldLabel, string $fieldName): void {
        if (empty($name)) {
            $this->errors[] = "{$fieldLabel} is required";
        } elseif (strlen($name) > self::MAX_NAME_LENGTH) {
            $this->errors[] = "{$fieldLabel} is too long (max " . self::MAX_NAME_LENGTH . " characters)";
        } elseif (!preg_match('/^[\p{L}\p{M}\s\-\'\.]+$/u', $name)) {
            $this->errors[] = "{$fieldLabel} contains invalid characters";
        }
    }
    
    /**
     * Validate email address
     */
    private function validateEmail(string $email): void {
        if (empty($email)) {
            $this->errors[] = 'Email address is required';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->errors[] = 'Email address format is invalid';
        } elseif (strlen($email) > 254) { // RFC 5321 limit
            $this->errors[] = 'Email address is too long (max 254 characters)';
        }
    }
    
    /**
     * Validate subject field
     */
    private function validateSubject(string $subject): void {
        if (empty($subject)) {
            $this->errors[] = 'Subject is required';
        } elseif (strlen($subject) > self::MAX_SUBJECT_LENGTH) {
            $this->errors[] = 'Subject is too long (max ' . self::MAX_SUBJECT_LENGTH . ' characters)';
        }
    }
    
    /**
     * Validate message field
     */
    private function validateMessage(string $message): void {
        if (empty($message)) {
            $this->errors[] = 'Message is required';
        } elseif (strlen($message) > self::MAX_MESSAGE_LENGTH) {
            $this->errors[] = 'Message is too long (max ' . self::MAX_MESSAGE_LENGTH . ' characters)';
        }
    }
    
    /**
     * Send email with secure headers and HTML template
     * 
     * @param array $data Sanitized form data
     * @return bool True if email was sent successfully
     */
    private function sendEmail(array $data): bool {
        $emailSubject = 'New Contact Message from Altoukhi Website: ' . $data['subject'];
        $htmlEmailBody = $this->buildEmailTemplate($data);
        // Keep headers minimal to reduce spam score
        $emailHeaders = [
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=UTF-8',
            'From: ' . $this->encodeEmailHeader('Altoukhi Contact Form') . ' <noreply@altoukhi.com>',
            'Reply-To: ' . $this->encodeEmailHeader($data['firstName'] . ' ' . $data['lastName']) . ' <' . $data['email'] . '>',
            'X-Mailer: Altoukhi Website Contact Form'
        ];

        return mail(
            $this->recipientEmail,
            $emailSubject,
            $htmlEmailBody,
            implode("\r\n", $emailHeaders),
            '-f noreply@altoukhi.com'
        );
    }
    
    /**
     * Build complete professional HTML email template
     * Consolidated all email template functions into one comprehensive method
     * 
     * @param array $data Sanitized form data
     * @return string Complete HTML email template
     */
    private function buildEmailTemplate(array $data): string {
        $currentDateTime = date('Y-m-d H:i:s');
        $clientIP = $this->getClientIP();
        
        $basePrefix = compute_base_prefix();
        $logoUrl = 'https://' . $_SERVER['HTTP_HOST'] . $basePrefix . '/assets/img/logo.png';
        return '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
    <title>New Contact Message - Altoukhi</title>
    <!--[if !mso]><!-->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!--<![endif]-->
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    
    <!-- CSS Styles -->
    <style type="text/css">
        #outlook a { padding:0; }
        body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
        table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
        img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
        p { display:block;margin:13px 0; }
    </style>
    <!--[if mso]>
    <noscript>
    <xml>
    <o:OfficeDocumentSettings>
      <o:AllowPNG/>
      <o:PixelsPerInch>96</o:PixelsPerInch>
    </o:OfficeDocumentSettings>
    </xml>
    </noscript>
    <![endif]-->
    <!--[if lte mso 11]>
    <style type="text/css">
      .email-column-fix { width:100% !important; }
    </style>
    <![endif]-->
    <style type="text/css">
        @media only screen and (min-width:480px) {
            .email-column-full { width:100% !important; max-width: 100%; }
        }
        @media all and (max-width: 768px) {
            body { background-color: #FFFFFF !important; }
            .base-layout-root { background-color: #FFFFFF !important; }
        }
        .card > table > tbody > tr > td {
            border-radius: 12px !important;
            padding: 36px 40px !important;
        }
        @media all and (max-width: 1024px) {
            .card > table > tbody > tr > td { padding: 28px 32px !important; }
        }
        @media all and (max-width: 768px) {
            .card > table > tbody > tr > td { border-radius: 9px !important; padding: 20px 24px !important; }
        }
        @media all and (max-width: 520px) {
            .card > table > tbody > tr > td { padding: 14px 16px !important; }
        }
        .email-header > table > tbody > tr > td {
            border-radius: 12px 12px 0px 0px !important;
            padding: 32px !important;
        }
        @media all and (max-width: 1024px) {
            .email-header > table > tbody > tr > td { padding: 24px 24px 0px !important; }
        }
        @media all and (max-width: 768px) {
            .email-header > table > tbody > tr > td { border-radius: 9px 9px 0px 0px !important; padding: 16px 16px 0px !important; }
        }
        @media all and (max-width: 520px) {
            .email-header > table > tbody > tr > td { padding: 8px 8px 0px !important; }
        }
        .email-content > table > tbody > tr > td {
            border-radius: 0px 0px 12px 12px !important;
            padding-top: 0px !important;
        }
        @media all and (max-width: 768px) {
            .email-content > table > tbody > tr > td { border-radius: 0px 0px 9px 9px !important; }
        }
        .image td { width: 100% !important; }
    </style>
    
    <meta name="x-apple-disable-message-reformatting">
    <meta content="light" name="color-scheme">
    <meta content="light" name="supported-color-schemes">
</head>
<body style="word-spacing:normal;background-color:#FCFCFC;">
    <!-- Hidden Preview Text -->
    <div style="display:none;font-size:1px;color:#ffffff;line-height:1px;max-height:0px;max-width:0px;opacity:0;overflow:hidden;">
        New contact message from ' . $data['firstName'] . ' ' . $data['lastName'] . ' regarding: ' . $data['subject'] . '
    </div>
    
    <!-- Email Body -->
    <div class="base-layout-root" style="background-color:#FCFCFC;">
        
        <!-- Header Section with Logo -->
        <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
            <tbody>
                <tr>
                    <td>
                        <div style="margin:0px auto;max-width:674px;">
                            <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
                                <tbody>
                                    <tr>
                                        <td style="direction:ltr;font-size:0px;padding:0;padding-left:16px;padding-right:16px;padding-top:32px;text-align:center;">
                                            <div class="email-column card email-header" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
                                                <table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%" style="border-collapse: separate;">
                                                    <tbody>
                                                        <tr>
                                                            <td style="background-color:#FFFFFF;border:1px solid #e0e0e0;border-bottom:none;border-radius:12px 12px 0px 0px;vertical-align:top;padding:28px 32px 0px;">
                                                                <!-- Altoukhi Logo -->
                                                                <div style="text-align:center;margin:0 auto;">
                                                                    <img src="' . $logoUrl . '" alt="Altoukhi Logo" width="120" height="80" style="border:0;display:block;outline:none;text-decoration:none;margin:0 auto;max-width:120px;height:auto;">
                                                                </div>
                                                                <table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%">
                                                                    <tbody>
                                                                        <tr>
                                                                            <td style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="height:16px;line-height:16px;">&nbsp;</div>
                                                                            </td>
                                                                        </tr>
                                                                    </tbody>
                                                                </table>
                                                            </td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
        
        <!-- Main Content Section -->
        <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
            <tbody>
                <tr>
                    <td>
                        <div style="margin:0px auto;max-width:674px;">
                            <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
                                <tbody>
                                    <tr>
                                        <td style="direction:ltr;font-size:0px;padding:0;padding-bottom:24px;padding-left:16px;padding-right:16px;text-align:center;">
                                            <div class="email-column card email-content" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
                                                <table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%" style="border-collapse: separate;">
                                                    <tbody>
                                                        <tr>
                                                            <td style="background-color:#FFFFFF;border:1px solid #e0e0e0;border-radius:0px 0px 12px 12px;border-top:none;vertical-align:top;padding:0px 40px 36px;">
                                                                <table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%">
                                                                    <tbody>
                                                                        <!-- Title -->
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:24px;font-weight:600;line-height:30px;text-align:left;color:#202020;">
                                                                                    New Contact Message
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                        <!-- Spacer -->
                                                                        <tr>
                                                                            <td style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="height:16px;line-height:16px;">&nbsp;</div>
                                                                            </td>
                                                                        </tr>
                                                                        <!-- Description -->
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:16px;line-height:24px;text-align:left;color:#202020;">
                                                                                    You have received a new contact message from your Altoukhi website. Here are the details:
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                        <!-- Spacer -->
                                                                        <tr>
                                                                            <td style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="height:24px;line-height:24px;">&nbsp;</div>
                                                                            </td>
                                                                        </tr>
                                                                        
                                                                        <!-- Contact Details -->
                                                                        <!-- FROM Section -->
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:14px;font-weight:600;line-height:20px;text-align:left;color:#646464;">
                                                                                    FROM
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:18px;font-weight:500;line-height:24px;text-align:left;color:#202020;">
                                                                                    ' . $data['firstName'] . ' ' . $data['lastName'] . '
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:16px;line-height:22px;text-align:left;color:#646464;">
                                                                                    ' . $data['email'] . '
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="height:20px;line-height:20px;">&nbsp;</div>
                                                                            </td>
                                                                        </tr>
                                                                        
                                                                        <!-- SUBJECT Section -->
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:14px;font-weight:600;line-height:20px;text-align:left;color:#646464;">
                                                                                    SUBJECT
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:18px;font-weight:500;line-height:24px;text-align:left;color:#202020;">
                                                                                    ' . $data['subject'] . '
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="height:20px;line-height:20px;">&nbsp;</div>
                                                                            </td>
                                                                        </tr>
                                                                        
                                                                        <!-- MESSAGE Section -->
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:14px;font-weight:600;line-height:20px;text-align:left;color:#646464;">
                                                                                    MESSAGE
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:16px;line-height:24px;text-align:left;color:#202020;white-space:pre-wrap;">
' . nl2br($data['message']) . '
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                        
                                                                        <!-- Separator -->
                                                                        <tr>
                                                                            <td style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="height:32px;line-height:32px;">&nbsp;</div>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td align="center" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <p style="border-top:solid 1px #d9d9d9;font-size:1px;margin:0px auto;width:100%;"></p>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="height:32px;line-height:32px;">&nbsp;</div>
                                                                            </td>
                                                                        </tr>
                                                                        
                                                                        <!-- Footer Info -->
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:12px;line-height:18px;text-align:left;color:#646464;">
                                                                                    Sent: ' . $currentDateTime . ' | IP: ' . $clientIP . '
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="height:12px;line-height:12px;">&nbsp;</div>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td align="left" style="font-size:0px;padding:0;word-break:break-word;">
                                                                                <div style="font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Helvetica, Arial, sans-serif;font-size:12px;line-height:18px;text-align:left;color:#646464;">
                                                                                    This message was sent from the Altoukhi website contact form. You can reply directly to this email to respond to the sender.
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                    </tbody>
                                                                </table>
                                                            </td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>';
    }
    
    /**
     * Safely encode email header text for international characters
     * 
     * @param string $text Text to encode
     * @return string Base64 encoded header
     */
    private function encodeEmailHeader(string $text): string {
        return '=?UTF-8?B?' . base64_encode($text) . '?=';
    }
    
    /**
     * Get client IP address with proxy support and validation
     * 
     * @return string Client IP address or 'unknown' if not determinable
     */
    private function getClientIP(): string {
        $ipHeaders = [
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_REAL_IP', 
            'HTTP_CLIENT_IP',
            'REMOTE_ADDR'
        ];
        
        foreach ($ipHeaders as $header) {
            if (!empty($_SERVER[$header])) {
                $ips = explode(',', $_SERVER[$header]);
                $clientIP = trim($ips[0]);
                
                if (filter_var($clientIP, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $clientIP;
                }
            }
        }
        
        return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    }
    
    /**
     * Log successful form submissions for monitoring
     * 
     * @param string $email Sender's email address
     */
    private function logSuccess(string $email): void {
        $logData = [
            'timestamp' => date('Y-m-d H:i:s'),
            'ip_address' => $this->getClientIP(),
            'sender_email' => $email,
            'status' => 'success',
            'user_agent' => substr($_SERVER['HTTP_USER_AGENT'] ?? 'unknown', 0, 200)
        ];
        
        $this->writeLog($logData);
    }
    
    /**
     * Log errors and failed attempts for security monitoring
     * 
     * @param string $errorMessage Error description
     * @param string $email Sender's email address
     */
    private function logError(string $errorMessage, string $email): void {
        $logData = [
            'timestamp' => date('Y-m-d H:i:s'),
            'ip_address' => $this->getClientIP(),
            'sender_email' => $email,
            'status' => 'error',
            'error_message' => $errorMessage,
            'user_agent' => substr($_SERVER['HTTP_USER_AGENT'] ?? 'unknown', 0, 200)
        ];
        
        $this->writeLog($logData);
    }
    
    /**
     * Write log entry to secure log file with proper permissions
     * 
     * @param array $logEntry Log data to write
     */
    private function writeLog(array $logEntry): void {
        $logFile = __DIR__ . '/../logs/contact_form.log';
        $logDirectory = dirname($logFile);
        
        if (!is_dir($logDirectory)) {
            mkdir($logDirectory, 0755, true);
        }
        
        $logLine = json_encode($logEntry, JSON_UNESCAPED_UNICODE) . "\n";
        file_put_contents($logFile, $logLine, FILE_APPEND | LOCK_EX);
    }
}

/**
 * Generate secure CSRF token for form protection
 * 
 * @return string 64-character hexadecimal CSRF token
 */
function generateCSRFToken(): string {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    
    return $_SESSION['csrf_token'];
}
?>
