<?php

namespace objects;

use classes\db;
use classes\object_property;
use Exception;
use traits\db_object_t;

class customer_vehicles_addons_o extends db
{
    use db_object_t;

    public object_property $vehicle_id; // The id of the vehicle
    public object_property $addon_id; // The id of the addon
    public object_property $amount; // The amount of the addon

    public function structure(): void
    {
        $this->setTable('customer_vehicles_addons');
    }

    /**
     * Add a new vehicle addon
     * @param int $vehicle_id
     * @param int $addon_id
     * @param int $amount
     * @return void
     * @throws Exception If the object was not created successfully
     */
    public function add(int $vehicle_id, int $addon_id, int $amount = 1): void
    {
        $tmp_id = self::add_object([
            'vehicle_id' => (int)$vehicle_id,
            'addon_id' => (int)$addon_id,
            'amount' => (int)$amount
        ]);
        $this->id = $tmp_id;
        self::getObjectProperties();
        self::objectChanged();
    }

    public function getObjectProperties(): void
    {
        $this->vehicle_id = new object_property($this->table, $this->id, 'vehicle_id', 'int', true);
        $this->addon_id = new object_property($this->table, $this->id, 'addon_id', 'int', true);
        $this->amount = new object_property($this->table, $this->id, 'amount', 'int', true);
    }

    public function objectChanged(): void
    {
        //TODO: Add cache invalidation
    }

    /**
     * Convert the object to an array
     * @throws Exception If the object is not selected
     * @throws Exception If the object is not foun
     */
    public function asArray(): array
    {
        self::requireSelected();
        return [
            'id' => (int)$this->id,
            'vehicle_id' => (int)$this->vehicle_id->value(),
            'addon_id' => (int)$this->addon_id->value(),
            'amount' => (int)$this->amount->value(),
            'product' => self::getProduct($this->getOption((int)$this->addon_id->value()))->asArray(),
        ];
    }

    /**
     * @param product_options_o $product_option
     * @return products_o
     * @throws Exception If the object is not selected
     * @throws Exception If the product is not selected
     * @throws Exception If the product is not found
     */
    private function getProduct(product_options_o $product_option): products_o
    {
        return (new products_o())->select((int)$product_option->option_id->value());
    }

    /**
     * @return product_options_o
     * @throws Exception If the object is not selected
     */
    private function getOption(): product_options_o
    {
        self::requireSelected();
        return (new product_options_o())->select((int)$this->addon_id->value());
    }

}