<?php
/**
 * EmailService - Send emails via PHPMailer or PHP mail()
 * Works with or without Composer
 */

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

class EmailService {
    
    private static $devMode = true; // Set to false for production
    private static $logDir = __DIR__ . '/logs/';
    
    /**
     * Check if PHPMailer files exist
     */
    private static function phpmailerAvailable() {
        $phpmailerPath = __DIR__ . '/PHPMailer/src/PHPMailer.php';
        return file_exists($phpmailerPath);
    }
    
    /**
     * Send email via PHPMailer (preferred) or fallback to PHP mail()
     */
    public static function sendEmail($to, $subject, $body, $isHtml = true) {
        // Try PHPMailer first
        if (self::phpmailerAvailable()) {
            try {
                return self::sendWithPHPMailer($to, $subject, $body, $isHtml);
            } catch (Exception $e) {
                error_log("PHPMailer error: " . $e->getMessage());
                // Fall through to PHP mail() fallback
            }
        }
        
        // Fallback to PHP mail()
        return self::sendWithPHPMail($to, $subject, $body, $isHtml);
    }
    
    /**
     * Send using PHPMailer
     */
    private static function sendWithPHPMailer($to, $subject, $body, $isHtml) {
        // Include PHPMailer classes from src/ subfolder
        require_once(__DIR__ . '/PHPMailer/src/PHPMailer.php');
        require_once(__DIR__ . '/PHPMailer/src/SMTP.php');
        require_once(__DIR__ . '/PHPMailer/src/Exception.php');
        
        $mail = new PHPMailer(true);
        
        try {
            // SMTP Configuration
            $mail->isSMTP();
            $mail->Host = 'mail.zemaraimgroups.com';                    
            $mail->SMTPAuth = true;
            $mail->Username = 'info@zemaraimgroups.com';    
            $mail->Password = 'zemaraimgroups@123';              // App password WITHOUT spaces
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;   // Use SMTPS instead of STARTTLS
            $mail->Port = 465;                                   // Use port 465 for SMTPS
            
            // Disable SSL verification for development (not recommended for production)
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );
            
            // Email details
            $mail->setFrom('info@zemaraimgroups.com', 'Interior Design Solutions');
            $mail->addAddress($to);
            $mail->Subject = $subject;
            $mail->isHTML($isHtml);
            $mail->Body = $body;
            
            // Enable debug logging
            $mail->SMTPDebug = 0; // Set to 2 for debugging SMTP issues
            
            // Send email
            $result = $mail->send();
            
            // Log if dev mode
            if (self::$devMode) {
                $status = $result ? "✅ Sent via PHPMailer" : "❌ PHPMailer send() returned false. Error: " . $mail->ErrorInfo;
                self::logEmail($to, $subject, $status);
            }
            
            return $result;
            
        } catch (Exception $e) {
            $errorMsg = "PHPMailer Exception: " . $e->getMessage();
            error_log($errorMsg);
            
            if (self::$devMode) {
                self::logEmail($to, $subject, "❌ " . $errorMsg);
            }
            
            return false;
        } catch (Throwable $e) {
            $errorMsg = "PHPMailer Error: " . $e->getMessage();
            error_log($errorMsg);
            
            if (self::$devMode) {
                self::logEmail($to, $subject, "❌ " . $errorMsg);
            }
            
            return false;
        }
    }
    
    /**
     * Fallback: Log email instead of using mail() (Windows doesn't have SMTP)
     */
    private static function sendWithPHPMail($to, $subject, $body, $isHtml) {
        // Windows XAMPP doesn't have a local SMTP server
        // Log the email in dev mode instead
        if (self::$devMode) {
            self::logEmail($to, $subject, "📝 Logged (PHP mail() not available on Windows - use PHPMailer)");
            return true; // Return true to prevent errors
        }
        
        // In production, PHPMailer should be available
        return false;
    }
    
    /**
     * Generate OTP (One-Time Password)
     */
    public static function generateOTP($length = 6) {
        return str_pad(rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
    }
    
    /**
     * Generate password reset token
     */
    public static function generateResetToken() {
        return bin2hex(random_bytes(32));
    }
    
    /**
     * Send Email Verification OTP
     */
    public static function sendEmailVerificationOTP($to_email, $user_name, $otp_code) {
        $subject = "Verify Your Email - Interior Design";
        
        $message = "
        <html>
        <head>
            <style>
                body { font-family: 'DM Sans', Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; background: #f9f9f9; padding: 20px; }
                .header { background: linear-gradient(135deg, #D4A574 0%, #b8905a 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
                .content { background: white; padding: 30px; }
                .otp-box { background: #f0e6d8; border-left: 4px solid #D4A574; padding: 20px; margin: 20px 0; text-align: center; }
                .otp-code { font-size: 32px; font-weight: 700; color: #D4A574; letter-spacing: 3px; }
                .footer { background: #1a1a1a; color: white; padding: 15px; text-align: center; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Email Verification</h1>
                </div>
                <div class='content'>
                    <p>Hello <strong>$user_name</strong>,</p>
                    <p>Thank you for registering. Please verify your email address using the OTP code below:</p>
                    <div class='otp-box'>
                        <p>Your verification code:</p>
                        <div class='otp-code'>$otp_code</div>
                        <p style='color: #999; font-size: 12px; margin: 10px 0 0 0;'>This code will expire in 10 minutes</p>
                    </div>
                    <p>If you didn't request this code, please ignore this email.</p>
                    <p>Best regards,<br><strong>Interior Design Team</strong></p>
                </div>
                <div class='footer'>
                    <p>&copy; 2025 Interior Design. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>";
        
        return self::sendEmail($to_email, $subject, $message, true);
    }
    
    /**
     * Send 2FA OTP
     */
    public static function send2FAOTP($to_email, $user_name = '', $otp_code) {
        $subject = "Your Two-Factor Authentication Code";
        
        $message = "
        <html>
        <head>
            <style>
                body { font-family: 'DM Sans', Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; background: #f9f9f9; padding: 20px; }
                .header { background: linear-gradient(135deg, #D4A574 0%, #b8905a 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
                .content { background: white; padding: 30px; }
                .otp-box { background: #f0e6d8; border-left: 4px solid #D4A574; padding: 20px; margin: 20px 0; text-align: center; }
                .otp-code { font-size: 32px; font-weight: 700; color: #D4A574; letter-spacing: 3px; }
                .footer { background: #1a1a1a; color: white; padding: 15px; text-align: center; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Two-Factor Authentication</h1>
                </div>
                <div class='content'>
                    <p>Hello <strong>$user_name</strong>,</p>
                    <p>Your two-factor authentication code is:</p>
                    <div class='otp-box'>
                        <div class='otp-code'>$otp_code</div>
                        <p style='color: #999; font-size: 12px; margin: 10px 0 0 0;'>This code will expire in 5 minutes</p>
                    </div>
                    <p style='color: red; font-weight: 600;'>⚠ Never share this code with anyone!</p>
                    <p>Best regards,<br><strong>Interior Design Team</strong></p>
                </div>
                <div class='footer'>
                    <p>&copy; 2025 Interior Design. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>";
        
        return self::sendEmail($to_email, $subject, $message, true);
    }
    
    /**
     * Send password reset link
     */
    public static function sendPasswordResetEmail($to_email, $user_name, $reset_link) {
        $subject = "Reset Your Password";
        
        $message = "
        <html>
        <head>
            <style>
                body { font-family: 'DM Sans', Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; background: #f9f9f9; padding: 20px; }
                .header { background: linear-gradient(135deg, #D4A574 0%, #b8905a 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
                .content { background: white; padding: 30px; }
                .button { background: linear-gradient(135deg, #D4A574 0%, #b8905a 100%); color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 20px 0; }
                .footer { background: #1a1a1a; color: white; padding: 15px; text-align: center; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Password Reset Request</h1>
                </div>
                <div class='content'>
                    <p>Hello <strong>$user_name</strong>,</p>
                    <p>We received a request to reset your password. Click the button below to create a new password:</p>
                    <p>
                        <a href='$reset_link' class='button'>Reset Password</a>
                    </p>
                    <p style='color: #999; font-size: 12px;'>Or copy this link: <br>$reset_link</p>
                    <p style='color: #999; font-size: 12px;'>This link will expire in 1 hour.</p>
                    <p>If you didn't request this, please ignore this email.</p>
                    <p>Best regards,<br><strong>Interior Design Team</strong></p>
                </div>
                <div class='footer'>
                    <p>&copy; 2025 Interior Design. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>";
        
        return self::sendEmail($to_email, $subject, $message, true);
    }
    
    /**
     * Log email in development mode
     */
    private static function logEmail($to, $subject, $status) {
        if (!is_dir(self::$logDir)) {
            @mkdir(self::$logDir, 0755, true);
        }
        
        $logFile = self::$logDir . 'emails_' . date('Y-m-d') . '.txt';
        $logEntry = "[" . date('Y-m-d H:i:s') . "] TO: {$to} | SUBJECT: {$subject} | {$status}\n";
        
        file_put_contents($logFile, $logEntry, FILE_APPEND);
    }
}
?>
