<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Boost;
use App\Models\Listing;
use App\Models\User;
use App\Models\Wallet;
use App\Models\WalletTransaction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    /* ── Dashboard ── */
    public function dashboard(): JsonResponse
    {
        return response()->json([
            'total_escorts'      => User::where('role', 'escort')->count(),
            'active_escorts'     => User::where('role', 'escort')->where('is_active', true)->count(),
            'total_listings'     => Listing::count(),
            'pending_listings'   => Listing::where('status', 'pending')->count(),
            'active_listings'    => Listing::where('status', 'active')->count(),
            'active_boosts'      => Boost::where('status', 'active')->count(),
            'total_wallet_funds' => Wallet::sum('balance'),
            'total_topups'       => WalletTransaction::where('type', 'topup')->sum('amount'),
            'recent_listings'    => Listing::with('user:id,name,city')->latest()->limit(10)->get(),
        ]);
    }

    /* ── Users ── */
    public function users(Request $request): JsonResponse
    {
        $users = User::where('role', 'escort')
            ->with('wallet')
            ->withCount('listings')
            ->latest()
            ->paginate(20);

        return response()->json($users);
    }

    public function showUser(User $user): JsonResponse
    {
        return response()->json($user->load(['listings', 'wallet', 'walletTransactions']));
    }

    public function updateUser(Request $request, User $user): JsonResponse
    {
        $data = $request->validate([
            'is_verified' => 'sometimes|boolean',
            'is_active'   => 'sometimes|boolean',
        ]);
        $user->update($data);
        return response()->json(['message' => 'User updated.', 'user' => $user]);
    }

    public function toggleUser(User $user): JsonResponse
    {
        $user->update(['is_active' => !$user->is_active]);
        $status = $user->is_active ? 'activated' : 'suspended';
        return response()->json(['message' => "User {$status}.", 'user' => $user]);
    }

    public function suspendUser(Request $request, User $user): JsonResponse
    {
        $data = $request->validate(['reason' => 'required|string|max:500']);
        $user->update([
            'is_active' => false,
            'suspension_reason' => $data['reason']
        ]);
        return response()->json(['message' => 'User suspended.', 'user' => $user]);
    }

    /* ── Listings ── */
    public function listings(Request $request): JsonResponse
    {
        $query = Listing::with(['user:id,name,city', 'primaryImage']);

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        return response()->json($query->latest()->paginate(20));
    }

    public function updateListingStatus(Request $request, Listing $listing): JsonResponse
    {
        $data = $request->validate([
            'status' => 'required|in:active,pending,paused,rejected',
        ]);
        $listing->update($data);
        return response()->json(['message' => 'Status updated.', 'listing' => $listing]);
    }

    public function deleteListing(Listing $listing): JsonResponse
    {
        $listing->delete();
        return response()->json(['message' => 'Listing deleted.']);
    }

    /* ── Boosts ── */
    public function boosts(): JsonResponse
    {
        $boosts = Boost::with(['listing:id,title,city', 'user:id,name'])
            ->latest()
            ->paginate(20);

        return response()->json($boosts);
    }

    public function pauseBoost(Boost $boost): JsonResponse
    {
        $boost->update(['status' => 'paused']);
        return response()->json(['message' => 'Boost paused.']);
    }

    /* ── Financials ── */
    public function transactions(Request $request): JsonResponse
    {
        $txns = WalletTransaction::with('user:id,name,email')
            ->latest()
            ->paginate(30);

        return response()->json($txns);
    }

    public function wallets(): JsonResponse
    {
        $wallets = Wallet::with('user:id,name,email')
            ->orderByDesc('balance')
            ->paginate(30);

        return response()->json($wallets);
    }

    /* ── Fund Management ── */
    public function addFunds(Request $request, User $user): JsonResponse
    {
        $data = $request->validate([
            'amount' => 'required|numeric|min:1',
            'description' => 'nullable|string'
        ]);

        $wallet = $user->wallet()->firstOrCreate([], ['balance' => 0]);

        $wallet->balance += $data['amount'];
        $wallet->save();

        WalletTransaction::create([
            'user_id' => $user->id,
            'wallet_id' => $wallet->id,
            'type' => 'topup',
            'amount' => $data['amount'],
            'balance_after' => $wallet->balance,
            'description' => $data['description'] ?? 'Admin Top-up',
            'reference' => 'admin_credit_' . time(),
        ]);

        return response()->json(['message' => 'Funds added successfully.', 'wallet' => $wallet]);
    }

    public function removeFunds(Request $request, User $user): JsonResponse
    {
        $data = $request->validate([
            'amount' => 'required|numeric|min:1',
            'description' => 'nullable|string'
        ]);

        $wallet = $user->wallet()->firstOrCreate([], ['balance' => 0]);

        if ($wallet->balance < $data['amount']) {
            return response()->json(['message' => 'Insufficient funds.'], 400);
        }

        $wallet->balance -= $data['amount'];
        $wallet->save();

        WalletTransaction::create([
            'user_id' => $user->id,
            'wallet_id' => $wallet->id,
            'type' => 'deduction',
            'amount' => $data['amount'],
            'balance_after' => $wallet->balance,
            'description' => $data['description'] ?? 'Admin Deduction',
            'reference' => 'admin_debit_' . time(),
        ]);

        return response()->json(['message' => 'Funds removed successfully.', 'wallet' => $wallet]);
    }

    /* ── Staff Management ── */
    public function staffList(Request $request): JsonResponse
    {
        if (!$request->user()->isAdmin()) {
            return response()->json(['message' => 'Only main admin can view staff.'], 403);
        }
        $staff = User::where('role', 'staff')->latest()->get();
        return response()->json($staff);
    }

    public function createStaff(Request $request): JsonResponse
    {
        if (!$request->user()->isAdmin()) {
            return response()->json(['message' => 'Only main admin can create staff.'], 403);
        }
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|string|min:8',
            'permissions' => 'nullable|array',
            'permissions.*' => 'string'
        ]);

        $staff = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => \Illuminate\Support\Facades\Hash::make($data['password']),
            'role' => 'staff',
            'permissions' => $data['permissions'] ?? [],
        ]);

        return response()->json(['message' => 'Staff created.', 'staff' => $staff], 201);
    }

    public function updateStaff(Request $request, User $staff): JsonResponse
    {
        if (!$request->user()->isAdmin() || $staff->role !== 'staff') {
            return response()->json(['message' => 'Unauthorized or invalid user.'], 403);
        }
        $data = $request->validate([
            'name' => 'sometimes|string|max:255',
            'email' => 'sometimes|email|unique:users,email,'.$staff->id,
            'password' => 'nullable|string|min:8',
            'permissions' => 'nullable|array',
            'permissions.*' => 'string'
        ]);

        if (isset($data['password'])) {
            $data['password'] = \Illuminate\Support\Facades\Hash::make($data['password']);
        } else {
            unset($data['password']);
        }

        $staff->update($data);
        return response()->json(['message' => 'Staff updated.', 'staff' => $staff]);
    }

    public function deleteStaff(Request $request, User $staff): JsonResponse
    {
        if (!$request->user()->isAdmin() || $staff->role !== 'staff') {
            return response()->json(['message' => 'Unauthorized.'], 403);
        }
        $staff->delete();
        return response()->json(['message' => 'Staff deleted.']);
    }

    /* ── Reports & Moderation ── */
    public function reports(Request $request): JsonResponse
    {
        $reports = \Illuminate\Support\Facades\DB::table('reports')
            ->join('listings', 'reports.listing_id', '=', 'listings.id')
            ->join('users', 'listings.user_id', '=', 'users.id')
            ->select('reports.*', 'listings.title', 'listings.user_id', 'users.name as escort_name')
            ->orderByDesc('reports.created_at')
            ->paginate(20);

        return response()->json($reports);
    }

    public function dismissReport(int $id): JsonResponse
    {
        \Illuminate\Support\Facades\DB::table('reports')->where('id', $id)->delete();
        return response()->json(['message' => 'Report dismissed.']);
    }
}
