<?php
session_start();
require_once 'db.php';

// Définir le fuseau horaire pour l'Europe/Bruxelles (Belgique)
date_default_timezone_set('Europe/Brussels');

if(isset($_SESSION['user_id'])) {
    header('Location: https://idsma.imators.com/dashboard.php');
    exit;
}

$error = '';
$success = '';
$valid_token = false;
$token = $_GET['token'] ?? '';

if(empty($token)) {
    header('Location: login.php');
    exit;
}

try {
    $db = new Database();
    $conn = $db->connect();
    
    // Utilisation d'une requête qui prend en compte le fuseau horaire pour comparer la date d'expiration
    $stmt = $conn->prepare("SELECT pr.*, u.email FROM password_resets pr 
                           JOIN utilisateurs u ON pr.user_id = u.id 
                           WHERE pr.token = ? AND pr.expires_at > NOW() AND pr.used = 0
                           LIMIT 1");
    $stmt->execute([$token]);
    
    if($stmt->rowCount() > 0) {
        $reset_data = $stmt->fetch(PDO::FETCH_ASSOC);
        $valid_token = true;
    } else {
        $error = "Invalid or expired token. Please request a new password reset.";
    }
} catch(PDOException $e) {
    $error = "An error occurred. Please try again later.";
    error_log("Token validation error: " . $e->getMessage());
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $valid_token) {
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    if(strlen($password) < 8) {
        $error = "Password must be at least 8 characters long.";
    } elseif($password !== $confirm_password) {
        $error = "Passwords do not match.";
    } else {
        try {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            $stmt = $conn->prepare("UPDATE utilisateurs SET password = ? WHERE id = ?");
            $stmt->execute([$hashed_password, $reset_data['user_id']]);
            
            $stmt = $conn->prepare("UPDATE password_resets SET used = 1 WHERE token = ?");
            $stmt->execute([$token]);
            
            $success = "Your password has been successfully reset. You can now login with your new password.";
        } catch(PDOException $e) {
            $error = "Password reset failed. Please try again.";
            error_log("Password update error: " . $e->getMessage());
        }
    }
}
?>

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

    <meta property="og:url" content="https://accounts.imators.com">
    <meta property="og:type" content="website">
    <meta property="og:title" content="Reset Password - Imators Auth.">
    <meta property="og:description" content="Create a new password for your Imators account.">
    <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">
    <meta name="twitter:title" content="Reset Password - Imators Auth.">
    <meta name="twitter:description" content="Create a new password for your Imators account.">
    <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">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.imators.com/logo.png" rel="icon" type="image/png" />
    <script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <style>
        body {
            font-family: 'Poppins', sans-serif;
        }
    </style>
</head>
<body 
    x-data="resetPasswordManager()" 
    class="bg-black text-white min-h-screen flex items-center justify-center">
    <div class="w-full max-w-md p-8">
    
        <div class="text-center mb-8">
            <img src="https://cdn.imators.com/logo.png" alt="Logo" class="mx-left mb-4" style="height: 60px;">
            <h1 class="text-3xl text-left text-green-200">Create new password</h1>
            <p class="text-xs text-left">
                <?php echo $valid_token ? "Please create a new password for {$reset_data['email']}" : "Set up your new password"; ?>
            </p>
        </div>
        
        <?php if($success): ?>
            <div class="bg-green-500/20 border border-green-500 text-green-300 p-4 rounded-lg text-center mb-6">
                <?php echo htmlspecialchars($success); ?>
                <p class="mt-4">
                    <a href="login.php" class="bg-white text-black py-2 px-4 rounded-lg font-medium hover:bg-gray-100 transition-colors inline-block">Go to Login</a>
                </p>
            </div>
        <?php elseif($valid_token): ?>
            <form 
                method="POST" 
                x-on:submit.prevent="submitForm"
                class="space-y-6"
            >
                <?php if($error): ?>
                    <div 
                        x-show="showError"
                        class="bg-red-500 text-white p-3 rounded-lg text-center mb-4"
                    >
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php endif; ?>
                
                <div>
                    <label class="block text-sm font-medium mb-2">New Password</label>
                    <div class="relative">
                        <input 
                            type="password" 
                            name="password" 
                            required 
                            x-model="password"
                            id="password-field"
                            class="w-full px-4 py-2 rounded-lg bg-gray-900 border border-gray-800 focus:border-white focus:outline-none"
                        >
                        <button 
                            type="button"
                            class="absolute inset-y-0 right-0 pr-3 flex items-center"
                            onclick="togglePasswordVisibility('password-field', 'eye-icon', 'eye-off-icon')"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400" id="eye-icon" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                            </svg>
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400 hidden" id="eye-off-icon" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l18 18" />
                            </svg>
                        </button>
                    </div>
                    <div class="mt-1 text-xs text-gray-400">Password must be at least 8 characters long</div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium mb-2">Confirm Password</label>
                    <div class="relative">
                        <input 
                            type="password" 
                            name="confirm_password" 
                            required 
                            x-model="confirmPassword"
                            id="confirm-password-field"
                            class="w-full px-4 py-2 rounded-lg bg-gray-900 border border-gray-800 focus:border-white focus:outline-none"
                        >
                        <button 
                            type="button"
                            class="absolute inset-y-0 right-0 pr-3 flex items-center"
                            onclick="togglePasswordVisibility('confirm-password-field', 'eye-icon-2', 'eye-off-icon-2')"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400" id="eye-icon-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                            </svg>
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400 hidden" id="eye-off-icon-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l18 18" />
                            </svg>
                        </button>
                    </div>
                </div>
                
                <button 
                    type="submit"
                    class="w-full bg-white text-black py-2 px-4 rounded-lg font-medium hover:bg-gray-100 transition-colors"
                >
                    Reset Password
                </button>
            </form>
        <?php else: ?>
            <div class="bg-red-500/20 border border-red-500 text-red-300 p-4 rounded-lg text-center mb-6">
                <?php echo htmlspecialchars($error); ?>
                <p class="mt-4">
                    <a href="forgot-password.php" class="bg-white text-black py-2 px-4 rounded-lg font-medium hover:bg-gray-100 transition-colors inline-block">Request New Reset Link</a>
                </p>
            </div>
        <?php endif; ?>
    </div>

    <script>
    function togglePasswordVisibility(fieldId, eyeIconId, eyeOffIconId) {
        const passwordField = document.getElementById(fieldId);
        const eyeIcon = document.getElementById(eyeIconId);
        const eyeOffIcon = document.getElementById(eyeOffIconId);
        
        if (passwordField.type === 'password') {
            passwordField.type = 'text';
            eyeIcon.classList.add('hidden');
            eyeOffIcon.classList.remove('hidden');
        } else {
            passwordField.type = 'password';
            eyeIcon.classList.remove('hidden');
            eyeOffIcon.classList.add('hidden');
        }
    }

    function resetPasswordManager() {
        return {
            password: '',
            confirmPassword: '',
            showError: <?php echo $error ? 'true' : 'false'; ?>,
            submitForm() {
                if (!this.password || !this.confirmPassword) {
                    this.showError = true;
                    return;
                }
                
                if (this.password.length < 8) {
                    this.showError = true;
                    return;
                }
                
                if (this.password !== this.confirmPassword) {
                    this.showError = true;
                    return;
                }
                
                document.querySelector('form').submit();
            }
        };
    }
    </script>
</body>
</html>