<?php

namespace Modules\Noticeboard\Repositories\Eloquents;

use App\Repositories\Eloquents\BaseRepository;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Modules\Noticeboard\Entities\Noticeboard;
use Modules\Noticeboard\Entities\NoticeboardAssign;
use Modules\Noticeboard\Repositories\Interfaces\NoticeboardRepositoryInterface;

class NoticeboardRepository extends BaseRepository implements NoticeboardRepositoryInterface
{
    protected $model, $noticeboardAssign;

    public function __construct(Noticeboard $model, NoticeboardAssign $noticeboardAssign)
    {
        $this->model = $model;
        $this->noticeboardAssign = $noticeboardAssign;
    }

    public function allGeneral(array $columns = ['*'], array $relations = []): Collection
    {
        $query = $this->model->where('group', 1)->with($relations);

        if (isModuleActive('Organization') && Auth::user()->isOrganization()) {
            $query->whereHas('user', function ($q) {
                $q->where('organization_id', Auth::id());
                $q->orWhere('user_id', Auth::id());
            });
        }

        return $query->latest()->get($columns);
    }

    public function createNotice(array $payload): ?Model
    {
        $payload['user_id'] = Auth::id();
        $model = $this->model->create($payload);
        $this->roleAssign($model->id, $payload['role_id']);

        if ($model) {
            $this->successMsg();
        }
        return $model->fresh();
    }

    public function updateNotice(array $payload): ?bool
    {
        $model = $this->model->where('id', $payload['id'])->update(Arr::except($payload, ['role_id']));

        $this->roleDelete($payload['id']);
        $this->roleAssign($payload['id'], $payload['role_id']);

        if ($model) {
            $this->successMsg();
        }
        return $model;
    }

    public function deleteNotice(array $payload): void
    {
        $model = $this->model->where('id', $payload['id'])->first();
        $model->delete();
        $this->roleDelete($payload['id']);
        $this->successMsg();
    }

    private function roleAssign(int $noticeboard, array $role_ids)
    {
        foreach ($role_ids as $role_id) {
            $this->noticeboardAssign->create([
                'role_id' => $role_id,
                'noticeboard_id' => $noticeboard
            ]);
        }
    }

    private function roleDelete(int $noticeboard)
    {
        $this->noticeboardAssign->where('noticeboard_id', $noticeboard)->delete();
    }
}
