<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Database\Query\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\View\View;

class ModuleController extends Controller
{
    private const MODULES = [
        'users' => ['title' => 'User Management', 'table' => 'users', 'icon' => 'bi-people', 'columns' => ['uuid', 'full_name', 'email', 'mobile', 'status', 'is_premium', 'created_at'], 'search' => ['uuid', 'full_name', 'email', 'mobile']],
        'devices' => ['title' => 'Device Management', 'table' => 'devices', 'icon' => 'bi-phone', 'columns' => ['uuid', 'device_name', 'device_brand', 'device_model', 'imei_1', 'status', 'battery_percentage', 'last_online'], 'search' => ['uuid', 'device_name', 'device_brand', 'device_model', 'imei_1']],
        'tracking' => ['title' => 'Live Tracking', 'table' => 'device_locations', 'icon' => 'bi-geo-alt', 'columns' => ['uuid', 'device_id', 'latitude', 'longitude', 'accuracy', 'address', 'gps_status', 'created_at'], 'search' => ['uuid', 'address', 'city', 'country']],
        'alerts' => ['title' => 'Theft Alerts', 'table' => 'theft_events', 'icon' => 'bi-shield-exclamation', 'columns' => ['incident_number', 'event_title', 'event_type', 'risk_level', 'risk_score', 'status', 'created_at'], 'search' => ['incident_number', 'event_title', 'event_type']],
        'subscriptions' => ['title' => 'Subscriptions', 'table' => 'user_subscriptions', 'icon' => 'bi-gem', 'columns' => ['subscription_number', 'user_id', 'plan_id', 'purchase_amount', 'payment_status', 'status', 'starts_at', 'expires_at'], 'search' => ['subscription_number', 'payment_status', 'status']],
        'payments' => ['title' => 'Wallet & Payments', 'table' => 'payments', 'icon' => 'bi-credit-card', 'columns' => ['invoice_number', 'order_id', 'payment_gateway', 'payment_method', 'amount', 'currency', 'status', 'created_at'], 'search' => ['invoice_number', 'order_id', 'gateway_transaction_id']],
        'notifications' => ['title' => 'Notifications', 'table' => 'notifications', 'icon' => 'bi-bell', 'columns' => ['uuid', 'title', 'channel', 'priority', 'category', 'status', 'sent_at', 'created_at'], 'search' => ['uuid', 'title', 'message', 'category']],
        'reports' => ['title' => 'Reports & Analytics', 'table' => 'reports', 'icon' => 'bi-bar-chart', 'columns' => ['uuid', 'report_name', 'report_type', 'module', 'format', 'status', 'generated_at', 'created_at'], 'search' => ['uuid', 'report_name', 'report_type', 'module']],
        'settings' => ['title' => 'System Settings', 'table' => 'system_settings', 'icon' => 'bi-gear', 'columns' => ['setting_group', 'setting_key', 'setting_type', 'description', 'is_public', 'updated_at'], 'search' => ['setting_group', 'setting_key', 'description']],
        'roles' => ['title' => 'Roles & Permissions', 'table' => 'roles', 'icon' => 'bi-person-lock', 'columns' => ['name', 'display_name', 'description', 'is_system', 'status', 'created_at'], 'search' => ['name', 'display_name', 'description']],
    ];

    public function __invoke(Request $request, string $module): View
    {
        abort_unless(isset(self::MODULES[$module]), 404);
        $configuration = self::MODULES[$module];
        $table = $configuration['table'];
        $columns = array_values(array_filter($configuration['columns'], fn (string $column): bool => Schema::hasColumn($table, $column)));
        $searchColumns = array_values(array_filter($configuration['search'], fn (string $column): bool => Schema::hasColumn($table, $column)));
        $query = DB::table($table);

        if (Schema::hasColumn($table, 'deleted_at')) {
            $query->whereNull('deleted_at');
        }

        $search = $request->string('search')->trim()->toString();
        if ($search !== '' && $searchColumns !== []) {
            $query->where(function (Builder $nested) use ($searchColumns, $search): void {
                foreach ($searchColumns as $index => $column) {
                    $nested->{$index === 0 ? 'where' : 'orWhere'}($column, 'like', '%'.$search.'%');
                }
            });
        }

        $status = $request->string('status')->trim()->toString();
        if ($status !== '' && Schema::hasColumn($table, 'status')) {
            $query->where('status', $status);
        }

        $orderColumn = Schema::hasColumn($table, 'created_at') ? 'created_at' : 'id';
        $records = $query->select($columns)->orderByDesc($orderColumn)->paginate(15)->withQueryString();
        $statuses = Schema::hasColumn($table, 'status') ? DB::table($table)->whereNotNull('status')->distinct()->orderBy('status')->pluck('status') : collect();

        return view('admin.modules.index', compact('module', 'configuration', 'columns', 'records', 'statuses'));
    }
}
