<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../../config.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../PHPMailer-master/src/Exception.php';
require '../PHPMailer-master/src/PHPMailer.php';
require '../PHPMailer-master/src/SMTP.php';

header('Content-Type: application/json');

if (!isset($_SESSION['verify_email'])) {
    echo json_encode(['status' => 'error', 'message' => 'Session expired. Please sign up again.']); exit();
}

$email = $_SESSION['verify_email'];
$ip = $_SERVER['REMOTE_ADDR'];

// ব্রাউজার কুকি চেক (যদি আইপি চেঞ্জ করেও আসে)
if (isset($_COOKIE['block_verify'])) {
    echo json_encode(['status' => 'error', 'message' => 'Security Alert: You are blocked for 3 hours due to multiple attempts.']); exit();
}

// IP Tracking এর জন্য অটোমেটিক টেবিল তৈরি
$conn->query("CREATE TABLE IF NOT EXISTS ip_blocks (ip VARCHAR(45) PRIMARY KEY, attempts INT DEFAULT 1, blocked_until INT DEFAULT 0)");

$block_check = $conn->query("SELECT * FROM ip_blocks WHERE ip='$ip'");
if ($block_check->num_rows > 0) {
    $row = $block_check->fetch_assoc();
    if ($row['blocked_until'] > time()) {
        echo json_encode(['status' => 'error', 'message' => 'Your IP is temporarily blocked for 3 hours.']); exit();
    }
    
    $attempts = $row['attempts'] + 1;
    if ($attempts > 3) {
        $block_time = time() + (3 * 3600); // ৩ ঘণ্টা ব্লক
        $conn->query("UPDATE ip_blocks SET attempts=$attempts, blocked_until=$block_time WHERE ip='$ip'");
        setcookie("block_verify", "true", time() + (3 * 3600), "/"); // ব্রাউজার কুকি সেট
        echo json_encode(['status' => 'error', 'message' => 'Max limit reached! Your IP is blocked for 3 hours.']); exit();
    } else {
        $conn->query("UPDATE ip_blocks SET attempts=$attempts WHERE ip='$ip'");
    }
} else {
    $conn->query("INSERT INTO ip_blocks (ip, attempts) VALUES ('$ip', 1)");
}

// নতুন OTP জেনারেট
$new_otp = rand(100000, 999999);
$_SESSION['otp_expire'] = time() + 300; 

// নতুন অটো-ভেরিফাই লিংক তৈরি
$enc_email = base64_encode($email);
$enc_otp = base64_encode($new_otp);
$magic_link = "https://" . $_SERVER['HTTP_HOST'] . "/signup/verify/?e=$enc_email&c=$enc_otp";

// ইউজারের নাম নেওয়া ইমেইলের জন্য
$user_data = $conn->query("SELECT fullname FROM users WHERE email='$email'")->fetch_assoc();
$fullname = $user_data['fullname'] ?? 'User';

// ডাটাবেসে OTP আপডেট করা
$stmt = $conn->prepare("UPDATE users SET otp=? WHERE email=? AND is_verified=0");
$stmt->bind_param("ss", $new_otp, $email);

if ($stmt->execute() && $stmt->affected_rows > 0) {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = 'mail.invoice-generatorfree.com'; 
        $mail->SMTPAuth = true;
        $mail->Username = 'support@invoice-generatorfree.com'; 
        $mail->Password = '@##Mdhasan.com24';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; 
        $mail->Port = 465;
        $mail->SMTPOptions = array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true));

        $mail->setFrom('support@invoice-generatorfree.com', 'Invoice Generator');
        $mail->addAddress($email, $fullname);
        $mail->isHTML(true);
        $mail->Subject = 'New Secure Verification Code - Invoice Generator';
        
        // হুবহু প্রথম মেইলের মতো প্রফেশনাল, সফট ও ক্লিন ইমেইল বডি
        $mail->Body = "
        <div style=\"max-width: 600px; margin: 0 auto; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; border: 1px solid #e2e8f0; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.03);\">
            <div style=\"background-color: #1e293b; padding: 20px 0; text-align: center;\">
                <h2 style=\"color: #ffffff; margin: 0; font-size: 22px; font-weight: 500; letter-spacing: 1px;\">Invoice Generator</h2>
            </div>
            <div style=\"padding: 35px 40px; background-color: #ffffff;\">
                <h3 style=\"color: #334155; margin-top: 0; font-size: 18px; font-weight: 600;\">Hello $fullname,</h3>
                <p style=\"color: #475569; font-size: 15px; line-height: 1.6; margin-bottom: 25px;\">You requested a new verification code. To complete your secure verification, please use the following 6-digit code. This code is valid for <strong>5 minutes</strong>.</p>
                
                <div style=\"text-align: center; margin: 30px 0;\">
                    <div style=\"display: inline-block; font-size: 28px; font-weight: 600; letter-spacing: 8px; color: #15803d; background-color: #f0fdf4; padding: 10px 25px; border-radius: 6px; border: 1px solid #bbf7d0; white-space: nowrap;\">$new_otp</div>
                </div>
                
                <p style=\"color: #475569; font-size: 14px; text-align: center; margin-bottom: 20px;\">Or verify automatically by clicking the button below:</p>
                <div style=\"text-align: center; margin-bottom: 30px;\">
                    <a href=\"$magic_link\" style=\"background-color: #2ecc71; color: #ffffff; text-decoration: none; padding: 12px 30px; border-radius: 6px; font-size: 15px; font-weight: 600; display: inline-block; transition: 0.3s;\">Verify My Account</a>
                </div>
                
                <hr style=\"border: none; border-top: 1px solid #e2e8f0; margin: 30px 0;\">
                
                <div style=\"background-color: #fffaf0; border-left: 4px solid #f59e0b; padding: 15px 20px; border-radius: 4px;\">
                    <p style=\"margin: 0; color: #92400e; font-size: 13px; line-height: 1.5;\"><strong>Security Alert:</strong> Never share this code with anyone. Our support team will never ask for your verification code or password.</p>
                </div>
            </div>
        </div>";
        
        $mail->send();
        echo json_encode(['status' => 'success', 'message' => 'New verification code sent successfully!']);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => 'Failed to send email.']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Account already verified or invalid.']);
}
?>