<?php
require_once 'functions.php';

if (isLoggedIn()) {
    header('Location: dashboard.php');
    exit();
}

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

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

// Validate token
$db = getDB();
$stmt = $db->prepare("SELECT id, email, first_name, email_verified_at FROM users WHERE remember_token = ?");
$stmt->bind_param('s', $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows !== 1) {
    $error = 'Invalid or expired reset token.';
} else {
    $user = $result->fetch_assoc();
    
    // Check if token is expired (1 hour)
    if (strtotime($user['email_verified_at']) < time() - 3600) {
        $error = 'Reset token has expired. Please request a new one.';
    }
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($error)) {
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        if (strlen($password) < 6) {
            $error = 'Password must be at least 6 characters.';
        } elseif ($password !== $confirmPassword) {
            $error = 'Passwords do not match.';
        } else {
            $hashed = hashPassword($password);
            $stmt = $db->prepare("UPDATE users SET password = ?, remember_token = NULL, email_verified_at = NULL WHERE id = ?");
            $stmt->bind_param('si', $hashed, $user['id']);
            
            if ($stmt->execute()) {
                $success = 'Password reset successfully! You can now log in with your new password.';
                header('Refresh: 3; URL=login.php');
            } else {
                $error = 'Failed to reset password.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Password - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body class="login-page">
    <div class="login-container">
        <div class="login-card">
            <div class="login-logo">
                <img src="assets/images/logo.png" alt="<?php echo SITE_NAME; ?>">
                <h1>Set New Password</h1>
            </div>
            
            <?php if ($error): ?>
                <div class="alert alert-danger" style="margin-bottom: 20px;"><span>⚠</span> <?php echo e($error); ?></div>
                <a href="forgot-password.php" class="btn btn-primary btn-block">Request New Link</a>
            <?php elseif ($success): ?>
                <div class="alert alert-success" style="margin-bottom: 20px;"><span>✓</span> <?php echo e($success); ?></div>
                <p style="text-align: center; font-size: 13px; color: var(--gray);">Redirecting to login...</p>
            <?php else: ?>
                <form method="POST" action="">
                    <div class="form-group">
                        <label class="form-label">New Password</label>
                        <input type="password" name="password" class="form-control" required minlength="6" placeholder="Min 6 characters" autofocus>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Confirm Password</label>
                        <input type="password" name="confirm_password" class="form-control" required placeholder="Repeat password">
                    </div>
                    <button type="submit" class="btn btn-primary btn-block" style="padding: 14px;">Reset Password</button>
                </form>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
