<?php

/**
 * User Search CLI Tool
 *
 * Usage:
 *   php artisan-user-search.php                    # List all users
 *   php artisan-user-search.php "search term"      # Search users by name or email
 *   php artisan-user-search.php --email "term"     # Search by email only
 *   php artisan-user-search.php --name "term"      # Search by name only
 *   php artisan-user-search.php --admin            # Show only admin users
 *   php artisan-user-search.php --active           # Show only active users
 *   php artisan-user-search.php --banned           # Show only banned users
 */

// Load Composer autoloader
require_once __DIR__ . '/vendor/autoload.php';

// Bootstrap Laravel
$app = require_once __DIR__ . '/bootstrap/app.php';

use App\Models\User;
use Illuminate\Database\Eloquent\Builder;

class UserSearchTool
{
    private $query;
    private $searchTerm = null;
    private $searchType = 'all'; // 'all', 'name', 'email'
    private $filterAdmin = false;
    private $filterActive = null; // null = all, true = active, false = banned
    private $limit = 50;

    public function __construct()
    {
        $this->parseArguments();
    }

    private function parseArguments()
    {
        global $argv;

        // Skip script name
        for ($i = 1; $i < count($argv); $i++) {
            $arg = $argv[$i];

            if ($arg === '--admin') {
                $this->filterAdmin = true;
            } elseif ($arg === '--active') {
                $this->filterActive = true;
            } elseif ($arg === '--banned') {
                $this->filterActive = false;
            } elseif ($arg === '--email') {
                $this->searchType = 'email';
                if (isset($argv[$i + 1]) && !str_starts_with($argv[$i + 1], '--')) {
                    $this->searchTerm = $argv[++$i];
                }
            } elseif ($arg === '--name') {
                $this->searchType = 'name';
                if (isset($argv[$i + 1]) && !str_starts_with($argv[$i + 1], '--')) {
                    $this->searchTerm = $argv[++$i];
                }
            } elseif ($arg === '--limit') {
                if (isset($argv[$i + 1]) && is_numeric($argv[$i + 1])) {
                    $this->limit = (int)$argv[++$i];
                }
            } elseif (!str_starts_with($arg, '--') && $this->searchTerm === null) {
                // Positional argument for search term
                $this->searchTerm = $arg;
                $this->searchType = 'all';
            }
        }
    }

    public function run()
    {
        $this->buildQuery();
        $users = $this->query->limit($this->limit)->get();

        if ($users->isEmpty()) {
            echo "\n❌ No users found.\n\n";
            return;
        }

        $this->displayResults($users);
    }

    private function buildQuery()
    {
        $this->query = User::query();

        // Apply admin filter
        if ($this->filterAdmin) {
            $this->query->where('is_admin', true);
        }

        // Apply active/banned filter
        if ($this->filterActive !== null) {
            $this->query->where('is_active', $this->filterActive);
        }

        // Apply search filter
        if ($this->searchTerm !== null) {
            $searchTerm = "%{$this->searchTerm}%";

            if ($this->searchType === 'email') {
                $this->query->where('email', 'like', $searchTerm);
            } elseif ($this->searchType === 'name') {
                $this->query->where('name', 'like', $searchTerm);
            } else {
                // Search both name and email
                $this->query->where(function (Builder $q) use ($searchTerm) {
                    $q->where('name', 'like', $searchTerm)
                      ->orWhere('email', 'like', $searchTerm);
                });
            }
        }

        $this->query->orderBy('created_at', 'desc');
    }

    private function displayResults($users)
    {
        echo "\n╔════════════════════════════════════════════════════════════════════════════════╗\n";
        echo "║                          USER SEARCH RESULTS                                   ║\n";
        echo "╚════════════════════════════════════════════════════════════════════════════════╝\n\n";

        // Header
        printf("%-5s | %-20s | %-30s | %-10s | %-10s\n", "ID", "Name", "Email", "Admin", "Status");
        echo str_repeat("-", 90) . "\n";

        // Rows
        foreach ($users as $user) {
            $admin = $user->is_admin ? "✅ Yes" : "No";
            $status = $user->is_active ? "✅ Active" : "🚫 Banned";
            $name = $user->name ?? "(no name)";

            printf("%-5d | %-20s | %-30s | %-10s | %-10s\n",
                $user->id,
                substr($name, 0, 20),
                substr($user->email, 0, 30),
                $admin,
                $status
            );
        }

        echo "\n";
        echo "Total: " . count($users) . " user(s)\n";

        // Show search criteria if applied
        if ($this->searchTerm !== null) {
            echo "Search: " . ucfirst($this->searchType) . " contains '" . $this->searchTerm . "'\n";
        }
        if ($this->filterAdmin) {
            echo "Filter: Admin users only\n";
        }
        if ($this->filterActive === true) {
            echo "Filter: Active users only\n";
        } elseif ($this->filterActive === false) {
            echo "Filter: Banned users only\n";
        }
        echo "\n";
    }
}

// Display help
function showHelp()
{
    echo "\n╔════════════════════════════════════════════════════════════════════════════════╗\n";
    echo "║                         USER SEARCH CLI TOOL                                   ║\n";
    echo "╚════════════════════════════════════════════════════════════════════════════════╝\n\n";

    echo "USAGE:\n";
    echo "  php artisan-user-search.php [options] [search-term]\n\n";

    echo "EXAMPLES:\n";
    echo "  php artisan-user-search.php\n";
    echo "    → Lists all users (name + email)\n\n";

    echo "  php artisan-user-search.php john\n";
    echo "    → Search for users with 'john' in name or email\n\n";

    echo "  php artisan-user-search.php --email gmail.com\n";
    echo "    → Search for users with 'gmail.com' in email\n\n";

    echo "  php artisan-user-search.php --name john\n";
    echo "    → Search for users with 'john' in name\n\n";

    echo "  php artisan-user-search.php --admin\n";
    echo "    → List all admin users\n\n";

    echo "  php artisan-user-search.php --active\n";
    echo "    → List all active users\n\n";

    echo "  php artisan-user-search.php --banned\n";
    echo "    → List all banned users\n\n";

    echo "  php artisan-user-search.php john --admin\n";
    echo "    → Search for admin users with 'john' in name or email\n\n";

    echo "OPTIONS:\n";
    echo "  --name \"term\"        Search by name only\n";
    echo "  --email \"term\"       Search by email only\n";
    echo "  --admin              Show only admin users\n";
    echo "  --active             Show only active users\n";
    echo "  --banned             Show only banned users\n";
    echo "  --limit N            Limit results to N users (default: 50)\n";
    echo "  --help               Show this help message\n\n";
}

// Check for help flag
if (in_array('--help', $argv) || in_array('-h', $argv)) {
    showHelp();
    exit(0);
}

// Run the tool
$tool = new UserSearchTool();
$tool->run();
