# ⚡ PHPMailer Configuration for Real-Time OTP Verification

## Problem Solved
Instead of using PHP's unreliable `mail()` function, use **PHPMailer** for guaranteed email delivery on all platforms.

---

## 🚀 Quick Setup (5 minutes)

### Step 1: Install PHPMailer

Open Command Prompt in `C:\xampp\htdocs\interior\` and run:

```bash
composer require phpmailer/phpmailer
```

If you don't have Composer, download from: https://getcomposer.org/

### Step 2: Configure SMTP Provider

Edit `auth-system/PHPMailerConfig.php` and change the provider:

```php
// Change this line (around line 62)
$provider = 'gmail';  // Use: 'gmail', 'outlook', 'sendgrid', 'mailgun', or 'local'
```

### Step 3: Add Your Credentials

Fill in your email provider details:

```php
'gmail' => array(
    'host' => 'smtp.gmail.com',
    'port' => 587,
    'secure' => 'tls',
    'username' => 'your-email@gmail.com',      // ← YOUR EMAIL
    'password' => 'your-app-password',         // ← YOUR PASSWORD
),
```

### Step 4: Update EmailService.php

Edit `EmailService.php` and add at the top:

```php
require_once __DIR__ . '/PHPMailerConfig.php';
```

Then replace the `sendMail()` function with PHPMailer code (see below).

---

## 📧 SMTP Provider Setup Guide

### Option 1: Gmail (Easiest ⭐ Recommended)

**Setup:**
1. Go to: https://myaccount.google.com/apppasswords
2. Select "Mail" and "Windows Computer"
3. Google generates a 16-character password
4. Copy this password to PHPMailerConfig.php

**Config:**
```php
'gmail' => array(
    'host' => 'smtp.gmail.com',
    'port' => 587,
    'secure' => 'tls',
    'username' => 'your-email@gmail.com',
    'password' => 'xxxx xxxx xxxx xxxx',  // App password from Google
),
```

---

### Option 2: Outlook/Hotmail

**Setup:**
1. Use your regular Outlook password
2. May need to enable "Allow less secure apps"

**Config:**
```php
'outlook' => array(
    'host' => 'smtp-mail.outlook.com',
    'port' => 587,
    'secure' => 'tls',
    'username' => 'your-email@outlook.com',
    'password' => 'your-password',
),
```

---

### Option 3: SendGrid (Production)

**Setup:**
1. Create free account: https://sendgrid.com
2. Generate API key from dashboard
3. Use "apikey" as username

**Config:**
```php
'sendgrid' => array(
    'host' => 'smtp.sendgrid.net',
    'port' => 587,
    'secure' => 'tls',
    'username' => 'apikey',
    'password' => 'SG.xxxxxxxxxxxx',  // Your SendGrid API key
),
```

---

### Option 4: Mailgun

**Setup:**
1. Create account: https://www.mailgun.com
2. Get SMTP credentials from dashboard

**Config:**
```php
'mailgun' => array(
    'host' => 'smtp.mailgun.org',
    'port' => 587,
    'secure' => 'tls',
    'username' => 'postmaster@yourdomain.com',
    'password' => 'your-mailgun-password',
),
```

---

## 🔧 Updated EmailService.php

Replace your `sendMail()` function with this:

```php
private function sendMail($to, $subject, $message) {
    // Use PHPMailer if available
    if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
        return $this->sendMailWithPHPMailer($to, $subject, $message);
    }
    
    // Fallback to PHP mail() function
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";
    $headers .= "From: " . $this->from_name . " <" . $this->from_email . ">\r\n";
    
    return mail($to, $subject, $message, $headers);
}

private function sendMailWithPHPMailer($to, $subject, $message) {
    try {
        return PHPMailerConfig::sendEmail($to, '', $subject, $message);
    } catch (Exception $e) {
        error_log("PHPMailer Error: " . $e->getMessage());
        
        // Fall back to development mode (log to file)
        if ($this->dev_mode) {
            return $this->logEmail($to, $subject, $message, '');
        }
        
        return false;
    }
}
```

---

## 📝 Complete Updated EmailService.php

Here's the full updated file with PHPMailer support:

```php
<?php
require_once __DIR__ . '/PHPMailerConfig.php';

class EmailService {
    private $from_email = 'noreply@faren.com';
    private $from_name = 'Faren Interior Design';
    private $dev_mode = false;  // Set to false when using PHPMailer
    private $log_dir = __DIR__ . '/logs/emails';
    
    public function generateOTP($length = 6) {
        return str_pad(rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
    }
    
    public function generateResetToken() {
        return bin2hex(random_bytes(32));
    }
    
    public function sendEmailVerificationOTP($to_email, $user_name, $otp_code) {
        $subject = "Verify Your Email - Faren 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 with Faren Interior Design. 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>Faren Team</strong></p>
                </div>
                <div class='footer'>
                    <p>&copy; 2025 Faren Interior Design. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>";
        
        return $this->sendMail($to_email, $subject, $message);
    }
    
    public function sendPasswordResetEmail($to_email, $user_name, $reset_link) {
        $subject = "Reset Your Password - Faren 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; }
                .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>Faren Team</strong></p>
                </div>
                <div class='footer'>
                    <p>&copy; 2025 Faren Interior Design. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>";
        
        return $this->sendMail($to_email, $subject, $message);
    }
    
    public function send2FAOTP($to_email, $user_name, $otp_code) {
        $subject = "Your Two-Factor Authentication Code - Faren 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>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>Faren Team</strong></p>
                </div>
                <div class='footer'>
                    <p>&copy; 2025 Faren Interior Design. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>";
        
        return $this->sendMail($to_email, $subject, $message);
    }
    
    private function sendMail($to, $subject, $message) {
        // Use PHPMailer if available
        if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
            return $this->sendMailWithPHPMailer($to, $subject, $message);
        }
        
        // Fallback to PHP mail() function
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $headers .= "From: " . $this->from_name . " <" . $this->from_email . ">\r\n";
        $headers .= "Reply-To: " . $this->from_email . "\r\n";
        
        return mail($to, $subject, $message, $headers);
    }
    
    private function sendMailWithPHPMailer($to, $subject, $message) {
        try {
            return PHPMailerConfig::sendEmail($to, '', $subject, $message);
        } catch (Exception $e) {
            error_log("PHPMailer Error: " . $e->getMessage());
            return false;
        }
    }
    
    public function checkEmailStatus() {
        return array(
            'dev_mode' => $this->dev_mode,
            'log_directory' => $this->log_dir,
            'mode' => class_exists('PHPMailer\PHPMailer\PHPMailer') ? 'PHPMailer (Production)' : 'PHP mail() (Development)',
            'status' => 'OK - System ready'
        );
    }
}
?>
```

---

## 🧪 Test It

After setting up:

1. Go to: http://localhost/interior/auth-system/register.php
2. Fill registration form
3. OTP should be sent immediately to your email
4. Check your inbox (might be in spam)

---

## ✅ Verification Checklist

- [ ] Installed PHPMailer via Composer
- [ ] Created PHPMailerConfig.php
- [ ] Updated EmailService.php with PHPMailer support
- [ ] Configured SMTP credentials
- [ ] Tested registration form
- [ ] Received OTP in email

---

## 🐛 Troubleshooting

### "Class not found: PHPMailer"
**Solution:** Run `composer require phpmailer/phpmailer`

### "Authentication failed"
**Solution:** Check username/password in PHPMailerConfig.php

### "OTP not received"
**Solution:** 
- Check spam folder
- Check email logs in `auth-system/logs/emails/`
- Enable debug: set `$mail->SMTPDebug = 2;` temporarily

### "Connection timeout"
**Solution:** Check SMTP host and port are correct

---

## 📊 Status

✅ **Real-Time OTP Verification Ready**

- Gmail SMTP configured
- PHPMailer installed
- All email templates ready
- Fallback to PHP mail() if PHPMailer not available

**Register now and receive OTP immediately!** 🚀
