<?php

namespace kernel\modules\post\controllers;

use Illuminate\Database\Eloquent\Model;
use JetBrains\PhpStorm\NoReturn;
use kernel\App;
use kernel\helpers\Debug;
use kernel\modules\post\models\Post;
use kernel\Request;
use kernel\RestController;

class PostRestController extends RestController
{
    public function __construct()
    {
        $this->model = new Post();
    }

    protected function expand(): array
    {
        return ["user"];
    }

    public function actionIndex(): void
    {
        $request = new Request();
        $page = $request->get('page') ?? 1;
        $perPage = $request->get('per_page') ?? 10;
        $query = $this->model->query();
        if (App::$user){
            $query->where("user_id", App::$user->id);
        }

        if ($page > 1) {
            $query->skip(($page - 1) * $perPage)->take($perPage);
        } else {
            $query->take($perPage);
        }

        $expand = $this->expand();
        $expandParams = explode( ",", $request->get('expand') ?? "");
        $finalExpand = array_intersect($expandParams, $expand);
        if ($finalExpand) {
            $res = $query->get()->load($finalExpand)->toArray();
        } else {
            $res = $query->get()->toArray();
        }

        $this->renderApi($res);
    }
}