<?php

namespace objects;

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

class module_action_logs_o extends db
{
    use db_object_t;

    /**
     * The module name
     * @var object_property $module The module name
     */
    public object_property $module;
    /**
     * The action name
     * @var object_property $action The action name
     */
    public object_property $action;
    /**
     * The action status code (HTTP status code, e.g. 200, 404, 500)
     * @var object_property $status_code The action status code (HTTP status code, e.g. 200, 404, 500)
     */
    public object_property $status_code;
    /**
     * The action data
     * @var object_property $data The data JSON encoded
     */
    public object_property $data;
    /**
     * The action created at
     * @var object_property $created_at The action created at
     */
    public object_property $created_at;


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

    /**
     * Add a module action log
     * @param string $module The module name
     * @param string $action The action name
     * @param int $status_code The action status code (HTTP status code, e.g. 200, 404, 500)
     * @param array $data The action data
     * @return void
     * @throws Exception If the object was not created successfully
     */
    public function add(string $module, string $action, int $status_code, array $data): void
    {
        global /** @var db $db */
        $db;
        // Sanitize the input
        $module = $db->escape_string($module);
        $action = $db->escape_string($action);
        $status_code = (int)$status_code;
        // JSON encode the data
        $encoded_data = $db->escape_string(json_encode($data));
        // Add the object
        $tmp_id = self::add_object([
            'module' => $module,
            'action' => $action,
            'status_code' => $status_code,
            'data' => $encoded_data,
        ]);
        if (!$tmp_id) {
            throw new Exception('The object was not created successfully.');
        }
        $this->id = $tmp_id;
        self::getObjectProperties();
        self::objectChanged();
    }

    public function getObjectProperties(): void
    {
        $this->module = new object_property($this->table, $this->id, 'module', 'string', false);
        $this->action = new object_property($this->table, $this->id, 'action', 'string', false);
        $this->status_code = new object_property($this->table, $this->id, 'status_code', 'int', false);
        $this->data = new object_property($this->table, $this->id, 'data', 'string', false);
        $this->created_at = new object_property($this->table, $this->id, 'created_at', 'datetime', false);
    }

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

    /**
     * Get the object as an array
     * @return array The object as an array
     */
    public function asArray(): array
    {
        return [
            'id' => (int)$this->id,
            'module' => (string)$this->module->value(),
            'action' => (string)$this->action->value(),
            'status_code' => (int)$this->status_code->value(),
            'data' => self::decodeData((string)$this->data->value()),
            'created_at' => (string)$this->created_at->value(),
        ];
    }

    /**
     * Decode the data
     * @param string $data The data JSON encoded
     * @return array The data
     */
    public static function decodeData(string $data): array
    {
        $decoded = json_decode($data, true);
        if ($decoded === null) {
            $decoded = json_decode(htmlspecialchars_decode($data), true);
        }

        // If it's still null, try stripping slashes - common when data is double escaped in DB
        if ($decoded === null) {
            $decoded = json_decode(stripslashes($data), true);
        }

        // Final attempt: stripslashes + htmlspecialchars_decode
        if ($decoded === null) {
            $decoded = json_decode(stripslashes(htmlspecialchars_decode($data)), true);
        }

        return is_array($decoded) ? $decoded : [];
    }
}