<?php

/**
 * @var \Illuminate\Database\Eloquent\Collection $contents
 * @var int $page_number
 * @var \kernel\CgView $view
 */

use kernel\modules\post\models\Post;
use kernel\modules\user\models\User;
use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable;
use kernel\widgets\IconBtn\IconBtnCreateWidget;
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnViewWidget;

$table = new ListEloquentTable(new EloquentDataProvider(Post::class, [
    'currentPage' => $page_number,
    'perPage' => 3,
    'params' => ["class" => "table table-bordered", "border" => "2"],
    'baseUrl' => "/admin/post"
]));

$view->setTitle("Список постов");
$view->setMeta([
    'description' => 'Список постов системы'
]);

$entityRelation = new \kernel\EntityRelation();
$additionals = $entityRelation->getEntityRelationsBySlug("post");

foreach ($additionals as $additional) {
    $table->addColumn($additional, $additional, function ($id) use ($entityRelation, $additional) {
        return $entityRelation->getAdditionalPropertyByEntityId("post", $id, $additional);
    });
}

$table->columns([
    'created_at' => function ($data) {
        if (!$data){
            return null;
        }

        return (new DateTimeImmutable($data))->format("d-m-Y");
    },
    'updated_at' => function ($data) {
        if (!$data){
            return null;
        }

        return (new DateTimeImmutable($data))->format("d-m-Y");
    },
    'user_id' => (function ($data) {
        return User::find($data)->username;
    })
]);

$table->beforePrint(function () {
    return IconBtnCreateWidget::create(['url' => '/admin/post/create'])->run();
});
$table->addAction(function($row) {
    return IconBtnViewWidget::create(['url' => '/admin/post/view/' . $row['id']])->run();
});
$table->addAction(function($row) {
    return IconBtnEditWidget::create(['url' => '/admin/post/update/' . $row['id']])->run();
});
$table->addAction(function($row) {
    return IconBtnDeleteWidget::create(['url' => '/admin/post/delete/' . $row['id']])->run();
});
$table->create();
$table->render();