<?php
/**
 * Email Helper Functions
 * Reusable email sending functions for the ENT Hospital Management System
 * Uses PHPMailer with settings from system_settings table
 */

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Include PHPMailer if not already included
if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) {
    require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/Exception.php';
    require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/PHPMailer.php';
    require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/SMTP.php';
}

/**
 * Get email settings from database
 * @param mysqli $conn Database connection
 * @return array Email settings
 */
function getEmailSettings($conn) {
    $sql = "SELECT setting_key, setting_value FROM system_settings WHERE category = 'email'";
    $result = $conn->query($sql);
    
    $settings = [];
    while ($row = $result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    return $settings;
}

/**
 * Get hospital information from database
 * @param mysqli $conn Database connection
 * @return array Hospital information
 */
function getHospitalInfo($conn) {
    $sql = "SELECT setting_key, setting_value FROM system_settings WHERE category = 'hospital'";
    $result = $conn->query($sql);
    
    $info = [
        'name' => 'ENT Hospital',
        'email' => '',
        'phone' => '',
        'address' => ''
    ];
    
    while ($row = $result->fetch_assoc()) {
        switch ($row['setting_key']) {
            case 'hospital_name':
                $info['name'] = $row['setting_value'];
                break;
            case 'hospital_email':
                $info['email'] = $row['setting_value'];
                break;
            case 'hospital_phone':
                $info['phone'] = $row['setting_value'];
                break;
            case 'hospital_address':
                $info['address'] = $row['setting_value'];
                break;
        }
    }
    
    return $info;
}

/**
 * Initialize PHPMailer with system settings
 * @param mysqli $conn Database connection
 * @return array ['success' => bool, 'mailer' => PHPMailer|null, 'message' => string]
 */
function initMailer($conn) {
    $email_settings = getEmailSettings($conn);
    
    // Check if email is enabled
    if (empty($email_settings['email_enabled']) || $email_settings['email_enabled'] != '1') {
        return [
            'success' => false,
            'mailer' => null,
            'message' => 'Email notifications are disabled in system settings'
        ];
    }
    
    // Validate required settings
    $required_settings = ['smtp_host', 'smtp_port', 'smtp_username', 'smtp_password', 'email_from'];
    foreach ($required_settings as $setting) {
        if (empty($email_settings[$setting])) {
            return [
                'success' => false,
                'mailer' => null,
                'message' => "Email configuration incomplete: {$setting} not set"
            ];
        }
    }
    
    try {
        $mail = new PHPMailer(true);
        
        // Server settings
        $mail->isSMTP();
        $mail->Host = $email_settings['smtp_host'];
        $mail->SMTPAuth = true;
        $mail->Username = $email_settings['smtp_username'];
        $mail->Password = $email_settings['smtp_password'];
        
        // Encryption
        if (!empty($email_settings['smtp_encryption']) && $email_settings['smtp_encryption'] == 'ssl') {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        }
        
        $mail->Port = (int)$email_settings['smtp_port'];
        
        // Set from address
        $mail->setFrom(
            $email_settings['email_from'],
            $email_settings['email_from_name'] ?? 'ENT Hospital'
        );
        
        // Optional: Add reply-to if different from sender
        if (!empty($email_settings['email_reply_to'])) {
            $mail->addReplyTo($email_settings['email_reply_to']);
        }
        
        return [
            'success' => true,
            'mailer' => $mail,
            'message' => 'Mailer initialized successfully'
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'mailer' => null,
            'message' => 'Failed to initialize mailer: ' . $e->getMessage()
        ];
    }
}

/**
 * Get email template wrapper
 * @param string $content HTML content to wrap
 * @param string $title Email title
 * @param mysqli $conn Database connection
 * @return string Complete HTML email
 */
function getEmailTemplate($content, $title, $conn) {
    $hospital_info = getHospitalInfo($conn);
    
    return '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 600px;
            margin: 20px auto;
            background: #ffffff;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .header h1 {
            margin: 0;
            font-size: 24px;
        }
        .content {
            padding: 30px;
        }
        .footer {
            background: #f8f9fa;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #6c757d;
            border-top: 1px solid #dee2e6;
        }
        .button {
            display: inline-block;
            padding: 12px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white !important;
            text-decoration: none;
            border-radius: 5px;
            margin: 20px 0;
            font-weight: bold;
        }
        .info-box {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 15px;
            margin: 15px 0;
            border-radius: 5px;
        }
        .warning-box {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin: 15px 0;
            border-radius: 5px;
        }
        .success-box {
            background: #d4edda;
            border-left: 4px solid #28a745;
            padding: 15px;
            margin: 15px 0;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>' . htmlspecialchars($title) . '</h1>
            <p style="margin: 10px 0 0 0; opacity: 0.9;">' . htmlspecialchars($hospital_info['name']) . '</p>
        </div>
        
        <div class="content">
            ' . $content . '
        </div>
        
        <div class="footer">
            <p style="margin: 0;">
                <strong>' . htmlspecialchars($hospital_info['name']) . '</strong><br>';
    
    if (!empty($hospital_info['address'])) {
        $html .= htmlspecialchars($hospital_info['address']) . '<br>';
    }
    if (!empty($hospital_info['phone'])) {
        $html .= 'Phone: ' . htmlspecialchars($hospital_info['phone']) . '<br>';
    }
    if (!empty($hospital_info['email'])) {
        $html .= 'Email: ' . htmlspecialchars($hospital_info['email']) . '<br>';
    }
    
    $html .= '
            </p>
            <p style="margin: 10px 0 0 0;">
                This is an automated message, please do not reply to this email.
            </p>
            <p style="margin: 10px 0 0 0;">
                © ' . date('Y') . ' ' . htmlspecialchars($hospital_info['name']) . '. All rights reserved.
            </p>
        </div>
    </div>
</body>
</html>';
    
    return $html;
}

/**
 * Send a simple email
 * @param mysqli $conn Database connection
 * @param string $to_email Recipient email
 * @param string $to_name Recipient name
 * @param string $subject Email subject
 * @param string $html_body HTML email body
 * @param string $plain_body Plain text email body
 * @return array ['success' => bool, 'message' => string]
 */
function sendEmail($conn, $to_email, $to_name, $subject, $html_body, $plain_body = '') {
    $mailer_init = initMailer($conn);
    
    if (!$mailer_init['success']) {
        return $mailer_init;
    }
    
    $mail = $mailer_init['mailer'];
    
    try {
        // Recipients
        $mail->addAddress($to_email, $to_name);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $html_body;
        
        if (!empty($plain_body)) {
            $mail->AltBody = $plain_body;
        } else {
            // Strip HTML tags for plain text version
            $mail->AltBody = strip_tags($html_body);
        }
        
        // Send email
        $mail->send();
        
        return ['success' => true, 'message' => 'Email sent successfully'];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Email sending failed: ' . $mail->ErrorInfo];
    }
}

/**
 * Send appointment reminder email
 * @param mysqli $conn Database connection
 * @param array $appointment Appointment details
 * @return array ['success' => bool, 'message' => string]
 */
function sendAppointmentReminderEmail($conn, $appointment) {
    $content = '
        <h2 style="color: #333; margin-top: 0;">Appointment Reminder</h2>
        
        <p>Dear ' . htmlspecialchars($appointment['patient_name']) . ',</p>
        
        <p>This is a friendly reminder about your upcoming appointment:</p>
        
        <div class="info-box">
            <p style="margin: 5px 0;"><strong>Date:</strong> ' . date('l, F j, Y', strtotime($appointment['appointment_date'])) . '</p>
            <p style="margin: 5px 0;"><strong>Time:</strong> ' . date('g:i A', strtotime($appointment['appointment_time'])) . '</p>
            <p style="margin: 5px 0;"><strong>Doctor:</strong> Dr. ' . htmlspecialchars($appointment['doctor_name']) . '</p>
            <p style="margin: 5px 0;"><strong>Department:</strong> ' . htmlspecialchars($appointment['department']) . '</p>
        </div>
        
        <p><strong>Important:</strong></p>
        <ul>
            <li>Please arrive 15 minutes before your appointment time</li>
            <li>Bring your insurance card and valid ID</li>
            <li>If you need to cancel or reschedule, please contact us at least 24 hours in advance</li>
        </ul>
        
        <p>We look forward to seeing you!</p>';
    
    $html_body = getEmailTemplate($content, 'Appointment Reminder', $conn);
    
    $plain_body = "Appointment Reminder\n\n"
                . "Dear {$appointment['patient_name']},\n\n"
                . "This is a reminder about your upcoming appointment:\n\n"
                . "Date: " . date('l, F j, Y', strtotime($appointment['appointment_date'])) . "\n"
                . "Time: " . date('g:i A', strtotime($appointment['appointment_time'])) . "\n"
                . "Doctor: Dr. {$appointment['doctor_name']}\n"
                . "Department: {$appointment['department']}\n\n"
                . "Please arrive 15 minutes early.\n\n"
                . "Thank you!";
    
    return sendEmail(
        $conn,
        $appointment['patient_email'],
        $appointment['patient_name'],
        'Appointment Reminder - ' . date('M j, Y', strtotime($appointment['appointment_date'])),
        $html_body,
        $plain_body
    );
}

/**
 * Send payment receipt email
 * @param mysqli $conn Database connection
 * @param array $payment Payment details
 * @return array ['success' => bool, 'message' => string]
 */
function sendPaymentReceiptEmail($conn, $payment) {
    $content = '
        <h2 style="color: #333; margin-top: 0;">Payment Receipt</h2>
        
        <p>Dear ' . htmlspecialchars($payment['patient_name']) . ',</p>
        
        <p>Thank you for your payment. Here are the details:</p>
        
        <div class="success-box">
            <p style="margin: 5px 0;"><strong>Receipt Number:</strong> ' . htmlspecialchars($payment['receipt_number']) . '</p>
            <p style="margin: 5px 0;"><strong>Date:</strong> ' . date('F j, Y g:i A', strtotime($payment['payment_date'])) . '</p>
            <p style="margin: 5px 0;"><strong>Amount Paid:</strong> KES ' . number_format($payment['amount'], 2) . '</p>
            <p style="margin: 5px 0;"><strong>Payment Method:</strong> ' . htmlspecialchars($payment['payment_method']) . '</p>
        </div>
        
        <p>This receipt serves as proof of payment. Please keep it for your records.</p>
        
        <p>If you have any questions about this payment, please contact our billing department.</p>';
    
    $html_body = getEmailTemplate($content, 'Payment Receipt', $conn);
    
    $plain_body = "Payment Receipt\n\n"
                . "Dear {$payment['patient_name']},\n\n"
                . "Thank you for your payment.\n\n"
                . "Receipt Number: {$payment['receipt_number']}\n"
                . "Date: " . date('F j, Y g:i A', strtotime($payment['payment_date'])) . "\n"
                . "Amount: KES " . number_format($payment['amount'], 2) . "\n"
                . "Payment Method: {$payment['payment_method']}\n\n"
                . "Thank you!";
    
    return sendEmail(
        $conn,
        $payment['patient_email'],
        $payment['patient_name'],
        'Payment Receipt - ' . $payment['receipt_number'],
        $html_body,
        $plain_body
    );
}

/**
 * Send test results notification email
 * @param mysqli $conn Database connection
 * @param array $test_info Test details
 * @return array ['success' => bool, 'message' => string]
 */
function sendTestResultsEmail($conn, $test_info) {
    $login_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") 
                . "://$_SERVER[HTTP_HOST]" . dirname($_SERVER['PHP_SELF']) . '/login.php';
    
    $content = '
        <h2 style="color: #333; margin-top: 0;">Test Results Available</h2>
        
        <p>Dear ' . htmlspecialchars($test_info['patient_name']) . ',</p>
        
        <p>Your test results are now available for review.</p>
        
        <div class="info-box">
            <p style="margin: 5px 0;"><strong>Test:</strong> ' . htmlspecialchars($test_info['test_name']) . '</p>
            <p style="margin: 5px 0;"><strong>Test Date:</strong> ' . date('F j, Y', strtotime($test_info['test_date'])) . '</p>
            <p style="margin: 5px 0;"><strong>Status:</strong> ' . htmlspecialchars($test_info['status']) . '</p>
        </div>
        
        <p>Please log in to your patient portal to view your complete results.</p>
        
        <center>
            <a href="' . $login_url . '" class="button">View Results</a>
        </center>
        
        <p style="margin-top: 30px; font-size: 14px; color: #6c757d;">
            If you have any questions about your results, please contact your doctor or our medical staff.
        </p>';
    
    $html_body = getEmailTemplate($content, 'Test Results Available', $conn);
    
    $plain_body = "Test Results Available\n\n"
                . "Dear {$test_info['patient_name']},\n\n"
                . "Your test results are now available.\n\n"
                . "Test: {$test_info['test_name']}\n"
                . "Test Date: " . date('F j, Y', strtotime($test_info['test_date'])) . "\n\n"
                . "Please log in to view your results.\n\n"
                . "Thank you!";
    
    return sendEmail(
        $conn,
        $test_info['patient_email'],
        $test_info['patient_name'],
        'Test Results Available',
        $html_body,
        $plain_body
    );
}
?>