<?php

namespace objects;

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

class customer_codes_o extends db
{
    use db_object_t;

    public object_property $user_id;
    public object_property $code;

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

    public function objectChanged(): void
    {
        // Since the customer_codes object is not cached, there is no need to invalidate the cache
    }

    public function getCode(int $user_id): customer_codes_o
    {
        global $db;
        // Get the record from the database
        $sql = "SELECT * FROM $this->table WHERE user_id = $user_id";
        $result = $db->query($sql);
        if ($result->num_rows > 0) {
            $this->id = $user_id;
            $this->getObjectProperties();
        } else {
            $this->set($user_id, null);
        }
        return $this;
    }

    public function setCode(int $id, mixed $code): customer_codes_o
    {
        global $db, $response;
        try {
            // Avoid SQL injection
            $code = $db->escape_string($code);
            // Update the record in the database
            $sql = "UPDATE $this->table SET code = '$code' WHERE user_id = $id";
            $db->query($sql);
            // Set the values of the object properties
            $this->id = $id;
            $this->getObjectProperties();
        } catch (\Exception $e) {
            $response->error($e->getMessage());
        }
        return $this;
    }

    public function getObjectProperties(): void
    {
        $this->user_id = new object_property($this->table, $this->id, 'user_id', 'int', true);
        $this->code = new object_property($this->table, $this->id, 'code', 'string', true);
    }

    public function set(int $user_id, string|null $code): customer_codes_o
    {
        global $db, $response;
        try {
            // Avoid SQL injection
            if (!is_null($code)) {
                $code = $db->escape_string($code);
            }
            // Create a new record in the database ( Replace the code, if an entry already exists )
            $sql = "INSERT INTO $this->table (user_id, code) VALUES ($user_id, '$code') ON DUPLICATE KEY UPDATE code = '$code'";
            $db->query($sql);

            // Get the id of the new record
            $this->id = $db->insert_id();

            // Set the values of the object properties
            $this->getObjectProperties();
        } catch (\Exception $e) {
            $response->error($e->getMessage());
        }
        return $this;
    }

}