# ZForex Mail System

A comprehensive email system for the ZForex trading platform with 22 pre-built email templates and SMTP integration.

## 🚀 Quick Setup

### 1. Install PHPMailer
```bash
composer install
```

Or manually download PHPMailer and place it in your project directory.

### 2. Configure SMTP Settings
Update `config.php` with your SMTP settings:

```php
// Mail Configuration
define("MAIL_HOST", "smtp.gmail.com"); // Your SMTP host
define("MAIL_PORT", 587); // 587 for TLS, 465 for SSL
define("MAIL_USERNAME", "your-email@gmail.com"); // Your email
define("MAIL_PASSWORD", "your-app-password"); // Your email password
define("MAIL_ENCRYPTION", "tls"); // tls or ssl
define("MAIL_FROM_EMAIL", "noreply@zforex.com"); // From email
define("MAIL_FROM_NAME", "ZForex"); // From name
define("BRAND_NAME", "ZForex"); // Brand name
```

### 3. Include Mail System
```php
require_once 'mail_system.php';
```

## 📧 Available Email Templates

1. **register_verification** - Email verification after registration
2. **after_verify_credentials** - Login credentials after verification
3. **login_alert** - Login notification
4. **open_live_account** - Live account creation
5. **kyc_upload** - KYC document submission
6. **kyc_approved** - KYC approval notification
7. **deposit_request_submitted** - Deposit request confirmation
8. **deposit_approved** - Deposit approval notification
9. **otp_withdrawal** - Withdrawal OTP
10. **withdrawal_request_submitted** - Withdrawal request confirmation
11. **withdrawal_approved** - Withdrawal approval notification
12. **ib_commission_withdrawal** - IB commission withdrawal
13. **referral_registration** - New referral notification
14. **trade_open** - Trade opening notification
15. **trade_close** - Trade closing notification
16. **daily_trade_summary** - Daily trading summary
17. **password_reset** - Password reset link
18. **password_changed** - Password change confirmation
19. **profile_updated** - Profile update notification
20. **deposit_failed** - Deposit failure notification
21. **withdrawal_rejected** - Withdrawal rejection notification
22. **monthly_statement** - Monthly account statement

## 🔧 Usage Examples

### Basic Usage
```php
// Initialize mailer
$mailer = new ZForexMailer();

// Send registration verification
$result = $mailer->sendRegisterVerification(
    'user@example.com',
    'John Doe',
    'https://yoursite.com/verify?token=abc123'
);

if ($result['success']) {
    echo "Email sent successfully!";
} else {
    echo "Failed: " . $result['message'];
}
```

### Using Global Function
```php
// Send any template using global function
$result = sendZForexMail(
    'user@example.com',
    'John Doe',
    'trade_open',
    [
        'trade_symbol' => 'EURUSD',
        'trade_side' => 'BUY',
        'trade_volume' => '0.1',
        'price' => '1.0850',
        'order_id' => 'ORD-123456',
        'trading_url' => 'https://yoursite.com/trading'
    ]
);
```

### Integration Examples

#### Registration with Email Verification
```php
// In register.php
require_once 'mail_system.php';

// After successful user insertion
$verification_token = bin2hex(random_bytes(32));
$verification_url = "https://yoursite.com/verify.php?token=" . $verification_token;

$mailer = new ZForexMailer();
$result = $mailer->sendRegisterVerification($email, $full_name, $verification_url);
```

#### Login Alert
```php
// In login.php
require_once 'mail_system.php';

// After successful login
$mailer = new ZForexMailer();
$result = $mailer->sendLoginAlert(
    $email,
    $full_name,
    date('Y-m-d H:i:s'),
    $_SERVER['REMOTE_ADDR'],
    'Chrome on Windows'
);
```

#### Deposit Notification
```php
// In deposit.php
require_once 'mail_system.php';

// After deposit approval
$mailer = new ZForexMailer();
$result = $mailer->sendDepositApproved(
    $email,
    $full_name,
    $amount,
    $currency,
    $new_balance,
    $transaction_id
);
```

## 🎨 Email Template Structure

Each email includes:
- **Professional HTML design** with responsive layout
- **Brand colors** and styling
- **Dynamic content** with variable replacement
- **Call-to-action buttons**
- **Footer** with unsubscribe and legal links

## 🔐 Security Features

- **SMTP Authentication** with TLS/SSL encryption
- **Input sanitization** for all variables
- **Error logging** for debugging
- **Token-based verification** for sensitive actions

## 📱 Responsive Design

All email templates are:
- **Mobile-friendly** with responsive design
- **Cross-client compatible** (Gmail, Outlook, Apple Mail)
- **Professional appearance** with consistent branding

## 🛠 Quick Send Methods

The `ZForexMailer` class includes quick send methods for common emails:

```php
$mailer = new ZForexMailer();

// Registration verification
$mailer->sendRegisterVerification($email, $name, $verification_url);

// Login credentials
$mailer->sendLoginCredentials($email, $name, $password, $login_url);

// Login alert
$mailer->sendLoginAlert($email, $name, $login_time, $ip, $device);

// Live account opened
$mailer->sendLiveAccountOpened($email, $name, $account_id, $type, $leverage, $currency);

// KYC upload
$mailer->sendKYCUpload($email, $name, $reference_id);

// KYC approved
$mailer->sendKYCApproved($email, $name, $verification_level);

// Deposit request
$mailer->sendDepositRequest($email, $name, $amount, $currency, $method, $txn_id);

// Deposit approved
$mailer->sendDepositApproved($email, $name, $amount, $currency, $balance, $txn_id);

// Withdrawal OTP
$mailer->sendWithdrawalOTP($email, $name, $otp, $amount, $currency, $destination);

// Password reset
$mailer->sendPasswordReset($email, $name, $reset_url, $ip);
```

## 🔧 Customization

### Adding New Templates
```php
// Add to the $templates array in ZForexMailer class
'your_template_key' => [
    'subject' => 'Your Subject with {{variables}}',
    'header' => 'Email Header',
    'body' => 'Email body with {{variable}} placeholders',
    'button_text' => 'Button Text',
    'button_url' => '{{button_url}}'
]
```

### Custom Variables
All templates support variable replacement using `{{variable_name}}` syntax:

```php
$result = sendZForexMail(
    'user@example.com',
    'John Doe',
    'template_key',
    [
        'variable_name' => 'value',
        'amount' => '1000',
        'currency' => 'USD'
    ]
);
```

## 📊 Error Handling

The mail system includes comprehensive error handling:

```php
$result = $mailer->sendMail($email, $name, $template, $variables);

if ($result['success']) {
    // Email sent successfully
    echo "Email sent!";
} else {
    // Handle error
    error_log("Mail error: " . $result['message']);
    echo "Failed to send email: " . $result['message'];
}
```

## 🧪 Testing

Use `test_mail.php` to test the mail system:

```bash
php test_mail.php
```

Make sure to update the SMTP settings in `config.php` before testing.

## 📋 Database Schema Updates

For email verification functionality, add these columns to your `loginusers` table:

```sql
ALTER TABLE loginusers ADD COLUMN verification_token VARCHAR(64) NULL;
ALTER TABLE loginusers ADD COLUMN verification_expires DATETIME NULL;
ALTER TABLE loginusers ADD COLUMN is_verified TINYINT(1) DEFAULT 0;
ALTER TABLE loginusers ADD COLUMN verified_at DATETIME NULL;

-- Optional: Login logs table
CREATE TABLE login_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    ip_address VARCHAR(45),
    user_agent TEXT,
    login_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES loginusers(id)
);
```

## 🚨 Important Notes

1. **Update SMTP settings** in `config.php` before using
2. **Install PHPMailer** using Composer or manually
3. **Test emails** in development environment first
4. **Use app passwords** for Gmail (not regular password)
5. **Check spam folders** during testing
6. **Monitor email logs** for debugging

## 📞 Support

For issues or questions about the mail system:
1. Check the error logs
2. Verify SMTP settings
3. Test with `test_mail.php`
4. Ensure PHPMailer is properly installed

---

**Ready to use!** 🎉 Your ZForex mail system is now set up and ready to send professional emails to your users.