<?php
session_start();
require 'config/db.php';
include 'includes/header.php';

$token = $_GET['token'] ?? '';
$error = "";
$success = "";

if (isset($_POST['new_password_submit'])) {
    $pass1 = $_POST['pass1'];
    $pass2 = $_POST['pass2'];
    $token_post = $_POST['token'];

    if ($pass1 !== $pass2) {
        $error = "Passwords do not match.";
    } else {
        // Verify Token
        $stmt = $pdo->prepare("SELECT email FROM password_resets WHERE token = ?");
        $stmt->execute([$token_post]);
        $reset = $stmt->fetch();

        if ($reset) {
            $email = $reset['email'];
            $new_hash = password_hash($pass1, PASSWORD_DEFAULT);

            // Update User Password
            $pdo->prepare("UPDATE users SET password_hash = ? WHERE email = ?")->execute([$new_hash, $email]);

            // Delete Token
            $pdo->prepare("DELETE FROM password_resets WHERE email = ?")->execute([$email]);

            $success = "Password updated successfully! <a href='login.php'>Login Now</a>";
        } else {
            $error = "Invalid or expired token.";
        }
    }
}
?>

<div class="auth-body-bg">
    <div class="auth-3d-card">
        <h2>New Password</h2>
        
        <?php if($success): ?>
            <div style="background:#d4edda; color:#155724; padding:10px; border-radius:5px; text-align:center; margin-bottom:15px;">
                <?php echo $success; ?>
            </div>
        <?php endif; ?>

        <?php if($error): ?>
            <div style="background:#ffdddd; color:#c0392b; padding:10px; border-radius:5px; text-align:center; margin-bottom:15px;">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <?php if(empty($success)): ?>
        <form method="POST">
            <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
            <input type="password" name="pass1" class="auth-input" placeholder="New Password" required>
            <input type="password" name="pass2" class="auth-input" placeholder="Confirm New Password" required>
            <button type="submit" name="new_password_submit" class="btn-3d btn-login">Change Password</button>
        </form>
        <?php endif; ?>

    </div>
</div>

<?php include 'includes/footer.php'; ?>