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

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

date_default_timezone_set('Europe/Brussels');

if(isset($_SESSION['user_id'])) {
    $redirect_url = "https://idsma.imators.com/dashboard.php";
    
    if (isset($_GET['forumconnectionaccount']) && !empty($_GET['forumconnectionaccount'])) {
        $redirect_url = $_GET['forumconnectionaccount'];
        
        if (strpos($redirect_url, '/new-post') !== false) {
            $redirect_url .= (strpos($redirect_url, '?') !== false ? '&' : '?') . 'auth_token=' . $_SESSION['user_id'];
        }
    }
    
    header('Location: ' . $redirect_url);
    exit;
}

if(isset($_SESSION['user_id'])) {
    $redirect_url = "https://idsma.imators.com/dashboard.php";
    
    if (isset($_GET['notification']) && !empty($_GET['notification'])) {
        $redirect_url = $_GET['notification'];
        
        if (strpos($redirect_url, '/dashboard') !== false) {
            $redirect_url .= (strpos($redirect_url, '?') !== false ? '&' : '?') . 'auth_token=' . $_SESSION['user_id'];
        }
    }
    
    header('Location: ' . $redirect_url);
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    
    try {
        $db = new Database();
        $conn = $db->connect();

        $stmt = $conn->prepare("SELECT * FROM utilisateurs WHERE email = ? AND is_verified = 1 LIMIT 1");
        $stmt->execute([$email]);
        
        if($stmt->rowCount() > 0) {
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $token = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', time() + 3600);
            
            $stmt = $conn->prepare("INSERT INTO password_resets (user_id, token, expires_at) VALUES (?, ?, ?)");
            $stmt->execute([$user['id'], $token, $expires]);
            
            $reset_link = "https://idsma.imators.com/reset-password.php?token=" . $token;
            
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host = 'mail.imators.com';
                $mail->SMTPAuth = true;
                $mail->Username = 'no-reply@imators.systems';
                $mail->Password = 'imators.managements4455*#@';
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port = 587;
                $mail->SMTPOptions = [
                    'ssl' => [
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                    ]
                ];

                $mail->setFrom('no-reply@imators.systems', 'Imators');
                $mail->addAddress($email);
                $mail->addReplyTo('no-reply@imators.systems', 'No Reply');
                $mail->isHTML(true);
                $mail->Subject = 'Password Reset Request';
                
                $stmt = $conn->prepare("SELECT `profile-picture` FROM utilisateurs WHERE id = ?");
                $stmt->execute([$user['id']]);
                $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
                $profile_picture = $user_data['profile-picture'] ?? 'https://cdn.imators.com/default-profile.png';
                
                $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;">
                            <div style="text-align: center; margin-bottom: 20px;">
                                <img src="' . $profile_picture . '" alt="Profile Picture" style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover; border: 2px solid #00ff00;">
                            </div>
                            <h1 style="margin-bottom: 20px;">Password Reset Request</h1>
                            <p style="margin-bottom: 20px;">We received a request to reset your password. Click the button below to create a new password:</p>
                            <a href="' . $reset_link . '" style="display: inline-block; background-color: #00ff00; color: black; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-bottom: 20px;">
                                Reset My Password
                            </a>
                            <p style="margin-bottom: 10px;">This link will expire in 1 hour.</p>
                            <p style="margin-bottom: 20px;">If you did not request this password reset, please ignore this email or contact our support team if you have concerns.</p>
                            <p style="font-size: 12px; color: #888;">
                                Imators - Secure your account
                            </p>
                        </div>
                    </div>';

                $mail->send();
                $success = "Password reset instructions have been sent to your email. Please check your inbox.";
            } catch (Exception $e) {
                $error = "Could not send reset email. Please try again later.";
                error_log("Reset email error: " . $mail->ErrorInfo);
            }
        } else {
            $success = "If your email exists in our system, you will receive password reset instructions shortly.";
        }
    } catch(PDOException $e) {
        $error = "An error occurred. Please try again later.";
        error_log("Password reset error: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Forgot Password - Imators Auth.</title>
    <meta name="description" content="Reset your Imators account password.">

    <meta property="og:url" content="https://accounts.imators.com/forgot-password">
    <meta property="og:type" content="website">
    <meta property="og:title" content="Forgot Password - Imators Auth.">
    <meta property="og:description" content="Reset your Imators account password.">
    <meta property="og:image" content="https://opengraph.b-cdn.net/production/images/fb6bc1ea-5744-46f1-bee6-fc033a6c6b56.png?token=_EL6e3nPPtxSgvlGKURhJgrJb5NireVFT99X4BXVrYA&height=600&width=1200&expires=33267345049">

    <meta name="twitter:card" content="summary_large_image">
    <meta property="twitter:domain" content="accounts.imators.com">
    <meta property="twitter:url" content="https://accounts.imators.com/forgot-password">
    <meta name="twitter:title" content="Forgot Password - Imators Auth.">
    <meta name="twitter:description" content="Reset your Imators account password.">
    <meta name="twitter:image" content="https://opengraph.b-cdn.net/production/images/fb6bc1ea-5744-46f1-bee6-fc033a6c6b56.png?token=_EL6e3nPPtxSgvlGKURhJgrJb5NireVFT99X4BXVrYA&height=600&width=1200&expires=33267345049">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="https://cdn.imators.com/logo.png" rel="icon" type="image/png" />
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background: #000;
            color: #fff;
            overflow-x: hidden;
        }
        
        .container {
            height: 100vh;
            display: flex;
        }
        
        .image-section {
            width: 50%;
            background: linear-gradient(45deg, #0a0a0a, #1a1a1a);
            position: relative;
            overflow: hidden;
        }
        
        .image-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: url('https://idsma.imators.com/illustr_pc.png') center/cover;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            filter: brightness(0.3);
        }
        
        .image-overlay {
            position: absolute;
            bottom: 40px;
            left: 40px;
            z-index: 2;
        }
        
        .form-section {
            width: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px;
        }
        
        .form-container {
            width: 100%;
            max-width: 400px;
        }
        
        .logo {
            height: 40px;
            margin-bottom: 40px;
        }
        
        .title {
            font-size: 28px;
            font-weight: 300;
            margin-bottom: 8px;
            line-height: 1.2;
        }
        
        .subtitle {
            color: #666;
            font-size: 14px;
            margin-bottom: 40px;
            line-height: 1.4;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            font-size: 14px;
            margin-bottom: 8px;
            color: #ccc;
        }
        
        .form-input {
            width: 100%;
            padding: 12px 0;
            border: none;
            border-bottom: 1px solid #333;
            background: transparent;
            color: #fff;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        .form-input:focus {
            outline: none;
            border-bottom-color: #fff;
        }
        
        .reset-btn {
            width: 100%;
            padding: 16px;
            background: #fff;
            color: #000;
            border: none;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            margin-top: 30px;
            transition: background-color 0.3s;
        }
        
        .reset-btn:hover {
            background: #f0f0f0;
        }
        
        .links {
            margin-top: 30px;
            text-align: center;
        }
        
        .links a {
            color: #666;
            text-decoration: none;
            font-size: 14px;
            transition: color 0.3s;
        }
        
        .links a:hover {
            color: #fff;
        }
        
        .alert {
            padding: 12px;
            margin-bottom: 20px;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .alert-error {
            background: rgba(220, 53, 69, 0.1);
            border: 1px solid #dc3545;
            color: #dc3545;
        }
        
        .alert-success {
            background: rgba(34, 197, 94, 0.1);
            border: 1px solid #22c55e;
            color: #22c55e;
        }
        
        .mobile-reset-btn {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            background: #fff;
            color: #000;
            padding: 16px 40px;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 10;
            display: none;
        }
        
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }
            
            .image-section {
                width: 100%;
                height: 40vh;
                transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
            }
            
            .image-section::before {
                background: url('https://idsma.imators.com/illustr_mobile.png') center/cover;
                background-size: cover;
                background-position: center;
                background-repeat: no-repeat;
                filter: brightness(0.3);
            }
            
            .image-section.hidden {
                height: 0;
                opacity: 0;
            }
            
            .form-section {
                width: 100%;
                height: 60vh;
                padding: 20px;
                transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
            }
            
            .form-section.expanded {
                height: 100vh;
            }
            
            .mobile-reset-btn {
                display: block;
            }
            
            .mobile-reset-btn.hidden {
                opacity: 0;
                transform: translateX(-50%) translateY(100px);
                pointer-events: none;
            }
            
            .form-container {
                transform: translateY(50px);
                opacity: 0;
                transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
            }
            
            .form-container.visible {
                transform: translateY(0);
                opacity: 1;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="image-section" id="imageSection">
            <div class="image-overlay">
                <img src="https://cdn.imators.com/logo.png" alt="Imators" class="logo">
                <h2 style="font-size: 24px; font-weight: 300;">Secure Reset</h2>
                <p style="color: #ccc; margin-top: 8px;">Recover your access</p>
            </div>
        </div>
        
        <div class="form-section" id="formSection">
            <div class="form-container" id="formContainer">
                <img src="https://cdn.imators.com/logo.png" alt="Imators" class="logo">
                
                <h1 class="title">Reset Password</h1>
                <p class="subtitle">Enter your email address and we'll send you a link to reset your password</p>
                
                <?php if($error): ?>
                    <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
                <?php endif; ?>
                
                <?php if($success): ?>
                    <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
                <?php endif; ?>
                
                <form method="POST" id="resetForm">
                    <div class="form-group">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-input" required>
                    </div>
                    
                    <button type="submit" class="reset-btn">
                        Send Reset Link
                    </button>
                </form>
                
                <div class="links">
                    <a href="login.php">Back to Login</a>
                </div>
            </div>
        </div>
        
        <button class="mobile-reset-btn" id="mobileResetBtn" onclick="showResetForm()">
            Reset my password
        </button>
    </div>

    <script>
    function showResetForm() {
        const imageSection = document.getElementById('imageSection');
        const formSection = document.getElementById('formSection');
        const formContainer = document.getElementById('formContainer');
        const mobileBtn = document.getElementById('mobileResetBtn');
        
        imageSection.classList.add('hidden');
        formSection.classList.add('expanded');
        mobileBtn.classList.add('hidden');
        
        setTimeout(() => {
            formContainer.classList.add('visible');
        }, 300);
    }
    </script>
</body>
</html>