<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\TravelAgent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class UserManagementController extends Controller
{
    public function index(Request $request)
    {
        $query = User::with('travelAgent');

        // Search filter
        if ($request->has('search') && $request->search) {
            $query->where('name', 'like', '%' . $request->search . '%')
                  ->orWhere('email', 'like', '%' . $request->search . '%')
                  ->orWhere('mobile', 'like', '%' . $request->search . '%');
        }

        // Travel Agent filter
        if ($request->has('travel_agent_id') && $request->travel_agent_id) {
            $query->where('travel_agent_id', $request->travel_agent_id);
        }

        // Status filter
        if ($request->has('is_active') && in_array($request->is_active, ['active', 'inactive'])) {
            $query->where('is_active', $request->is_active === 'active');
        }

        $users = $query->orderBy('created_at', 'desc')->paginate(20);

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

    public function toggleStatus($id)
    {
        $user = User::findOrFail($id);
        $user->update(['is_active' => !$user->is_active]);

        // Logout user if deactivated
        if (!$user->is_active) {
            $user->tokens()->delete();
        }

        $action = $user->is_active ? 'activated' : 'deactivated';

        return response()->json([
            'message' => "User {$action} successfully",
            'data' => $user
        ]);
    }

    public function update(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $validated = $request->validate([
            'name' => 'sometimes|string|max:255',
            'email' => ['sometimes', 'email', Rule::unique('users')->ignore($user->id)],
            'mobile' => ['sometimes', 'string', Rule::unique('users')->ignore($user->id)],
            'is_admin' => 'sometimes|boolean',
            'is_active' => 'sometimes|boolean',
            'travel_agent_id' => 'sometimes|exists:travel_agents,id',
        ]);

        // Logout user if deactivated
        if (isset($validated['is_active']) && !$validated['is_active']) {
            $user->tokens()->delete();
        }

        $user->update($validated);

        return response()->json([
            'message' => 'User updated successfully',
            'data' => $user->load('travelAgent')
        ]);
    }
}