<?php
session_start();
require_once 'db.php';
require 'vendor/autoload.php';

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

if (!isset($_SESSION['pending_email'])) {
    header('Location: login.php');
    exit;
}

$error = '';
$success = '';

$db = new Database();
$conn = $db->connect();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_code'])) {
    $code = trim($_POST['code']);
    
    $stmt = $conn->prepare("SELECT id, username, email FROM utilisateurs WHERE email = ? AND verification_code = ?");
    $stmt->execute([$_SESSION['pending_email'], $code]);
    
    if ($stmt->rowCount() > 0) {
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $updateStmt = $conn->prepare("UPDATE utilisateurs SET is_verified = 1, verification_code = NULL WHERE id = ?");
        if ($updateStmt->execute([$user['id']])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            unset($_SESSION['pending_email']);
            
            // Envoi de l'email de bienvenue après vérification réussie
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host = 'mail.imators.systems';
                $mail->SMTPAuth = true;
                $mail->Username = 'no-reply@imators.systems';
                $mail->Password = 'imators.managements4455*#@';
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port = 587;
                
                $mail->setFrom('no-reply@imators.systems', 'Imators');
                $mail->addAddress($user['email']);
                
                $mail->isHTML(true);
                $mail->Subject = 'Welcome to Imators!';
                
                $mail->Body = '
                    <div style="font-family: \'Poppins\', sans-serif; max-width: 600px; margin: 0 auto;">
                        <div style="background: #1a1a1a; padding: 30px; border-radius: 10px; color: white;">                           
                            <h1 style="margin-bottom: 20px;">Welcome to Imators, ' . htmlspecialchars($user['username']) . '!</h1>
                            <p style="margin-bottom: 30px;">
                                Your account has been successfully verified. You now have full access to Imators and its amazing features. 
                                We\'re excited to have you on board and can\'t wait to see what you\'ll accomplish.
                            </p>
                            <a href="https://idsma.imators.com/dashboard.php" style="display: inline-block; background-color: #00ff00; color: black; padding: 10px 20px; text-decoration: none; border-radius: 5px;">
                                Go to Dashboard
                            </a>
                        </div>
                    </div>';

                $mail->send();
            } catch (Exception $e) {
                // Log error but don't stop the process
                error_log("Welcome email error: " . $mail->ErrorInfo);
            }
            
            header('Location: dashboard.php');
            exit();
        }
    } else {
        $error = "Code incorrect. Please try again.";
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['resend_code'])) {
    $code = sprintf("%06d", mt_rand(0, 999999));
    
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = 'mail.imators.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@imators.com';
        $mail->Password = 'imators.managements4455*#@';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        
        $mail->setFrom('no-reply@imators.com', 'Imators');
        $mail->addAddress($_SESSION['pending_email']);
        
        $mail->isHTML(true);
        $mail->Subject = 'Your Verification Code';
        
        $mail->Body = '
            <div style="font-family: \'Poppins\', sans-serif; max-width: 600px; margin: 0 auto;">
                <div style="background: #1a1a1a; padding: 30px; border-radius: 10px; color: white;">
                    <img src="https://cdn.imators.com/logo.png" alt="Imators Logo" style="width: 40px; margin: 4px 0;">
                    <h1 style="margin-bottom: 20px;">Your verification code</h1>
                    <p style="margin-bottom: 30px;">A registration has been launched to create an Imators account with this email address. The account is not yet validated but you will use this code to validate it. If unfortunately it is not you who have tried this action, do not panic! You simply have to ignore this email and we will take care of deleting your account. For more information about Imators, do not hesitate to visit our <a href="https://imators.com/terms-of-use">terms and conditions</a></p>
                    <div style="background: #000; padding: 20px; border-radius: 5px; text-align: center; font-size: 24px; letter-spacing: 5px; margin-bottom: 30px;">
                        ' . $code . '
                    </div>
                </div>
            </div>';

        if ($mail->send()) {
            $stmt = $conn->prepare("UPDATE utilisateurs SET verification_code = ? WHERE email = ?");
            $stmt->execute([$code, $_SESSION['pending_email']]);
            $success = "New verification code sent!";
        }
    } catch (Exception $e) {
        $error = "Could not send verification code. Please try again.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify Email - Imators</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(to bottom, #000000, #111111);
        }
        .code-input {
            width: 50px !important;
            height: 60px;
            padding: 0 !important;
            font-size: 24px;
            text-align: center;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            background: rgba(0, 0, 0, 0.3);
            color: white;
        }
        .code-input:focus {
            outline: none;
            border-color: rgba(255, 255, 255, 0.3);
            box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
        }
    </style>
</head>
<body class="bg-black min-h-screen text-white">
    <div class="flex flex-col items-center justify-center min-h-screen p-4">
        <div class="w-full max-w-md">
            <div class="text-center mb-8">
                <img src="https://cdn.imators.com/logo.png" alt="Imators Logo" class="h-12 mx-auto mb-8">
                <h1 class="text-2xl font-semibold mb-2">Verify your email</h1>
                <p class="text-gray-400">We've sent a verification code to<br><?php echo htmlspecialchars($_SESSION['pending_email']); ?></p>
            </div>

            <?php if ($error): ?>
                <div class="bg-red-500/10 border border-red-500/20 text-red-400 p-4 rounded-lg mb-6">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="bg-green-500/10 border border-green-500/20 text-green-400 p-4 rounded-lg mb-6">
                    <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>

            <div class="bg-gray-900/80 rounded-lg p-8">
                <form method="POST" id="verificationForm" class="space-y-6">
                    <div>
                        <label class="block text-sm font-medium mb-4 text-gray-300">Enter verification code</label>
                        <div class="flex justify-center gap-2 mb-4">
                            <input type="number" maxlength="1" class="code-input" data-index="0" min="0" max="9" pattern="[0-9]*" inputmode="numeric">
                            <input type="number" maxlength="1" class="code-input" data-index="1" min="0" max="9" pattern="[0-9]*" inputmode="numeric">
                            <input type="number" maxlength="1" class="code-input" data-index="2" min="0" max="9" pattern="[0-9]*" inputmode="numeric">
                            <input type="number" maxlength="1" class="code-input" data-index="3" min="0" max="9" pattern="[0-9]*" inputmode="numeric">
                            <input type="number" maxlength="1" class="code-input" data-index="4" min="0" max="9" pattern="[0-9]*" inputmode="numeric">
                            <input type="number" maxlength="1" class="code-input" data-index="5" min="0" max="9" pattern="[0-9]*" inputmode="numeric">
                        </div>
                        <input type="hidden" name="code" id="finalCode">
                    </div>

                    <button type="submit" name="verify_code" class="w-full bg-white text-black py-3 px-6 rounded-lg font-medium hover:bg-gray-100">
                        Verify Email
                    </button>

                    <div class="text-center pt-4 border-t border-gray-800">
                        <p class="text-gray-400 text-sm mb-2">Didn't receive the code?</p>
                        <button type="submit" name="resend_code" class="text-white text-sm hover:underline focus:outline-none">
                            Send it again
                        </button>
                    </div>
                </form>
            </div>

            <div class="text-center mt-6">
                <a href="logout.php" class="text-gray-400 text-sm hover:text-white">
                    Use a different email
                </a>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('verificationForm');
    const inputs = [...document.querySelectorAll('.code-input')];
    const finalCode = document.getElementById('finalCode');

    inputs[0].focus();

    inputs.forEach((input, index) => {
        input.addEventListener('input', function(e) {
            let value = this.value;
            
            if (value.length >= 1) {
                value = value.slice(-1);
                this.value = value;
                if (index < inputs.length - 1) {
                    inputs[index + 1].focus();
                }
            }

            const code = inputs.map(input => input.value).join('');
            finalCode.value = code;
        });

        input.addEventListener('keydown', function(e) {
            if (e.key === 'Backspace' && !this.value && index > 0) {
                inputs[index - 1].focus();
                inputs[index - 1].value = '';
                finalCode.value = inputs.map(input => input.value).join('');
            }
        });
    });

    form.addEventListener('keypress', function(e) {
        if(e.key === 'Enter') {
            e.preventDefault();
        }
    });

    form.addEventListener('submit', function(e) {
        if(!e.submitter || e.submitter.name !== 'verify_code') {
            const code = inputs.map(input => input.value).join('');
            finalCode.value = code;
        }
    });
});
    </script>
</body>
</html>