<?php
session_start();
include 'functions.php';

$token      = trim($_GET['token'] ?? $_POST['token'] ?? '');
$success    = '';
$error      = '';
$valid      = false;
$user       = null;

if ($token !== '') {
    $stmt = $connect->prepare("SELECT id, fullname, email FROM users WHERE reset_token = ? LIMIT 1");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if ($user) { $valid = true; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $valid) {
    $password = $_POST['password'] ?? '';
    $confirm  = $_POST['password_confirmation'] ?? '';

    if (strlen($password) < 8) {
        $error = 'Password must be at least 8 characters.';
    } elseif ($password !== $confirm) {
        $error = 'Passwords do not match.';
    } else {
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $upd  = $connect->prepare("UPDATE users SET password = ?, reset_token = NULL WHERE id = ?");
        $upd->bind_param("si", $hash, $user['id']);
        $upd->execute();
        $upd->close();
        $success = 'Your password has been reset. You can now log in.';
        $valid   = false;
        $token   = '';
        $user    = null;
    }
}
?>
<!DOCTYPE html>
<html lang="en" x-data="{ darkMode: false }" x-init="darkMode = localStorage.getItem('darkMode') === 'true' || (!localStorage.getItem('darkMode') && window.matchMedia('(prefers-color-scheme: dark)').matches)" :class="{ 'dark': darkMode }">
<head>
    <title>Reset Password - <?php echo getSiteConfig('sitename'); ?></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow">
    <link rel="shortcut icon" href="storage/app/public/photos/JFhHkiuNvOTfUR5bSTcRhJrlW2nXDFpq3s6DoadO.png">
    <link rel="icon" type="image/png" href="storage/app/public/photos/JFhHkiuNvOTfUR5bSTcRhJrlW2nXDFpq3s6DoadO.png">

    <script>
        const isDarkMode = localStorage.getItem('darkMode') === 'true' ||
                          (!localStorage.getItem('darkMode') && window.matchMedia('(prefers-color-scheme: dark)').matches);
        if (isDarkMode) { document.documentElement.classList.add('dark'); }
    </script>

    <script src="https://cdn.tailwindcss.com/?plugins=forms,typography,aspect-ratio,line-clamp"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#f0f9ff', 100: '#e0f2fe', 200: '#bae6fd', 300: '#7dd3fc',
                            400: '#38bdf8', DEFAULT: '#0ea5e9', 500: '#0ea5e9',
                            600: '#0284c7', 700: '#0369a1', foreground: '#ffffff',
                        },
                    },
                }
            }
        }
    </script>

    <script defer src="../cdn.jsdelivr.net/npm/alpinejs%403.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="../cdn.jsdelivr.net/gh/aquawolf04/font-awesome-pro%405cd1511/css/all.css">
    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

    <style>
        body { font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
        .input-wrapper { position: relative; transition: all 0.3s ease; }
        .input-wrapper:focus-within { transform: translateY(-2px); }
        .input-icon { position: absolute; top: 50%; transform: translateY(-50%); left: 1rem; color: #94a3b8; transition: color 0.3s ease; }
        .input-wrapper:focus-within .input-icon { color: #0ea5e9; }
        .toggle-btn { position: absolute; top: 50%; transform: translateY(-50%); right: 1rem; cursor: pointer; color: #94a3b8; }
    </style>
</head>

<body class="font-sans bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100 flex min-h-screen">

    <!-- Dark Mode Toggle -->
    <div class="fixed top-4 right-4 z-50">
        <button @click="darkMode = !darkMode; localStorage.setItem('darkMode', darkMode)"
                class="p-3 rounded-2xl bg-white/80 dark:bg-gray-800/80 text-gray-700 dark:text-gray-300 shadow-lg hover:shadow-xl border border-gray-200/50 dark:border-gray-700/50 backdrop-blur-xl transition-all duration-300 hover:scale-110">
            <i class="fa-solid fa-sun h-5 w-5" x-show="darkMode"></i>
            <i class="fa-solid fa-moon h-5 w-5" x-show="!darkMode"></i>
        </button>
    </div>

    <div class="w-full">
        <div class="flex flex-col lg:flex-row min-h-screen">

            <!-- Left Side - Branding -->
            <div class="hidden lg:flex lg:w-1/2 bg-gradient-to-br from-primary-600 via-primary-700 to-primary-800 dark:from-primary-700 dark:via-primary-800 dark:to-primary-900 relative overflow-hidden">
                <div class="absolute inset-0 overflow-hidden">
                    <div class="absolute inset-0 opacity-20" style="background-image: radial-gradient(rgba(255,255,255,0.15) 1px, transparent 1px); background-size: 25px 25px;"></div>
                </div>
                <div class="relative flex flex-col justify-center items-center w-full h-full text-white p-8 z-10">
                    <div class="mb-6 relative">
                        <div class="absolute inset-0 bg-white/20 rounded-2xl blur-lg"></div>
                        <div class="relative bg-white/10 backdrop-blur-sm rounded-2xl p-4 border border-white/20">
                            <img src="storage/app/public/photos/ll6Rkij7mMXTskezBsaz1LTT1rIvUOc63TqzmuC6.png" alt="Logo" class="h-12">
                        </div>
                    </div>
                    <h1 class="text-3xl font-black mb-3 text-center">Set New Password</h1>
                    <h2 class="text-lg font-semibold mb-6 text-center text-white/90">Secure Your Account</h2>
                    <p class="text-sm mb-8 max-w-md text-center text-white/80 leading-relaxed">
                        Choose a strong password for your <?php echo getSiteConfig('sitename'); ?> account.
                    </p>
                    <div class="grid grid-cols-2 gap-4 w-full max-w-md">
                        <div class="flex items-center space-x-3 p-3 rounded-xl bg-white/10 backdrop-blur-sm border border-white/20">
                            <div class="flex-shrink-0 w-8 h-8 rounded-xl bg-white/20 flex items-center justify-center">
                                <i class="fas fa-lock text-sm"></i>
                            </div>
                            <div>
                                <h3 class="text-sm font-semibold">Strong Encryption</h3>
                                <p class="text-xs text-white/70">Bcrypt hashing</p>
                            </div>
                        </div>
                        <div class="flex items-center space-x-3 p-3 rounded-xl bg-white/10 backdrop-blur-sm border border-white/20">
                            <div class="flex-shrink-0 w-8 h-8 rounded-xl bg-white/20 flex items-center justify-center">
                                <i class="fas fa-shield-alt text-sm"></i>
                            </div>
                            <div>
                                <h3 class="text-sm font-semibold">One-time Link</h3>
                                <p class="text-xs text-white/70">Expires on use</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right Side - Form -->
            <div class="w-full lg:w-1/2 flex flex-col justify-center items-center p-3 lg:p-8 bg-gray-50/50 dark:bg-gray-900/50">
                <div class="w-full max-w-sm">

                    <!-- Mobile Header -->
                    <div class="lg:hidden text-center mb-6">
                        <div class="relative inline-block mb-3 mt-10">
                            <div class="relative bg-white/90 dark:bg-gray-800/90 backdrop-blur-sm rounded-2xl p-3 border border-gray-200/50 dark:border-gray-700/50">
                                <img src="storage/app/public/photos/ll6Rkij7mMXTskezBsaz1LTT1rIvUOc63TqzmuC6.png" alt="Logo" class="h-10 mx-auto">
                            </div>
                        </div>
                        <h1 class="text-xl font-bold text-gray-900 dark:text-white mb-1">Reset Password</h1>
                    </div>

                    <!-- Alerts -->
                    <?php if ($success): ?>
                    <div class="mb-4 p-4 rounded-xl bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-700 flex items-start gap-3">
                        <i class="fas fa-check-circle text-green-500 mt-0.5 flex-shrink-0"></i>
                        <div>
                            <p class="text-sm text-green-800 dark:text-green-200"><?php echo htmlspecialchars($success); ?></p>
                            <a href="login" class="mt-2 inline-block text-sm font-semibold text-primary-600 dark:text-primary-400 hover:underline">
                                Go to Login &rarr;
                            </a>
                        </div>
                    </div>
                    <?php endif; ?>
                    <?php if ($error): ?>
                    <div class="mb-4 p-4 rounded-xl bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 flex items-start gap-3">
                        <i class="fas fa-exclamation-circle text-red-500 mt-0.5 flex-shrink-0"></i>
                        <p class="text-sm text-red-800 dark:text-red-200"><?php echo htmlspecialchars($error); ?></p>
                    </div>
                    <?php endif; ?>
                    <?php if (!$valid && !$success): ?>
                    <div class="mb-4 p-4 rounded-xl bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-700 flex items-start gap-3">
                        <i class="fas fa-exclamation-triangle text-yellow-500 mt-0.5 flex-shrink-0"></i>
                        <div>
                            <p class="text-sm text-yellow-800 dark:text-yellow-200">This reset link is invalid or has already been used.</p>
                            <a href="forgot-password" class="mt-2 inline-block text-sm font-semibold text-primary-600 dark:text-primary-400 hover:underline">
                                Request a new link &rarr;
                            </a>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Reset Password Card -->
                    <?php if ($valid): ?>
                    <div class="bg-white/90 dark:bg-gray-800/90 backdrop-blur-xl rounded-2xl shadow-2xl border border-gray-200/50 dark:border-gray-700/50 overflow-hidden">
                        <div class="px-6 pt-6 pb-4 border-b border-gray-100/50 dark:border-gray-700/50 text-center">
                            <div class="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-primary-100/50 dark:bg-primary-800/50 mb-4">
                                <i class="fas fa-key text-2xl text-primary-600 dark:text-primary-300"></i>
                            </div>
                            <h2 class="text-xl font-bold text-gray-900 dark:text-white mb-1">New Password</h2>
                            <p class="text-sm text-gray-600 dark:text-gray-400">for <?php echo htmlspecialchars($user['email']); ?></p>
                        </div>

                        <div class="px-6 pb-6 pt-4">
                            <form method="POST" action="reset-password" class="space-y-4" x-data="{ showPw: false, showCf: false }">
                                <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">

                                <!-- Password -->
                                <div class="space-y-1">
                                    <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300">New Password <span class="text-red-500">*</span></label>
                                    <div class="input-wrapper group">
                                        <div class="relative">
                                            <div class="input-icon"><i class="fas fa-lock text-sm"></i></div>
                                            <input :type="showPw ? 'text' : 'password'" name="password"
                                                class="w-full pl-10 pr-10 py-3 border border-gray-300/50 dark:border-gray-600/50 rounded-xl bg-gray-50/50 dark:bg-gray-700/50 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500/50 focus:border-primary-500 text-sm transition-all duration-300"
                                                placeholder="Min. 8 characters" required minlength="8">
                                            <button type="button" class="toggle-btn" @click="showPw = !showPw">
                                                <i :class="showPw ? 'fas fa-eye-slash' : 'fas fa-eye'" class="text-sm"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <!-- Confirm Password -->
                                <div class="space-y-1">
                                    <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300">Confirm Password <span class="text-red-500">*</span></label>
                                    <div class="input-wrapper group">
                                        <div class="relative">
                                            <div class="input-icon"><i class="fas fa-lock text-sm"></i></div>
                                            <input :type="showCf ? 'text' : 'password'" name="password_confirmation"
                                                class="w-full pl-10 pr-10 py-3 border border-gray-300/50 dark:border-gray-600/50 rounded-xl bg-gray-50/50 dark:bg-gray-700/50 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500/50 focus:border-primary-500 text-sm transition-all duration-300"
                                                placeholder="Repeat new password" required>
                                            <button type="button" class="toggle-btn" @click="showCf = !showCf">
                                                <i :class="showCf ? 'fas fa-eye-slash' : 'fas fa-eye'" class="text-sm"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <div class="pt-2">
                                    <button type="submit"
                                        class="w-full py-3 px-4 bg-gradient-to-r from-primary-600 to-primary-700 hover:from-primary-700 hover:to-primary-800 text-white font-semibold rounded-xl shadow-lg hover:shadow-xl transform hover:scale-[1.02] transition-all duration-300 flex items-center justify-center text-sm">
                                        <i class="fas fa-check mr-2 text-sm"></i>
                                        Set New Password
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Footer -->
                    <div class="mt-6 text-center">
                        <p class="text-xs text-gray-500 dark:text-gray-500">
                            &copy; 2026 <?php echo getSiteConfig('sitename'); ?>. All Rights Reserved.
                        </p>
                    </div>

                </div>
            </div>

        </div>
    </div>

</body>
</html>
