<?php

namespace objects;

use classes\db;
use classes\object_property;
use classes\xlvask;
use Exception;
use helpers\xlvask_customer;
use helpers\xlvask_vehicle;
use traits\db_object_t;

class object_attachments_o extends db
{
    use db_object_t;

    public object_property $object_type; // The object type (e.g. 'users_o', 'customers_o', etc.)
    public object_property $object_id; // The ID of the object this attachment is linked to
    public object_property $content; // The content of the attachment (JSON formatted)
    public object_property $created_at; // The timestamp when the attachment was created
    public object_property $updated_at; // The timestamp when the attachment was last updated
    public object_property $deleted_at; // The timestamp when the attachment was deleted (if applicable)

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

    /**
     * Add a new attachment
     * @param array $data The properties
     * @returns void
     * @throws Exception If the object was not created successfully
     */
    public function add(array $data): void
    {
        $tmp_id = self::add_object($data);
        $this->id = $tmp_id;
        self::getObjectProperties();
        self::objectChanged();
    }

    public function getObjectProperties(): void
    {
        $this->object_type = new object_property($this->table, $this->id, 'object_type', 'string', false);
        $this->object_id = new object_property($this->table, $this->id, 'object_id', 'int', false);
        $this->content = new object_property($this->table, $this->id, 'content', 'json', false);
        $this->created_at = new object_property($this->table, $this->id, 'created_at', 'string', false);
        $this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'string', false);
        $this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'string', false);
    }

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

    public function toArray(): array
    {
        return [
            'id' => (int)$this->id,
            'object_type' => (string)$this->object_type->value(),
            'object_id' => (int)$this->object_id->value(),
            'content' => $this->content->value(),
            'created_at' => $this->created_at->value(),
            'updated_at' => $this->updated_at->value(),
            'deleted_at' => $this->deleted_at->value(),
        ];
    }

    public function isWashCertificate(): bool
    {
        $content = json_decode($this->content->value(), true);
        return isset($content['other']) && $content['other'] === 'wash_certificate';
    }
}