<?php

namespace App\Http\Controllers\Main;

use App\Friend;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class FriendsController extends Controller
{
    public function search(Request $request)
    {
        $q = $request->q;

        $users = User::where('id', '!=', Auth::id())
            ->where(function ($query) use ($q) {
                $query->where('name', 'like', "%$q%");
                $query->orWhere('surname', 'like', "%$q%");
            })->take(10)->get();

        if (count($users) === 0) {

            $full_name_arr = explode(' ', $q);

            $name = (isset($full_name_arr[0])) ? $full_name_arr[0] : '';
            $surname = (isset($full_name_arr[1])) ? $full_name_arr[1] : '';

            $users = User::where('id', '!=', Auth::id())
                ->where(function ($query) use ($name, $surname) {
                    $query->where('name', 'like', "%$name%");
                    $query->orWhere('surname', 'like', "%$surname%");
                })->take(10)->get();

        }

        $users_list = [];

        foreach ($users as $user) {
            $users_list[] = [
                "id" => $user->id,
                "name" => $user->name,
                "surname" => $user->surname,
                "avatar_url" => $user->avatar_url
            ];
        }

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

    public function addFriend(Request $request)
    {
        $friend = User::find($request->id);
        if (!$friend) return abort(404);


        /**
         * @status
         * 1 - заявка отправлена пользователю @user_id
         * 2 - заявка отклонена @user_id
         * 3 - заявка принята
         * 4 - оставить в подписчиках @sender_request
         */

        Friend::create([
            "sender_request" => Auth::id(),
            "user_id" => $request->id,
            "status" => 1
        ]);

        return redirect()->back();
    }

    static function myFriends()
    {
        $friends = Friend::where(function ($query) {
            $query->where('sender_request', Auth::id());
            $query->orWhere('user_id', Auth::id());
        })->where('status', 3)->get();

        return $friends;
    }
}
