<?php

namespace App\Modules\Chat\controllers\api\v1;

use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use Illuminate\Support\Arr;

class ChannelsControllerREST extends BaseController
{
    public function index(Request $request)
    {
        $query = Channel::query()->where('closed', 0)->with('users', 'current_user');

        if ($request->input('private')) {
            $query->where('public', 0)->whereHas('users', function ($q) use ($request) {
                $q->where('user_id', $request->input('user_id', getAuthUserId()));
            });
        } else {
            $query->where('public', 1)->orWhereHas('users', function ($q) use ($request) {
                $q->where('user_id', $request->input('user_id', getAuthUserId()));
            });
        }

        // Paginate the results
        $query = $query->paginate($request->input('limit', 50));

        // Prepare the response
        $response = [
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
            'per_page'     => $query->perPage(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
        ];

        // Return the response
        return $response;
    }

    public function store(Request $request)
    {
        $channel = Channel::create($request->all());

        if (! $channel->exists) {
            return Response::json(['errors' => $channel->errors->all()], 400);
        }

        // Store the invited users and the person who created the channel will be automatically added
        $user_ids = array_merge(Arr::pluck($request->input('users'), 'id'), [getAuthUserId()]);
        $channel->users()->sync($user_ids);
        $channel->public = 0;

        return $channel->load('users');
    }

    /**
     * Leave a channel.
     *
     * @return Illuminate\Response
     */
    public function leave($id)
    {
        $channel = Channel::findOrFail($id);
        $channel->users()->detach(getAuthUserId());

        return $channel->load('users');
    }
}
