<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Vms\Event;
use App\Models\Onm\Office;
use App\Models\UserVerify;
use Illuminate\Http\Request;

class MemberSearchController extends Controller
{
    public function index(Request $request)
    {
        if ($request->type == 'user_verify') {
            return $this->searchUserVerify();
        } elseif ($request->type == 'office') {
            return $this->searchOffice();
        } elseif ($request->type == 'user') {
            return $this->searchUser();
        } elseif ($request->type == 'event') {
            return $this->searchEvent();
        }

        return collect([]);
    }

    public function searchUserVerify()
    {
        $query = new UserVerify();

        if (request()->has('search') && request()->filled('search')) {
            $query = $query->search(request()->search, 10);
        } else {
            $query = $query->search('', 10);
        }
        $query = collect($query)->map(function ($item, $key) {
            $data = [];
            $data['id'] = $item->employee;
            $data['name'] = $item->employee_name;
            $data['username'] = $item->user_name;
            return $data;
        });

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

    public function searchOffice()
    {
        $query = Office::query()->whereIn('office_level', [2,3,4])->active();

        if (request()->has('search') && request()->filled('search')) {
            $query->search(request()->search);
        }

        $query = $query->limit(10)->get()->map(function ($item, $key) {
            $item['id'] = $item->office;
            $item['name'] = $item->office_name;
            $item['name_bn'] = $item->office_name_bn;
            return $item;
        });

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

    public function searchUser()
    {
        $query = User::query();

        if (request()->has('search') && request()->filled('search')) {
            $query->search(request()->search);
        }

        $query = $query->limit(10)->get()->map(function ($item, $key) {
            $data = [];
            $data['id'] = $item->id;
            $data['name'] = $item->name;
            $data['username'] = $item->username;
            $data['mobile'] = $item->mobile;
            $data['employee_id'] = $item->employee_id;
            return $data;
        });

        return response()->json($query);

    }

    public function searchEvent()
    {
        $query = Event::query();

        if (request()->has('search') && request()->filled('search')) {
            $query->search(request()->search);
        }

        $query = $query->limit(10)->get()->map(function ($item, $key) {
            $data = [];
            $data['id'] = $item->id;
            $data['name'] = $item->name;
            $data['description'] = $item->description;
            return $data;
        });

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