<?php

namespace App\FormModel\api\v1;


use App\Helpers\AppHelper;
use App\Model\AppArticle;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;

class ArticlesModel
{
    #[Inject]
    private readonly RequestInterface $_request;

    public function edit()
    {
        $query = AppArticle::find($this->_request->post('id'));
        $query->cover = AppHelper::extractImagePath($this->_request->post('cover'));

        $query->title = $this->_request->post('title');
        $query->brand = $this->_request->post('brand');

        $images = array_values($this->_request->post('images'));
        foreach ($images as &$image) {
            $image['src'] = AppHelper::extractImagePath($image['src']);
        }
        $query->images = json_encode($images);

        $query->save();
        return true;
    }

    public function create()
    {
        $query = new AppArticle();
        $query->cover = AppHelper::extractImagePath($this->_request->post('cover'));
        $query->title = $this->_request->post('title');
        $query->brand = $this->_request->post('brand');

        $images = array_values($this->_request->post('images') ?: []);
        foreach ($images as &$image) {
            $image['src'] = AppHelper::extractImagePath($image['src']);
        }
        $query->images = json_encode($images);

        $query->save();
        return true;
    }
}