<?php
/**
 * Email Configuration for cPanel Email Server
 * Settings are loaded from database (site_settings table) with fallback to constants
 */

// Default values (fallback if not set in database)
define('SMTP_HOST_DEFAULT', 'mail.horizondrillingco.com');
define('SMTP_USER_DEFAULT', 'info@horizondrillingco.com');
define('SMTP_PASS_DEFAULT', 'Horizon@drilling254');
define('SMTP_PORT_DEFAULT', 587);
define('SMTP_SECURE_DEFAULT', 'tls');
define('SMTP_FROM_EMAIL_DEFAULT', 'info@horizondrillingco.com');
define('SMTP_FROM_NAME_DEFAULT', 'Horizon Drilling Co. Ltd');

/**
 * Get email configuration from database or use defaults
 */
function getEmailConfig() {
    static $config = null;
    
    if ($config !== null) {
        return $config;
    }
    
    $config = [
        'host' => SMTP_HOST_DEFAULT,
        'user' => SMTP_USER_DEFAULT,
        'pass' => SMTP_PASS_DEFAULT,
        'port' => SMTP_PORT_DEFAULT,
        'secure' => SMTP_SECURE_DEFAULT,
        'from_email' => SMTP_FROM_EMAIL_DEFAULT,
        'from_name' => SMTP_FROM_NAME_DEFAULT
    ];
    
    // Try to load from database
    try {
        require_once __DIR__ . '/database.php';
        $pdo = getDBConnection();
        
        $stmt = $pdo->query("
            SELECT setting_key, setting_value 
            FROM site_settings 
            WHERE setting_key IN (
                'smtp_host', 'smtp_user', 'smtp_pass', 'smtp_port', 
                'smtp_secure', 'smtp_from_email', 'smtp_from_name'
            )
        ");
        
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $key = str_replace('smtp_', '', $row['setting_key']);
            if ($key === 'from_email') {
                $config['from_email'] = $row['setting_value'];
            } elseif ($key === 'from_name') {
                $config['from_name'] = $row['setting_value'];
            } else {
                $config[$key] = $row['setting_value'];
            }
        }
    } catch (Exception $e) {
        // Use defaults if database fails
        error_log("Email config database error: " . $e->getMessage());
    }
    
    return $config;
}

/**
 * Send email using PHPMailer
 */
function sendEmail($to, $subject, $body, $isHTML = true) {
    // Try to use Composer autoload first
    if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
        require_once __DIR__ . '/../vendor/autoload.php';
    } else {
        // Fallback to manual includes
        require_once __DIR__ . '/../vendor/PHPMailer/src/PHPMailer.php';
        require_once __DIR__ . '/../vendor/PHPMailer/src/SMTP.php';
        require_once __DIR__ . '/../vendor/PHPMailer/src/Exception.php';
    }
    
    $mail = new PHPMailer\PHPMailer\PHPMailer(true);
    
    try {
        // Get email config from database or defaults
        $emailConfig = getEmailConfig();
        
        // Server settings
        $mail->isSMTP();
        $mail->Host = $emailConfig['host'];
        $mail->SMTPAuth = true;
        $mail->Username = $emailConfig['user'];
        $mail->Password = $emailConfig['pass'];
        $mail->SMTPSecure = $emailConfig['secure'];
        $mail->Port = (int)$emailConfig['port'];
        $mail->CharSet = 'UTF-8';
        
        // Recipients
        $mail->setFrom($emailConfig['from_email'], $emailConfig['from_name']);
        $mail->addAddress($to);
        
        // Content
        $mail->isHTML($isHTML);
        $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;
    }
}

/**
 * Send contact form email
 */
function sendContactEmail($data) {
    $to = 'info@horizondrillingco.com'; // Admin email
    $subject = 'New Contact Form Submission - Horizon Drilling';
    
    $body = "
    <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: #FF6B35; color: white; padding: 20px; text-align: center; }
            .content { background: #f9f9f9; padding: 20px; }
            .field { margin-bottom: 15px; }
            .label { font-weight: bold; color: #0A1828; }
            .value { margin-top: 5px; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>New Contact Form Submission</h2>
            </div>
            <div class='content'>
                <div class='field'>
                    <div class='label'>Name:</div>
                    <div class='value'>{$data['name']}</div>
                </div>
                <div class='field'>
                    <div class='label'>Email:</div>
                    <div class='value'>{$data['email']}</div>
                </div>
                <div class='field'>
                    <div class='label'>Phone:</div>
                    <div class='value'>{$data['phone']}</div>
                </div>
                <div class='field'>
                    <div class='label'>Service Interest:</div>
                    <div class='value'>{$data['service']}</div>
                </div>
                <div class='field'>
                    <div class='label'>Message:</div>
                    <div class='value'>{$data['message']}</div>
                </div>
            </div>
        </div>
    </body>
    </html>
    ";
    
    return sendEmail($to, $subject, $body);
}
