<?php
/**
 * Mail Integration Examples
 * This file shows how to call the ZForex mail system from different functions
 */

// Include the mail system
require_once 'mail_system.php';
require_once 'config.php';

/**
 * Example 1: User Registration Function
 */
function registerUser($email, $password, $full_name) {
    global $conn;
    
    try {
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        // Generate verification token
        $verification_token = bin2hex(random_bytes(32));
        $verification_expires = date('Y-m-d H:i:s', strtotime('+24 hours'));
        
        // Insert user into database
        $stmt = $conn->prepare("INSERT INTO loginusers (email, password, full_name, verification_token, verification_expires, is_verified) VALUES (?, ?, ?, ?, ?, 0)");
        $stmt->bind_param("sssss", $email, $hashed_password, $full_name, $verification_token, $verification_expires);
        
        if ($stmt->execute()) {
            // Send verification email using the mail system
            $verification_url = "https://yoursite.com/verify_email.php?token=" . $verification_token;
            
            $result = sendZForexMail(
                $email,
                $full_name,
                'register_verification',
                ['verification_url' => $verification_url]
            );
            
            if ($result['success']) {
                return ['success' => true, 'message' => 'Registration successful! Please check your email for verification.'];
            } else {
                return ['success' => false, 'message' => 'Registration successful but email failed to send.'];
            }
        } else {
            return ['success' => false, 'message' => 'Registration failed.'];
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

/**
 * Example 2: Deposit Processing Function
 */
function processDeposit($user_id, $amount, $currency, $payment_method) {
    global $conn;
    
    try {
        // Get user details
        $stmt = $conn->prepare("SELECT email, full_name, balance FROM loginusers WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        
        if (!$user) {
            return ['success' => false, 'message' => 'User not found.'];
        }
        
        // Generate transaction ID
        $transaction_id = 'DEP-' . time() . '-' . $user_id;
        
        // Insert deposit request
        $stmt = $conn->prepare("INSERT INTO deposits (user_id, amount, currency, payment_method, transaction_id, status) VALUES (?, ?, ?, ?, ?, 'pending')");
        $stmt->bind_param("idsss", $user_id, $amount, $currency, $payment_method, $transaction_id);
        
        if ($stmt->execute()) {
            // Send deposit request email
            $result = sendZForexMail(
                $user['email'],
                $user['full_name'],
                'deposit_request_submitted',
                [
                    'amount' => $amount,
                    'currency' => $currency,
                    'payment_method' => $payment_method,
                    'transaction_id' => $transaction_id,
                    'dashboard_url' => 'https://yoursite.com/dashboard.php'
                ]
            );
            
            return ['success' => true, 'message' => 'Deposit request submitted successfully!', 'transaction_id' => $transaction_id];
        } else {
            return ['success' => false, 'message' => 'Failed to submit deposit request.'];
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

/**
 * Example 3: Approve Deposit Function (Admin)
 */
function approveDeposit($transaction_id) {
    global $conn;
    
    try {
        // Get deposit and user details
        $stmt = $conn->prepare("
            SELECT d.*, u.email, u.full_name, u.balance 
            FROM deposits d 
            JOIN loginusers u ON d.user_id = u.id 
            WHERE d.transaction_id = ? AND d.status = 'pending'
        ");
        $stmt->bind_param("s", $transaction_id);
        $stmt->execute();
        $deposit = $stmt->get_result()->fetch_assoc();
        
        if (!$deposit) {
            return ['success' => false, 'message' => 'Deposit not found or already processed.'];
        }
        
        // Update user balance
        $new_balance = $deposit['balance'] + $deposit['amount'];
        $stmt = $conn->prepare("UPDATE loginusers SET balance = ? WHERE id = ?");
        $stmt->bind_param("di", $new_balance, $deposit['user_id']);
        $stmt->execute();
        
        // Update deposit status
        $stmt = $conn->prepare("UPDATE deposits SET status = 'approved', approved_at = NOW() WHERE transaction_id = ?");
        $stmt->bind_param("s", $transaction_id);
        $stmt->execute();
        
        // Send approval email
        $result = sendZForexMail(
            $deposit['email'],
            $deposit['full_name'],
            'deposit_approved',
            [
                'amount' => $deposit['amount'],
                'currency' => $deposit['currency'],
                'new_balance' => $new_balance,
                'transaction_id' => $transaction_id,
                'dashboard_url' => 'https://yoursite.com/dashboard.php'
            ]
        );
        
        return ['success' => true, 'message' => 'Deposit approved successfully!'];
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

/**
 * Example 4: Trade Notification Function
 */
function notifyTradeOpened($user_id, $trade_data) {
    global $conn;
    
    try {
        // Get user details
        $stmt = $conn->prepare("SELECT email, full_name FROM loginusers WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        
        if (!$user) {
            return ['success' => false, 'message' => 'User not found.'];
        }
        
        // Send trade opened email
        $result = sendZForexMail(
            $user['email'],
            $user['full_name'],
            'trade_open',
            [
                'trade_symbol' => $trade_data['symbol'],
                'trade_side' => $trade_data['side'],
                'trade_volume' => $trade_data['volume'],
                'price' => $trade_data['price'],
                'order_id' => $trade_data['order_id'],
                'trading_url' => 'https://yoursite.com/trading.php'
            ]
        );
        
        return $result;
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

/**
 * Example 5: Password Reset Function
 */
function initiatePasswordReset($email) {
    global $conn;
    
    try {
        // Check if user exists
        $stmt = $conn->prepare("SELECT id, full_name FROM loginusers WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        
        if (!$user) {
            return ['success' => false, 'message' => 'Email not found.'];
        }
        
        // Generate reset token
        $reset_token = bin2hex(random_bytes(32));
        $reset_expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
        
        // Store reset token
        $stmt = $conn->prepare("UPDATE loginusers SET reset_token = ?, reset_expires = ? WHERE id = ?");
        $stmt->bind_param("ssi", $reset_token, $reset_expires, $user['id']);
        $stmt->execute();
        
        // Send password reset email
        $reset_url = "https://yoursite.com/reset_password.php?token=" . $reset_token;
        
        $result = sendZForexMail(
            $email,
            $user['full_name'],
            'password_reset',
            [
                'reset_url' => $reset_url,
                'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'Unknown'
            ]
        );
        
        return $result;
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

/**
 * Example 6: KYC Status Update Function
 */
function updateKYCStatus($user_id, $status, $verification_level = 'Basic') {
    global $conn;
    
    try {
        // Get user details
        $stmt = $conn->prepare("SELECT email, full_name FROM loginusers WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        
        if (!$user) {
            return ['success' => false, 'message' => 'User not found.'];
        }
        
        // Update KYC status
        $stmt = $conn->prepare("UPDATE loginusers SET kyc_status = ?, kyc_verified_at = NOW() WHERE id = ?");
        $stmt->bind_param("si", $status, $user_id);
        $stmt->execute();
        
        // Send appropriate email based on status
        if ($status === 'approved') {
            $result = sendZForexMail(
                $user['email'],
                $user['full_name'],
                'kyc_approved',
                [
                    'verification_level' => $verification_level,
                    'dashboard_url' => 'https://yoursite.com/dashboard.php'
                ]
            );
        }
        
        return ['success' => true, 'message' => 'KYC status updated successfully!'];
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

/**
 * Example 7: Using the ZForexMailer Class Directly
 */
function sendCustomNotification($email, $name, $custom_message) {
    try {
        // Initialize the mailer class
        $mailer = new ZForexMailer();
        
        // You can also use the class methods directly
        $result = $mailer->sendMail(
            $email,
            $name,
            'profile_updated',
            [
                'update_details' => $custom_message,
                'dashboard_url' => 'https://yoursite.com/dashboard.php'
            ]
        );
        
        return $result;
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

// Example usage in your main application files:

/*
// In register.php
if ($_POST['action'] == 'register') {
    $result = registerUser($_POST['email'], $_POST['password'], $_POST['full_name']);
    echo json_encode($result);
}

// In deposit.php
if ($_POST['action'] == 'deposit') {
    $result = processDeposit($_SESSION['user_id'], $_POST['amount'], $_POST['currency'], $_POST['method']);
    echo json_encode($result);
}

// In admin panel for approving deposits
if ($_POST['action'] == 'approve_deposit') {
    $result = approveDeposit($_POST['transaction_id']);
    echo json_encode($result);
}

// In trading system
if ($trade_opened) {
    notifyTradeOpened($user_id, $trade_data);
}

// In forgot password page
if ($_POST['action'] == 'reset_password') {
    $result = initiatePasswordReset($_POST['email']);
    echo json_encode($result);
}
*/

?>