<?php

namespace App\Repositories\Core;

use App\Datatables\Admin\Core\CommentsDataTable;
use App\Models\Core\Comment;
use App\Repositories\Core\Auth\Users;
use App\Traits\Model\Basic;

class Comments
{
    use Basic;

    public static function getDatatable()
    {
        return (new CommentsDataTable())->html();
    }

    public static function getCommentsByModel($model, $model_id)
    {
        return self::getCommentsByClass(self::getClass($model), $model_id);
    }

    public static function getCommentsByClass($class, $id)
    {
        return self::getByModel(self::getModel($class, $id));
    }

    public static function getItem($class, $id)
    {
        return $class::find($id);
    }

    public static function getClass($model)
    {
        return 'App\Models\\' . str_replace('.', '\\', $model);
    }

    public static function getByModel($model)
    {
        return $model ? $model->comments->sortByDesc('updated_at')->toArray() : false;
    }

    public static function storeComments($model, $comments)
    {
        foreach (($comments ?? []) as $comment) {
            self::storeComment($model, $comment);
        }
    }

    public static function storeComment($model, $comment)
    {
        return $model->comment($comment);
    }

    public static function store($data)
    {
        $id = $data['id'] ?? false;
        unset($data['_token']);
        $data['commentable_type'] = Comments::getClass($data['commentable_type']);
        $data['commentable_id'] = (int) $data['commentable_id'];

        return $id ? self::update($data, $id) : self::create($data);
    }

    public static function create($data)
    {
        unset($data['id']);
        $data['is_approved'] = true;
        $data['user_id'] = Users::getId();

        return Comment::create($data);
    }

    public static function getModel()
    {
        return Comment::query();
    }
}
