<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Email Configuration and Functions using PHPMailer
 * Developer: JOACHIM'S INNOTECH
 */

// Prevent direct access
if (!defined('BASE_PATH')) {
    exit('Direct access not permitted');
}

// Define possible PHPMailer paths
$possible_paths = [
    BASE_PATH . '/vendor/autoload.php',
    BASE_PATH . '/includes/phpmailer/src/Exception.php',
    BASE_PATH . '/includes/phpmailer/Exception.php',
    BASE_PATH . '/PHPMailer/src/Exception.php',
    __DIR__ . '/../vendor/autoload.php',
    __DIR__ . '/../includes/phpmailer/src/Exception.php'
];

$phpmailer_found = false;
foreach ($possible_paths as $path) {
    if (file_exists($path)) {
        if (strpos($path, 'autoload.php') !== false) {
            require_once $path;
            $phpmailer_found = true;
            break;
        } else {
            // Manual includes
            $base_dir = dirname($path);
            require_once $base_dir . '/Exception.php';
            require_once $base_dir . '/PHPMailer.php';
            require_once $base_dir . '/SMTP.php';
            $phpmailer_found = true;
            break;
        }
    }
}

if (!$phpmailer_found) {
    error_log("PHPMailer not found. Email functionality disabled.");
    
    // Define fallback functions
    function get_mailer() {
        throw new Exception('PHPMailer not installed');
    }
    
    function send_email($to, $subject, $body, $altBody = '', $attachments = [], $cc = [], $bcc = []) {
        error_log("Email sending failed: PHPMailer not installed. Would send: $subject to " . print_r($to, true));
        return false;
    }
    
    function send_template_email($template_code, $to, $variables = [], $attachments = []) {
        error_log("Template email sending failed: PHPMailer not installed");
        return false;
    }
    
    // Return to prevent further execution
    return;
}

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

/**
 * Get configured PHPMailer instance
 * 
 * @return PHPMailer
 */
function get_mailer() {
    $mail = new PHPMailer(true);
    
    try {
        // Server settings
        if (defined('SMTP_HOST') && SMTP_HOST && defined('SMTP_PORT') && SMTP_PORT) {
            $mail->isSMTP();
            $mail->Host       = SMTP_HOST;
            $mail->SMTPAuth   = true;
            $mail->Username   = SMTP_USER;
            $mail->Password   = SMTP_PASS;
            $mail->SMTPSecure = defined('SMTP_ENCRYPTION') ? SMTP_ENCRYPTION : 'tls';
            $mail->Port       = SMTP_PORT;
            
            // Enable debug in development
            if (defined('ENVIRONMENT') && ENVIRONMENT === 'development') {
                $mail->SMTPDebug = SMTP::DEBUG_SERVER;
                $mail->Debugoutput = function($str, $level) {
                    log_message("SMTP Debug: $str", 'DEBUG');
                };
            }
        } else {
            // Fallback to mail() if SMTP not configured
            $mail->isMail();
        }
        
        // Default from address
        $from_email = defined('SMTP_FROM_EMAIL') ? SMTP_FROM_EMAIL : 'noreply@ruhondo.com';
        $from_name = defined('SMTP_FROM_NAME') ? SMTP_FROM_NAME : 'Ruhondo Beach Resort';
        $mail->setFrom($from_email, $from_name);
        
        // Default settings
        $mail->isHTML(true);
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
        
        return $mail;
        
    } catch (Exception $e) {
        log_message("Mailer configuration error: " . $e->getMessage(), 'ERROR');
        throw $e;
    }
}

/**
 * Send email
 * 
 * @param string|array $to Recipient email(s)
 * @param string $subject Email subject
 * @param string $body HTML body
 * @param string $altBody Plain text alternative
 * @param array $attachments Array of file paths
 * @param array $cc CC recipients
 * @param array $bcc BCC recipients
 * @return bool True on success, false on failure
 */
function send_email($to, $subject, $body, $altBody = '', $attachments = [], $cc = [], $bcc = []) {
    if (defined('ENABLE_EMAIL') && !ENABLE_EMAIL) {
        log_message("Email sending disabled. Would send: $subject to " . print_r($to, true), 'DEBUG');
        return true;
    }
    
    try {
        $mail = get_mailer();
        
        // Add recipients
        if (is_array($to)) {
            foreach ($to as $email) {
                if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $mail->addAddress($email);
                }
            }
        } else {
            if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
                $mail->addAddress($to);
            } else {
                throw new Exception("Invalid email address: $to");
            }
        }
        
        // Add CC
        foreach ($cc as $email) {
            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $mail->addCC($email);
            }
        }
        
        // Add BCC
        foreach ($bcc as $email) {
            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $mail->addBCC($email);
            }
        }
        
        // Add attachments
        foreach ($attachments as $attachment) {
            if (is_array($attachment) && isset($attachment['path'])) {
                if (file_exists($attachment['path'])) {
                    $mail->addAttachment($attachment['path'], $attachment['name'] ?? '');
                }
            } elseif (is_string($attachment) && file_exists($attachment)) {
                $mail->addAttachment($attachment);
            }
        }
        
        // Content
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = $altBody ?: strip_tags($body);
        
        // Send
        $mail->send();
        
        log_message("Email sent successfully: $subject to " . (is_array($to) ? implode(', ', $to) : $to), 'INFO');
        return true;
        
    } catch (Exception $e) {
        log_message("Email sending failed: " . $e->getMessage(), 'ERROR');
        return false;
    }
}

// Rest of your mailer functions remain the same...
// [Include all the other functions from your original mailer.php]