<?php

namespace kernel;

use Illuminate\Database\Eloquent\Model;
use JetBrains\PhpStorm\NoReturn;
use kernel\helpers\Debug;

class RestController
{

    protected Model $model;


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

    #[NoReturn] public function actionIndex(): void
    {
        $request = new Request();
        $page = $request->get('page') ?? 1;
        $perPage = $request->get('per_page') ?? 10;
        $query = $this->model->query();

        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);
    }

    #[NoReturn] public function actionView($id): void
    {
        $expand = $this->expand();
        $request = new Request();
        $expandParams = explode( ",", $request->get('expand') ?? "");
        $model = $this->model->where("id", $id)->first();
        $finalExpand = array_intersect($expandParams, $expand);
        if ($finalExpand){
            $model->load($finalExpand);
        }
        $res = [];
        if ($model){
            $res = $model->toArray();
        }

        $this->renderApi($res);
    }

    #[NoReturn] public function actionDelete($id): void
    {
        $model = $this->model->where("id", $id)->first();
        $res = [];
        if ($model){
            $res = $model->toArray();
        }

        $model->delete();

        $this->renderApi($res);

    }

    #[NoReturn] public function actionStore(): void
    {
        $request = new Request();
        $data = $request->post();
        foreach ($this->model->getFillable() as $item){
            $this->model->{$item} = $data[$item] ?? null;
        }
        $this->model->save();

        $this->renderApi($this->model->toArray());
    }

    #[NoReturn] public function actionEdit(int $id): void
    {
        $request = new Request();
        $data = $request->post();

        $model = $this->model->where('id', $id)->first();

        foreach ($model->getFillable() as $item){
            $model->{$item} = $data[$item] ?? null;
        }

        $model->save();
        $this->renderApi($model->toArray());
    }

    #[NoReturn] public function returnError(int $code): void
    {
        http_response_code($code);
        die('Forbidden');
    }

    #[NoReturn] protected function renderApi(array $data): void
    {
        header("Content-Type: application/json");
        echo json_encode($data);
        exit();
    }



}