<?php
// reset-password.php — Process password reset with token
session_start();
include 'config.php';

$message = '';
$error = '';
$valid_token = false;
$token = trim($_GET['token'] ?? $_POST['token'] ?? '');

if (!empty($token)) {
    // Validate token
    $stmt = $conn->prepare("SELECT id, org_name FROM users WHERE password_reset_token = ? AND password_reset_expires > NOW()");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    if ($user) {
        $valid_token = true;

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $new_password = trim($_POST['new_password'] ?? '');
            $confirm = trim($_POST['confirm_password'] ?? '');

            if (strlen($new_password) < 8) {
                $error = "Password must be at least 8 characters.";
            } elseif ($new_password !== $confirm) {
                $error = "Passwords do not match.";
            } else {
                $hash = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt = $conn->prepare("UPDATE users SET password = ?, password_reset_token = NULL, password_reset_expires = NULL WHERE id = ?");
                $stmt->bind_param("si", $hash, $user['id']);
                if ($stmt->execute()) {
                    if (file_exists(__DIR__ . '/util/audit_logger.php')) {
                        include_once __DIR__ . '/util/audit_logger.php';
                        audit_log(
                            $conn,
                            'password_reset_completed',
                            'users',
                            $user['id'],
                            $user['id'],
                            0,
                            null,
                            null,
                            "Password reset via token."
                        );
                    }
                    $message = "Password has been reset. You can now log in.";
                    $valid_token = false;
                } else {
                    $error = "Error resetting password.";
                }
            }
        }
    } else {
        $error = "Invalid or expired reset token.";
    }
} else {
    $error = "No reset token provided.";
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Reset Password - SaniBook</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <style>
        body {
            font-family: 'Inter', system-ui, sans-serif;
        }
    </style>
</head>

<body class="bg-gradient-to-br from-slate-50 to-blue-50/30 min-h-screen flex items-center justify-center">
    <div class="w-full max-w-md p-6">
        <div class="bg-white rounded-2xl shadow-lg p-8 border border-slate-200">
            <div class="text-center mb-6">
                <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-3">
                    <i class="fa-solid fa-shield-halved text-2xl text-green-600"></i>
                </div>
                <h2 class="text-2xl font-bold text-slate-900">Reset Password</h2>
            </div>

            <?php if ($message): ?>
                <div
                    class="bg-green-50 border border-green-200 text-green-800 p-3 rounded-lg mb-4 text-sm flex items-center gap-2">
                    <i class="fa-solid fa-check-circle"></i>
                    <?= htmlspecialchars($message) ?>
                </div>
                <div class="text-center">
                    <a href="login.php"
                        class="inline-block py-3 px-6 bg-blue-600 text-white rounded-lg font-bold hover:bg-blue-700 transition-all text-sm">
                        <i class="fa-solid fa-sign-in-alt mr-1"></i> Go to Login
                    </a>
                </div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div
                    class="bg-red-50 border border-red-200 text-red-800 p-3 rounded-lg mb-4 text-sm flex items-center gap-2">
                    <i class="fa-solid fa-exclamation-circle"></i>
                    <?= htmlspecialchars($error) ?>
                </div>
                <div class="text-center mt-3">
                    <a href="forgot-password.php" class="text-sm text-blue-600 hover:underline">Request a new token</a>
                </div>
            <?php endif; ?>

            <?php if ($valid_token): ?>
                <p class="text-sm text-slate-600 mb-4 text-center">
                    Setting new password for <strong>
                        <?= htmlspecialchars($user['org_name']) ?>
                    </strong>
                </p>
                <form method="POST" class="space-y-5">
                    <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-1">New Password</label>
                        <input type="password" name="new_password" required minlength="8"
                            class="w-full border border-slate-300 rounded-lg p-3 text-sm focus:ring-2 focus:ring-blue-500">
                        <p class="text-xs text-slate-400 mt-1">Minimum 8 characters</p>
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-1">Confirm Password</label>
                        <input type="password" name="confirm_password" required minlength="8"
                            class="w-full border border-slate-300 rounded-lg p-3 text-sm focus:ring-2 focus:ring-blue-500">
                    </div>
                    <button type="submit"
                        class="w-full py-3 bg-green-600 text-white rounded-lg font-bold hover:bg-green-700 transition-all text-sm">
                        <i class="fa-solid fa-check mr-1"></i> Set New Password
                    </button>
                </form>
            <?php endif; ?>
        </div>
    </div>
</body>

</html>