<?php
session_start();
require '../config.php';

// Load settings
$stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC LIMIT 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);

$cname  = $settings['domain_name'];
$curl   = $settings['url'];
$cemail = $settings['email2'];   // system email
$cpass  = $settings['password']; // smtp password
$chost  = $settings['contact_email'];
$cport  = $settings['service1'];
$cright = $settings['copyright'];
$logo   = $settings['logo'];     // logo URL
$adminEmail = $settings['admin_email'] ?? $cemail; // fallback

// PHPMailer
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function sendEmail($to, $subject, $body) {
    global $chost, $cemail, $cpass, $cname, $cport;

    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = $chost;
        $mail->SMTPAuth   = true;
        $mail->Username   = $cemail;
        $mail->Password   = $cpass;
        $mail->Port       = $cport;
        $mail->SMTPSecure = ($cport == 465) ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;

        $mail->setFrom($cemail, $cname);
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("PHPMailer error: " . $mail->ErrorInfo);
        return false;
    }
}

// Helper: Get client IP
function getClientIp() {
    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';
}

// Helper: Get country by IP (using ip-api.com)
function getCountryByIp($ip) {
    $resp = @file_get_contents("http://ip-api.com/json/$ip?fields=country");
    if ($resp) {
        $data = json_decode($resp, true);
        return $data['country'] ?? 'Unknown';
    }
    return 'Unknown';
}

$message = "";

// Handle verification
if ($_SERVER["REQUEST_METHOD"] === "POST" || (isset($_GET['email']) && isset($_GET['code']))) {
    $email = $_POST['email'] ?? $_GET['email'];
    $code  = $_POST['vcode'] ?? $_GET['code'];

    if ($email && $code) {
        $stmt = $pdo->prepare("SELECT * FROM logins WHERE email = :email AND vcode = :code AND vstatus = 0 LIMIT 1");
        $stmt->execute([':email' => $email, ':code' => $code]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            // Mark verified
            $update = $pdo->prepare("UPDATE logins SET vstatus = 1, vcode = NULL WHERE email = :email");
            $update->execute([':email' => $email]);

            // Get IP & Country
            $ip = getClientIp();
            $country = getCountryByIp($ip);

            // ================= USER WELCOME EMAIL =================
            $userSubject = "🎉 Welcome to $cname - Your Account is Verified!";
            $userBody = "
            <div style='background:#f4f7fa;padding:20px;text-align:center;font-family:Arial,sans-serif;'>
              <div style='max-width:600px;margin:auto;background:#fff;border-radius:10px;box-shadow:0 4px 12px rgba(0,0,0,0.1);overflow:hidden;'>
                <div style='background:linear-gradient(135deg,#4facfe,#00f2fe);padding:30px 20px;'>
                  <img src='$logo' alt='$cname Logo' style='max-width:120px;display:block;margin:0 auto 10px;'>
                  <h1 style='color:#fff;margin:0;font-size:28px;'>Welcome, {$user['username']}!</h1>
                </div>
                <div style='padding:30px;text-align:left;color:#333;line-height:1.6;'>
                  <p>Hi <b>{$user['username']}</b>,</p>
                  <p>Your email has been successfully verified. 🎉</p>
                  <p><b>Email:</b> {$user['email']}<br>
                  <b>Password:</b> ######## (hidden for security)</p>
                  <p style='margin:20px 0;'>Click below to access your dashboard:</p>
                  <p style='text-align:center;'>
                    <a href='{$curl}invest' style='background:#4facfe;color:#fff;padding:14px 28px;font-size:16px;text-decoration:none;border-radius:6px;display:inline-block;'>
                      Go to Dashboard
                    </a>
                  </p>
                  <p style='margin-top:25px;font-size:13px;color:#777;text-align:center;'>If you did not create this account, please contact support.</p>
                </div>
                <div style='background:#f9f9f9;padding:15px;text-align:center;font-size:12px;color:#888;'>
                  $cright
                </div>
              </div>
            </div>";

            // ================= ADMIN NOTIFICATION EMAIL =================
          // ================= USER WELCOME EMAIL =================
// ================= USER WELCOME EMAIL =================
$userSubject = "&#127881; Welcome to $cname - Your Account is Verified!";
$userBody = "
<div style='background:#f4f7fa;padding:20px;text-align:center;font-family:Arial,sans-serif;'>
  <div style='max-width:600px;margin:auto;background:#fff;border-radius:10px;box-shadow:0 4px 12px rgba(0,0,0,0.1);overflow:hidden;'>
    <div style='background:linear-gradient(135deg,#4facfe,#00f2fe);padding:30px 20px;'>
      <img src='$logo' alt='$cname Logo' style='max-width:120px;display:block;margin:0 auto 10px;'>
      <h1 style='color:#fff;margin:0;font-size:28px;'>Welcome, {$user['username']}!</h1>
    </div>
    <div style='padding:30px;text-align:left;color:#333;line-height:1.6;'>
      <p>Hi <b>{$user['username']}</b>,</p>
      <p>Your email has been successfully verified. &#127881;</p>
      <p><b>Email:</b> {$user['email']}</p>
      <p style='margin:20px 0;'>Click below to access your dashboard:</p>
      <p style='text-align:center;'>
        <a href='{$curl}invest' style='background:#4facfe;color:#fff;padding:14px 28px;font-size:16px;text-decoration:none;border-radius:6px;display:inline-block;'>
          Go to Dashboard
        </a>
      </p>
      <p style='margin-top:25px;font-size:13px;color:#777;text-align:center;'>If you did not create this account, please contact support.</p>
    </div>
    <div style='background:#f9f9f9;padding:15px;text-align:center;font-size:12px;color:#888;'>
      $cright
    </div>
  </div>
</div>";


// ================= ADMIN NOTIFICATION EMAIL =================
$adminSubject = "&#128226; New User Verified - $cname"; // 📢 -> &#128226;
$adminBody = "
<div style='background:#f4f7fa;padding:20px;text-align:center;font-family:Arial,sans-serif;'>
  <div style='max-width:600px;margin:auto;background:#fff;border-radius:10px;box-shadow:0 4px 12px rgba(0,0,0,0.1);overflow:hidden;'>
    <div style='background:linear-gradient(135deg,#4facfe,#00f2fe);padding:25px 20px;'>
      <img src='$logo' alt='$cname Logo' style='max-width:120px;display:block;margin:0 auto 10px;'>
      <h1 style='color:#fff;margin:0;font-size:24px;'>New User Verified</h1>
    </div>
    <div style='padding:30px;text-align:left;color:#333;line-height:1.6;'>
      <p>Hello Admin,</p>
      <p>A new user has just verified their account.</p>
      <p><b>Username:</b> {$user['username']}<br>
      <b>Email:</b> {$user['email']}<br>
      <b>IP:</b> $ip<br>
      <b>Country:</b> $country<br>
      <b>Date:</b> " . date("Y-m-d H:i:s") . "</p>
      <p style='margin-top:25px;font-size:13px;color:#777;text-align:center;'>This is an automated notification from $cname.</p>
    </div>
    <div style='background:#f9f9f9;padding:15px;text-align:center;font-size:12px;color:#888;'>
      $cright
    </div>
  </div>
</div>";


            // Send to user
            sendEmail($user['email'], $userSubject, $userBody);

            // Send to admin
            sendEmail($adminEmail, $adminSubject, $adminBody);

            $message = "<p style='color:green; font-weight:bold;'>✅ Email verified successfully! A welcome email has been sent. <a href='login.php'>Login</a>.</p>";
        } else {
            $message = "<p style='color:red; font-weight:bold;'>❌ Invalid verification code or already verified.</p>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Email Verification - <?= htmlspecialchars($cname) ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    /* Background Gradient */
    body {
      margin: 0;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background: linear-gradient(135deg, #4facfe, #00f2fe);
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      overflow-x: hidden;
    }

    /* Fade In Animation */
    .fade-in {
      animation: fadeIn 1.2s ease-in-out;
    }
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(20px); }
      to { opacity: 1; transform: translateY(0); }
    }

    /* Fade Out (for messages) */
    .fade-out {
      animation: fadeOut 1.2s ease-in-out forwards;
    }
    @keyframes fadeOut {
      from { opacity: 1; }
      to { opacity: 0; transform: translateY(-20px); }
    }

    /* Container */
    .container {
      background: #fff;
      padding: 30px;
      border-radius: 15px;
      box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
      width: 100%;
      max-width: 420px;
      text-align: center;
      transition: transform 0.3s ease;
    }
    .container:hover {
      transform: translateY(-5px);
    }

    h2 {
      margin-bottom: 20px;
      color: #333;
      font-size: 24px;
    }

    /* Input Fields */
    input {
      width: 100%;
      padding: 12px 15px;
      margin: 10px 0;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-size: 15px;
      transition: border 0.3s, box-shadow 0.3s;
    }
    input:focus {
      border-color: #4facfe;
      box-shadow: 0 0 8px rgba(79, 172, 254, 0.5);
      outline: none;
    }

    /* Button */
    button {
      width: 100%;
      padding: 14px;
      background: linear-gradient(135deg, #4facfe, #00f2fe);
      color: #fff;
      font-size: 16px;
      font-weight: bold;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      transition: background 0.3s, transform 0.2s;
    }
    button:hover {
      transform: scale(1.05);
      background: linear-gradient(135deg, #00f2fe, #4facfe);
    }

    /* Message */
    .message {
      margin: 15px 0;
      padding: 10px;
      border-radius: 8px;
      font-size: 14px;
      animation: fadeIn 1s ease;
    }
    .message.success {
      background: #e6ffed;
      color: #28a745;
      border: 1px solid #28a745;
    }
    .message.error {
      background: #ffe6e6;
      color: #dc3545;
      border: 1px solid #dc3545;
    }

    /* Mobile Responsive */
    @media (max-width: 480px) {
      .container {
        padding: 20px;
        margin: 10px;
      }
      h2 {
        font-size: 20px;
      }
    }
  </style>
</head>
<body>
  <div class="container fade-in">
    <h2>Email Verification</h2>

    <?php if (!empty($message)) : ?>
      <div class="message <?= strpos($message, '✅') !== false ? 'success' : 'error' ?>" id="msgBox">
        <?= $message ?>
      </div>
    <?php endif; ?>

    <form method="POST">
      <input type="email" name="email" placeholder="Enter your email" required>
      <input type="text" name="vcode" placeholder="Enter verification code" required>
      <button type="submit">Verify Email</button>
    </form>
  </div>

  <script>
    // Auto fade-out success/error message after 5 seconds
    window.addEventListener('DOMContentLoaded', () => {
      const msgBox = document.getElementById('msgBox');
      if (msgBox) {
        setTimeout(() => {
          msgBox.classList.add('fade-out');
        }, 5000);
      }
    });
  </script>
</body>
</html>
