<?php namespace App\Controllers\Api\Manager\PlansExtra;

use App\Controllers\PrivateController;
use App\Models\PlansExtraModel;
use CodeIgniter\HTTP\ResponseInterface;
use ReflectionException;

class UpdatePlanExtra extends PrivateController
{
  	/**************************************************************************************
     * PUBLIC FUNCTIONS
     **************************************************************************************/

    /**
     * Update plan extra
     * @return ResponseInterface
     * @throws ReflectionException
     */
    public function index(): ResponseInterface
    {
        if (!$this->validate($this->update_validation_type())) {
            return $this->respond(["message" => $this->validator->getErrors()], 400);
        }

        $id = (int) $this->request->getGet("id");

        $plansExtra = new PlansExtraModel();

        $planExtra = $plansExtra
            ->where("id", $id)
            ->select("id")
            ->first();

        if (!$planExtra) {
            return $this->respond(["message" => lang("Message.message_59")], 400);
        }

        $plansExtra->update($planExtra["id"], [
            "build_count_extra" => (int) $this->request->getJsonVar("build_count_extra"),
            "price"             => esc($this->request->getJsonVar("price")),
            "save"              => esc($this->request->getJsonVar("save")),
            "api_id"            => esc($this->request->getJsonVar("api_id")),
            "status"            => esc($this->request->getJsonVar("status")),
        ]);

        return $this->respond(["status" => "ok"], 200);
    }
  
  	/**************************************************************************************
     * PRIVATE FUNCTIONS
     **************************************************************************************/

    /**
     * Get validation rules for update plan
     * @return array
     */
    private function update_validation_type(): array
    {
        return [
            "build_count_extra" => [
                "label" => lang("Fields.field_159"),
                "rules" => "required|numeric|greater_than_equal_to[0]"
            ],
            "price" => [
                "label" => lang("Fields.field_105"),
                "rules" => "required|numeric"
            ],
            "save"  => [
                "label" => lang("Fields.field_106"),
                "rules" => "required|numeric"
            ],
            "api_id"  => [
                "label" => lang("Fields.field_151"),
                "rules" => "permit_empty|max_length[1000]"
            ],
        ];
    }
}