<?php
/**
 * SMTP Email Helper - PVP360
 * Domain : pvp360.us
 * Email  : pvp360@pvp360.us
 */

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

require_once __DIR__ . '/PHPMailer-master/src/Exception.php';
require_once __DIR__ . '/PHPMailer-master/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer-master/src/SMTP.php';

/* ================================================================
   CORE SEND FUNCTION
================================================================ */
function sendEmail($to, $subject, $body, $attachments = []) {
    $config = require __DIR__ . '/smtp_config.php';
    $mail   = new PHPMailer(true);

    try {
        if ($config['debug'] > 0) {
            $mail->SMTPDebug = $config['debug'];
        }

        $mail->isSMTP();
        $mail->Host          = $config['host'];
        $mail->SMTPAuth      = true;
        $mail->Username      = $config['username'];
        $mail->Password      = $config['password'];
        $mail->SMTPSecure    = $config['encryption'];
        $mail->Port          = $config['port'];
        $mail->Timeout       = $config['timeout'];
        $mail->SMTPKeepAlive = true;

        $mail->setFrom($config['from_email'], $config['from_name']);
        $mail->addAddress($to);
        $mail->addReplyTo($config['reply_to'], $config['reply_to_name']);

        // Anti-spam headers
        $mail->MessageID = sprintf('<%s@pvp360.us>', md5(uniqid(time())));
        $mail->XMailer   = 'PVP360 Mailer';
        $mail->addCustomHeader('X-Priority',            '3');
        $mail->addCustomHeader('Importance',            'Normal');
        $mail->addCustomHeader('List-Unsubscribe',      '<mailto:pvp360@pvp360.us?subject=unsubscribe>');
        $mail->addCustomHeader('List-Unsubscribe-Post', 'List-Unsubscribe=One-Click');
        $mail->addCustomHeader('Return-Path',           $config['from_email']);
        $mail->addCustomHeader('Organization',          'PVP360');
        $mail->addCustomHeader('Precedence',            'bulk');

        if (!empty($attachments)) {
            foreach ($attachments as $path => $name) {
                if (file_exists($path)) $mail->addAttachment($path, $name);
            }
        }

        $mail->isHTML(true);
        $mail->CharSet  = 'UTF-8';
        $mail->Encoding = 'base64';
        $mail->Subject  = $subject;
        $mail->Body     = $body;
        $mail->AltBody  = convertHtmlToPlainText($body);

        $mail->send();
        error_log("PVP360 Email sent to: $to | Subject: $subject");
        return true;

    } catch (Exception $e) {
        error_log("PVP360 Email Error to $to: {$mail->ErrorInfo}");
        error_log("Exception: " . $e->getMessage());
        return false;
    } finally {
        $mail->smtpClose();
    }
}

/* ================================================================
   HTML → PLAIN TEXT
================================================================ */
function convertHtmlToPlainText($html) {
    $text = preg_replace('/<script\b[^>]*>.*?<\/script>/is', '', $html);
    $text = preg_replace('/<style\b[^>]*>.*?<\/style>/is',  '', $text);
    $text = preg_replace('/<br\s*\/?>/i',  "\n",   $text);
    $text = preg_replace('/<\/p>/i',       "\n\n", $text);
    $text = preg_replace('/<\/div>/i',     "\n",   $text);
    $text = strip_tags($text);
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $text = preg_replace('/[ \t]+/',   ' ',    $text);
    $text = preg_replace('/\n\s*\n/', "\n\n", $text);
    return trim($text);
}

/* ================================================================
   SHARED EMAIL WRAPPER
   - Logo image in header (replaces text)
   - Optional $paidBadge to show PAID stamp
================================================================ */
function buildEmailTemplate($title, $badgeText, $badgeColor, $contentHtml, $recipientEmail, $paidBadge = false) {
    $year = date('Y');
    $safeEmail = htmlspecialchars($recipientEmail);
    $unsubLink = 'https://pvp360.us/unsubscribe.php?email=' . urlencode($recipientEmail);

    // PAID stamp HTML (shown only when $paidBadge = true)
    $paidStampHtml = '';
    if ($paidBadge) {
        $paidStampHtml = '
        <!-- PAID STAMP -->
        <tr>
          <td style="padding:0 30px 10px;text-align:center;">
            <div style="display:inline-block;border:3px solid #00b894;border-radius:8px;padding:6px 28px;transform:rotate(-3deg);margin:0 auto;">
              <span style="color:#00b894;font-size:22px;font-weight:900;letter-spacing:4px;font-family:Arial,sans-serif;">&#10003; PAID</span>
            </div>
          </td>
        </tr>';
    }

    return '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>' . $title . '</title>
</head>
<body style="margin:0;padding:0;background:#f0f0f0;font-family:Arial,sans-serif;font-size:14px;color:#333;">

  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f0f0f0;padding:20px 0;">
    <tr><td align="center">
      <table width="580" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:8px;overflow:hidden;border:1px solid #ddd;">

        <!-- HEADER with LOGO IMAGE -->
        <tr>
          <td style="background:#0a0a0a;padding:20px 30px;text-align:center;">
            <img src="https://pvp360.us/zambia/logoo.png"
                 alt="PVP360"
                 width="160"
                 style="display:block;margin:0 auto;max-width:160px;height:auto;border:0;">
            <div style="color:#888;font-size:11px;margin-top:6px;">pvp360.us</div>
          </td>
        </tr>

        <!-- BADGE -->
        <tr>
          <td style="padding:20px 30px 0;text-align:center;">
            <span style="background:' . $badgeColor . ';color:#fff;padding:6px 18px;border-radius:20px;font-size:12px;font-weight:600;">' . $badgeText . '</span>
          </td>
        </tr>

        ' . $paidStampHtml . '

        <!-- CONTENT -->
        <tr>
          <td style="padding:20px 30px 30px;">
            ' . $contentHtml . '
          </td>
        </tr>

        <!-- FOOTER -->
        <tr>
          <td style="background:#f8f8f8;padding:18px 30px;text-align:center;border-top:1px solid #eee;">
            <p style="margin:0 0 6px;font-size:12px;color:#888;">PVP360 Investment Platform &bull; pvp360.us</p>
            <p style="margin:0;font-size:11px;color:#aaa;">
              This email was sent to ' . $safeEmail . ' &nbsp;|&nbsp;
              <a href="' . $unsubLink . '" style="color:#aaa;">Unsubscribe</a>
            </p>
          </td>
        </tr>

      </table>
    </td></tr>
  </table>

</body>
</html>';
}

/* ================================================================
   1. WELCOME EMAIL
================================================================ */
function sendWelcomeEmail($email, $referralCode) {
    $subject = "Welcome to PVP360 - Account Ready";

    $content = '
      <h2 style="margin:0 0 12px;color:#0a0a0a;font-size:20px;">Welcome aboard!</h2>
      <p style="color:#555;line-height:1.7;margin:0 0 20px;">
        Your PVP360 account has been created successfully. You now have access to our investment platform.
      </p>

      <!-- Registration Bonus Box -->
      <table width="100%" cellpadding="0" cellspacing="0" style="background:#eafaf1;border:2px solid #00b894;border-radius:8px;margin:0 0 20px;">
        <tr><td style="padding:14px 18px;text-align:center;">
          <div style="font-size:11px;color:#1a7a4a;font-weight:600;letter-spacing:1px;margin-bottom:6px;">🎁 REGISTRATION BONUS</div>
          <div style="font-size:26px;font-weight:900;color:#00b894;font-family:monospace;">ZMW 15.00</div>
          <div style="font-size:12px;color:#1a7a4a;margin-top:6px;">Has been added to your balance — start investing today!</div>
        </td></tr>
      </table>

      <!-- Referral Code Box -->
      <table width="100%" cellpadding="0" cellspacing="0" style="background:#fffbea;border:2px solid #FFD700;border-radius:8px;margin:0 0 20px;">
        <tr><td style="padding:18px;text-align:center;">
          <div style="font-size:12px;color:#888;margin-bottom:8px;">Your Referral Code</div>
          <div style="font-size:28px;font-weight:700;letter-spacing:5px;color:#0a0a0a;font-family:monospace;">' . htmlspecialchars($referralCode) . '</div>
          <div style="font-size:11px;color:#888;margin-top:8px;">Share this code to earn referral commissions</div>
        </td></tr>
      </table>

      <!-- Quick Info -->
      <table width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 20px;">
        <tr>
          <td style="background:#f8f8f8;border-left:3px solid #FFD700;padding:10px 14px;border-radius:4px;width:48%;vertical-align:top;">
            <div style="font-weight:600;color:#0a0a0a;font-size:13px;">Referral Commissions</div>
            <div style="color:#666;font-size:12px;margin-top:4px;">Level 1: 10% &bull; Level 2: 6% &bull; Level 3: 4%</div>
          </td>
          <td width="4%"></td>
          <td style="background:#f8f8f8;border-left:3px solid #FFD700;padding:10px 14px;border-radius:4px;width:48%;vertical-align:top;">
            <div style="font-weight:600;color:#0a0a0a;font-size:13px;">Min Deposit</div>
            <div style="color:#666;font-size:12px;margin-top:4px;">ZMW 100 &bull; Processed within 1 minute</div>
          </td>
        </tr>
      </table>

      <!-- CTA -->
      <div style="text-align:center;margin-top:10px;">
        <a href="https://pvp360.us/login.php"
           style="background:#0a0a0a;color:#FFD700;padding:13px 32px;text-decoration:none;border-radius:6px;font-weight:600;font-size:14px;display:inline-block;">
          Login to Your Account
        </a>
      </div>
    ';

    $body = buildEmailTemplate('Welcome to PVP360', 'Account Activated', '#00b894', $content, $email);
    return sendEmail($email, $subject, $body);
}

/* ================================================================
   2. DEPOSIT NOTIFICATION
================================================================ */
function sendDepositNotification($email, $amount, $status = 'processing') {
    $date        = date('d M Y, H:i');
    $isProcessed = ($status === 'processed');
    $statusText  = $isProcessed ? 'Approved' : 'Received & Processing';
    $statusColor = $isProcessed ? '#00b894' : '#f39c12';
    $badgeText   = $isProcessed ? 'Deposit Approved' : 'Deposit Received';
    $subject     = "PVP360 - Deposit " . ($isProcessed ? 'Approved' : 'Received') . " | ZMW " . number_format($amount, 2);

    $content = '
      <h2 style="margin:0 0 8px;color:#0a0a0a;font-size:20px;">Deposit ' . ($isProcessed ? 'Approved' : 'Received') . '</h2>
      <p style="color:#555;margin:0 0 20px;line-height:1.6;">
        ' . ($isProcessed
            ? 'Your deposit has been approved and credited to your account balance.'
            : 'We have received your deposit request. It is currently being reviewed.') . '
      </p>

      <!-- Transaction Details Table -->
      <table width="100%" cellpadding="0" cellspacing="0" style="background:#f8f8f8;border-radius:8px;overflow:hidden;margin:0 0 20px;">
        <tr style="background:#0a0a0a;">
          <td colspan="2" style="padding:10px 16px;color:#FFD700;font-size:12px;font-weight:600;letter-spacing:1px;">TRANSACTION DETAILS</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:12px 16px;color:#888;font-size:13px;">Amount</td>
          <td style="padding:12px 16px;text-align:right;font-weight:700;font-size:16px;color:#0a0a0a;">ZMW ' . number_format($amount, 2) . '</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:12px 16px;color:#888;font-size:13px;">Date &amp; Time</td>
          <td style="padding:12px 16px;text-align:right;font-size:13px;color:#333;">' . $date . '</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:12px 16px;color:#888;font-size:13px;">Type</td>
          <td style="padding:12px 16px;text-align:right;font-size:13px;color:#333;">Deposit</td>
        </tr>
        <tr>
          <td style="padding:12px 16px;color:#888;font-size:13px;">Status</td>
          <td style="padding:12px 16px;text-align:right;">
            <span style="background:' . $statusColor . ';color:#fff;padding:3px 12px;border-radius:12px;font-size:12px;font-weight:600;">' . $statusText . '</span>
          </td>
        </tr>
      </table>

      ' . ($isProcessed ? '
      <div style="background:#eafaf1;border:1px solid #00b894;border-radius:6px;padding:12px 16px;font-size:13px;color:#1a7a4a;">
        Your balance has been updated. You can now invest or view your portfolio.
      </div>' : '
      <div style="background:#fffbea;border:1px solid #FFD700;border-radius:6px;padding:12px 16px;font-size:13px;color:#856404;">
        <strong>Processing Time:</strong> Your deposit is normally approved within 1 minute during business hours.
      </div>') . '

      <div style="text-align:center;margin-top:20px;">
        <a href="https://pvp360.us/home.php"
           style="background:#0a0a0a;color:#FFD700;padding:12px 28px;text-decoration:none;border-radius:6px;font-weight:600;font-size:13px;display:inline-block;">
          View Dashboard
        </a>
      </div>
    ';

    // Show PAID badge only when deposit is approved/processed
    $showPaid = $isProcessed;

    $body = buildEmailTemplate('Deposit Notification', $badgeText, $statusColor, $content, $email, $showPaid);
    return sendEmail($email, $subject, $body);
}

/* ================================================================
   3. WITHDRAWAL NOTIFICATION
================================================================ */
function sendWithdrawalNotification($email, $amount, $status = 'processing') {
    $feePercent = 8;
    $feeAmount  = ($amount * $feePercent) / 100;
    $netAmount  = $amount - $feeAmount;
    $date       = date('d M Y, H:i');

    $statusText  = $status === 'processed' ? 'Completed' : ($status === 'rejected' ? 'Rejected' : 'Processing');
    $statusColor = $status === 'processed' ? '#00b894' : ($status === 'rejected' ? '#e74c3c' : '#f39c12');
    $badgeText   = 'Withdrawal ' . $statusText;
    $subject     = "PVP360 - Withdrawal " . $statusText . " | ZMW " . number_format($amount, 2);

    $statusNote = '';
    if ($status === 'processing') {
        $statusNote = '<div style="background:#fffbea;border:1px solid #FFD700;border-radius:6px;padding:12px 16px;font-size:13px;color:#856404;margin-top:16px;">
            <strong>Processing Time:</strong> Withdrawals are processed within 1 minute during business hours.
        </div>';
    } elseif ($status === 'processed') {
        $statusNote = '<div style="background:#eafaf1;border:1px solid #00b894;border-radius:6px;padding:12px 16px;font-size:13px;color:#1a7a4a;margin-top:16px;">
            Your withdrawal has been sent. Please allow a few minutes for funds to reflect in your account.
        </div>';
    } elseif ($status === 'rejected') {
        $statusNote = '<div style="background:#fdecea;border:1px solid #e74c3c;border-radius:6px;padding:12px 16px;font-size:13px;color:#a61c00;margin-top:16px;">
            Your withdrawal was not approved. Please contact support at <a href="mailto:pvp360@pvp360.us" style="color:#a61c00;">pvp360@pvp360.us</a> for assistance.
        </div>';
    }

    $content = '
      <h2 style="margin:0 0 8px;color:#0a0a0a;font-size:20px;">Withdrawal ' . $statusText . '</h2>
      <p style="color:#555;margin:0 0 20px;line-height:1.6;">
        Here is a summary of your withdrawal request.
      </p>

      <!-- Transaction Details Table -->
      <table width="100%" cellpadding="0" cellspacing="0" style="background:#f8f8f8;border-radius:8px;overflow:hidden;margin:0 0 6px;">
        <tr style="background:#0a0a0a;">
          <td colspan="2" style="padding:10px 16px;color:#FFD700;font-size:12px;font-weight:600;letter-spacing:1px;">TRANSACTION DETAILS</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:12px 16px;color:#888;font-size:13px;">Amount Requested</td>
          <td style="padding:12px 16px;text-align:right;font-weight:700;font-size:16px;color:#0a0a0a;">ZMW ' . number_format($amount, 2) . '</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:12px 16px;color:#888;font-size:13px;">Service Fee (' . $feePercent . '%)</td>
          <td style="padding:12px 16px;text-align:right;font-size:13px;color:#e74c3c;font-weight:600;">- ZMW ' . number_format($feeAmount, 2) . '</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;background:#fff;">
          <td style="padding:12px 16px;color:#0a0a0a;font-size:13px;font-weight:600;">You Receive</td>
          <td style="padding:12px 16px;text-align:right;font-size:15px;color:#00b894;font-weight:700;">ZMW ' . number_format($netAmount, 2) . '</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:12px 16px;color:#888;font-size:13px;">Date &amp; Time</td>
          <td style="padding:12px 16px;text-align:right;font-size:13px;color:#333;">' . $date . '</td>
        </tr>
        <tr>
          <td style="padding:12px 16px;color:#888;font-size:13px;">Status</td>
          <td style="padding:12px 16px;text-align:right;">
            <span style="background:' . $statusColor . ';color:#fff;padding:3px 12px;border-radius:12px;font-size:12px;font-weight:600;">' . $statusText . '</span>
          </td>
        </tr>
      </table>

      ' . $statusNote . '

      <div style="text-align:center;margin-top:20px;">
        <a href="https://pvp360.us/withdraw.php"
           style="background:#0a0a0a;color:#FFD700;padding:12px 28px;text-decoration:none;border-radius:6px;font-weight:600;font-size:13px;display:inline-block;">
          View Withdrawal History
        </a>
      </div>
    ';

    // Show PAID badge only when withdrawal is completed/processed
    $showPaid = ($status === 'processed');

    $body = buildEmailTemplate('Withdrawal Notification', $badgeText, $statusColor, $content, $email, $showPaid);
    return sendEmail($email, $subject, $body);
}

/* ================================================================
   4. LOGIN ALERT EMAIL
================================================================ */
function sendLoginAlert($email, $phone, $loginTime, $ipAddress, $device) {
    $subject = "PVP360 - New Login to Your Account";

    $content = '
      <h2 style="margin:0 0 8px;color:#0a0a0a;font-size:20px;">New Login Detected</h2>
      <p style="color:#555;margin:0 0 20px;line-height:1.6;">
        A login to your PVP360 account was just recorded. If this was you, no action is needed.
      </p>

      <table width="100%" cellpadding="0" cellspacing="0" style="background:#f8f8f8;border-radius:8px;overflow:hidden;margin:0 0 16px;">
        <tr style="background:#0a0a0a;">
          <td colspan="2" style="padding:10px 16px;color:#FFD700;font-size:12px;font-weight:600;letter-spacing:1px;">LOGIN DETAILS</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:11px 16px;color:#888;font-size:13px;">Email</td>
          <td style="padding:11px 16px;text-align:right;font-size:13px;color:#333;">' . htmlspecialchars($email) . '</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:11px 16px;color:#888;font-size:13px;">Phone</td>
          <td style="padding:11px 16px;text-align:right;font-size:13px;color:#333;">' . htmlspecialchars($phone) . '</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:11px 16px;color:#888;font-size:13px;">Date &amp; Time</td>
          <td style="padding:11px 16px;text-align:right;font-size:13px;color:#333;">' . htmlspecialchars($loginTime) . '</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:11px 16px;color:#888;font-size:13px;">IP Address</td>
          <td style="padding:11px 16px;text-align:right;font-size:13px;color:#333;">' . htmlspecialchars($ipAddress) . '</td>
        </tr>
        <tr>
          <td style="padding:11px 16px;color:#888;font-size:13px;">Device</td>
          <td style="padding:11px 16px;text-align:right;font-size:13px;color:#333;">' . htmlspecialchars($device) . '</td>
        </tr>
      </table>

      <div style="background:#fff3cd;border:1px solid #ffc107;border-radius:6px;padding:14px 16px;font-size:13px;color:#856404;">
        <strong>Was this not you?</strong> Change your password immediately and contact our support team.
        <div style="margin-top:12px;text-align:center;">
          <a href="https://pvp360.us/change_password.php"
             style="background:#0a0a0a;color:#FFD700;padding:10px 22px;text-decoration:none;border-radius:5px;font-weight:600;font-size:12px;display:inline-block;margin-right:8px;">
            Change Password
          </a>
          <a href="mailto:pvp360@pvp360.us"
             style="background:#6c757d;color:#fff;padding:10px 22px;text-decoration:none;border-radius:5px;font-weight:600;font-size:12px;display:inline-block;">
            Contact Support
          </a>
        </div>
      </div>

      <p style="font-size:12px;color:#aaa;margin-top:16px;text-align:center;">
        PVP360 will never ask for your password via email or phone.
      </p>
    ';

    $body = buildEmailTemplate('Security Alert', 'Login Alert', '#e74c3c', $content, $email);
    return sendEmail($email, $subject, $body);
}

/* ================================================================
   5. TEST EMAIL
================================================================ */
function testEmailConfiguration($testEmail) {
    $subject = "PVP360 - Email Configuration Test";

    $content = '
      <h2 style="margin:0 0 12px;color:#0a0a0a;">Email Configuration Test</h2>
      <p style="color:#555;margin:0 0 16px;">If you received this, your SMTP configuration is working correctly.</p>

      <table width="100%" cellpadding="0" cellspacing="0" style="background:#f8f8f8;border-radius:6px;">
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:10px 16px;color:#888;font-size:13px;">Date</td>
          <td style="padding:10px 16px;text-align:right;font-size:13px;">' . date('Y-m-d H:i:s') . '</td>
        </tr>
        <tr style="border-bottom:1px solid #eee;">
          <td style="padding:10px 16px;color:#888;font-size:13px;">Server</td>
          <td style="padding:10px 16px;text-align:right;font-size:13px;">' . ($_SERVER['SERVER_NAME'] ?? 'Unknown') . '</td>
        </tr>
        <tr>
          <td style="padding:10px 16px;color:#888;font-size:13px;">PHP</td>
          <td style="padding:10px 16px;text-align:right;font-size:13px;">' . phpversion() . '</td>
        </tr>
      </table>
    ';

    $body = buildEmailTemplate('Email Test', 'Configuration Test', '#0a0a0a', $content, $testEmail);
    return sendEmail($testEmail, $subject, $body);
}

/* ================================================================
   UTILITY FUNCTIONS
================================================================ */
function getUserDevice() {
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    if (preg_match('/mobile/i', $ua))  return 'Mobile Device';
    if (preg_match('/tablet/i', $ua))  return 'Tablet';
    return 'Desktop / Laptop';
}

function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP']))        return $_SERVER['HTTP_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    return $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
}