<?php
/**
 * Email Notification System
 * 
 * Handles sending email notifications for appointments and system events.
 */

require_once 'Response.php';

class Email {
    private $db;
    private $response;

    public function __construct($database) {
        $this->db = $database;
        $this->response = new Response();
    }

    /**
     * Get email settings from system settings
     */
    private function getEmailSettings() {
        try {
            $stmt = $this->db->prepare("
                SELECT setting_key, setting_value 
                FROM system_settings 
                WHERE setting_key IN ('smtp_host', 'smtp_port', 'smtp_username', 'smtp_password', 'smtp_encryption', 'admin_email', 'company_name', 'company_email')
            ");
            $stmt->execute();
            $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
            
            return [
                'smtp_host' => $settings['smtp_host'] ?? '',
                'smtp_port' => $settings['smtp_port'] ?? '587',
                'smtp_username' => $settings['smtp_username'] ?? '',
                'smtp_password' => $settings['smtp_password'] ?? '',
                'smtp_encryption' => $settings['smtp_encryption'] ?? 'tls',
                'admin_email' => $settings['admin_email'] ?? 'admin@alrunan.com',
                'company_name' => $settings['company_name'] ?? 'Al-Runan Llumar Authorized Fitment Centre',
                'company_email' => $settings['company_email'] ?? 'info@alrunan.com'
            ];
        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * Send appointment notification email
     */
    public function sendAppointmentNotification($appointmentData) {
        $settings = $this->getEmailSettings();
        
        // Check if email settings are configured
        if (empty($settings['smtp_host']) || empty($settings['smtp_username'])) {
            error_log('Email settings not configured');
            return false;
        }

        $subject = "New Appointment Booking - " . $settings['company_name'];
        
        $body = $this->buildAppointmentEmailBody($appointmentData, $settings);
        
        $headers = [
            'From: ' . $settings['company_email'],
            'Reply-To: ' . $settings['company_email'],
            'Content-Type: text/html; charset=UTF-8',
            'X-Mailer: PHP/' . phpversion()
        ];

        try {
            // Send to admin
            $adminSent = $this->sendEmail($settings['admin_email'], $subject, $body, $headers, $settings);
            
            // Send to customer if email is provided
            $customerSent = false;
            if (!empty($appointmentData['customer_email'])) {
                $customerSubject = "Appointment Confirmation - " . $settings['company_name'];
                $customerBody = $this->buildCustomerAppointmentEmailBody($appointmentData, $settings);
                $customerSent = $this->sendEmail($appointmentData['customer_email'], $customerSubject, $customerBody, $headers, $settings);
            }

            return $adminSent || $customerSent;
            
        } catch (Exception $e) {
            error_log('Email sending failed: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Send email using PHP mail function (fallback)
     */
    private function sendEmail($to, $subject, $body, $headers, $settings) {
        $headerString = implode("\r\n", $headers);
        
        if (mail($to, $subject, $body, $headerString)) {
            error_log("Email sent successfully to: $to");
            return true;
        } else {
            error_log("Failed to send email to: $to");
            return false;
        }
    }

    /**
     * Build appointment notification email body for admin
     */
    private function buildAppointmentEmailBody($appointment, $settings) {
        $serviceLocation = $appointment['service_location'] == 'workshop' ? 'Shop' : 'On-site';
        $locationDetails = $serviceLocation == 'On-site' ? 
            "Location: {$appointment['county']}, {$appointment['subcounty']}, {$appointment['address']}" : 
            "Location: Shop";
        
        return "
        <!DOCTYPE html>
        <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: #f90606; color: white; padding: 20px; text-align: center; }
                .content { background: #f9f9f9; padding: 20px; }
                .details { background: white; padding: 15px; margin: 10px 0; border-left: 4px solid #f90606; }
                .footer { text-align: center; padding: 20px; color: #666; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>New Appointment Booking</h1>
                    <p>{$settings['company_name']}</p>
                </div>
                
                <div class='content'>
                    <h2>Appointment Details</h2>
                    
                    <div class='details'>
                        <h3>Customer Information</h3>
                        <p><strong>Name:</strong> {$appointment['customer_name']}</p>
                        <p><strong>Phone:</strong> {$appointment['customer_phone']}</p>
                        <p><strong>Email:</strong> {$appointment['customer_email']}</p>
                    </div>
                    
                    <div class='details'>
                        <h3>Vehicle Information</h3>
                        <p><strong>Make:</strong> {$appointment['car_make']}</p>
                        <p><strong>Model:</strong> {$appointment['car_model']}</p>
                        <p><strong>Year:</strong> {$appointment['car_year']}</p>
                    </div>
                    
                    <div class='details'>
                        <h3>Service Details</h3>
                        <p><strong>Service Type:</strong> {$appointment['service_type']}</p>
                        <p><strong>Date:</strong> {$appointment['appointment_date']}</p>
                        <p><strong>Time:</strong> {$appointment['appointment_time']}</p>
                        <p><strong>Service Location:</strong> {$serviceLocation}</p>
                        <p><strong>{$locationDetails}</strong></p>
                    </div>
                    
                    <div class='details'>
                        <h3>Payment Information</h3>
                        <p><strong>Total Amount:</strong> KES " . number_format($appointment['total_amount'], 2) . "</p>
                        <p><strong>Deposit Amount (50%):</strong> KES " . number_format($appointment['deposit_amount'], 2) . "</p>
                        <p><strong>Payment Status:</strong> {$appointment['payment_status']}</p>
                    </div>
                    
                    <div class='details'>
                        <h3>Additional Notes</h3>
                        <p>{$appointment['notes']}</p>
                    </div>
                </div>
                
                <div class='footer'>
                    <p>This email was automatically generated by the {$settings['company_name']} booking system.</p>
                    <p>Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    /**
     * Build appointment confirmation email body for customer
     */
    private function buildCustomerAppointmentEmailBody($appointment, $settings) {
        $serviceLocation = $appointment['service_location'] == 'workshop' ? 'Shop' : 'On-site';
        $locationDetails = $serviceLocation == 'On-site' ? 
            "We will come to your location at: {$appointment['county']}, {$appointment['subcounty']}, {$appointment['address']}" : 
            "Please visit our shop at the scheduled time";
        
        return "
        <!DOCTYPE html>
        <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: #f90606; color: white; padding: 20px; text-align: center; }
                .content { background: #f9f9f9; padding: 20px; }
                .details { background: white; padding: 15px; margin: 10px 0; border-left: 4px solid #f90606; }
                .footer { text-align: center; padding: 20px; color: #666; font-size: 12px; }
                .important { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 10px 0; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Appointment Confirmation</h1>
                    <p>{$settings['company_name']}</p>
                </div>
                
                <div class='content'>
                    <p>Dear {$appointment['customer_name']},</p>
                    <p>Thank you for booking an appointment with {$settings['company_name']}. Your appointment has been scheduled successfully.</p>
                    
                    <div class='details'>
                        <h3>Your Appointment Details</h3>
                        <p><strong>Service:</strong> {$appointment['service_type']}</p>
                        <p><strong>Date:</strong> {$appointment['appointment_date']}</p>
                        <p><strong>Time:</strong> {$appointment['appointment_time']}</p>
                        <p><strong>Vehicle:</strong> {$appointment['car_make']} {$appointment['car_model']} ({$appointment['car_year']})</p>
                        <p><strong>Service Location:</strong> {$serviceLocation}</p>
                        <p><strong>{$locationDetails}</strong></p>
                    </div>
                    
                    <div class='important'>
                        <h3>Payment Information</h3>
                        <p><strong>Total Amount:</strong> KES " . number_format($appointment['total_amount'], 2) . "</p>
                        <p><strong>Deposit Paid (50%):</strong> KES " . number_format($appointment['deposit_amount'], 2) . "</p>
                        <p><strong>Remaining Balance:</strong> KES " . number_format($appointment['total_amount'] - $appointment['deposit_amount'], 2) . "</p>
                        <p><em>The remaining balance is due upon completion of the service.</em></p>
                    </div>
                    
                    <div class='details'>
                        <h3>Contact Information</h3>
                        <p>If you need to reschedule or have any questions, please contact us:</p>
                        <p><strong>Phone:</strong> {$settings['company_phone']}</p>
                        <p><strong>Email:</strong> {$settings['company_email']}</p>
                    </div>
                </div>
                
                <div class='footer'>
                    <p>We look forward to serving you!</p>
                    <p>The {$settings['company_name']} Team</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    /**
     * Test email configuration
     */
    public function testEmailConfiguration($testEmail) {
        $settings = $this->getEmailSettings();
        
        if (empty($settings['smtp_host']) || empty($settings['smtp_username'])) {
            return [
                'success' => false,
                'message' => 'Email settings are not configured'
            ];
        }

        $subject = "Test Email - {$settings['company_name']}";
        $body = "
        <html>
        <body>
            <h2>Test Email</h2>
            <p>This is a test email from {$settings['company_name']} booking system.</p>
            <p>If you received this email, your email configuration is working correctly.</p>
            <p><strong>SMTP Settings:</strong></p>
            <ul>
                <li>Host: {$settings['smtp_host']}</li>
                <li>Port: {$settings['smtp_port']}</li>
                <li>Username: {$settings['smtp_username']}</li>
                <li>Encryption: {$settings['smtp_encryption']}</li>
            </ul>
        </body>
        </html>
        ";

        $headers = [
            'From: ' . $settings['company_email'],
            'Reply-To: ' . $settings['company_email'],
            'Content-Type: text/html; charset=UTF-8',
            'X-Mailer: PHP/' . phpversion()
        ];

        try {
            $sent = $this->sendEmail($testEmail, $subject, $body, $headers, $settings);
            
            return [
                'success' => $sent,
                'message' => $sent ? 'Test email sent successfully' : 'Failed to send test email'
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Email sending failed: ' . $e->getMessage()
            ];
        }
    }
}
?>