<?php

namespace objects;

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

class cron_o extends db
{
    use db_object_t;

    public object_property $name;
    public object_property $last_run;
    public object_property $times_ran;

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

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

    public function getByName(string $name): cron_o
    {
        global $db;
        // Get the record from the database
        $sql = "SELECT * FROM $this->table WHERE name = '$name'";
        $result = $db->query($sql);
        if ($result->num_rows > 0) {
            $this->id = $result->fetch_assoc()['id'];
            $this->getObjectProperties();
        }
        return $this;
    }

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

    public function incrementTimesRan(int $id): void
    {
        global $db;
        $this->id = $id;
        // Update the record in the database
        $sql = "UPDATE $this->table SET times_ran = times_ran + 1 WHERE id = $this->id";
        $db->query($sql);
    }

    public function updateLastRun(int $id): void
    {
        global $db;
        $this->id = $id;
        // Update the record in the database
        $sql = "UPDATE $this->table SET last_run = NOW() WHERE id = $this->id";
        $db->query($sql);
    }

    public function getCronCreateIfNotExists(string $name): cron_o
    {
        global $db;
        // Avoid SQL injection
        $name = $db->escape_string($name);
        // Check if the record exists
        $sql = "SELECT id FROM $this->table WHERE name = '$name'";
        $result = $db->query($sql);
        if ($result->num_rows == 0) {
            // Create a new record in the database
            $sql = "INSERT INTO $this->table (name, last_run, times_ran) VALUES ('$name', NOW(), 0)";
            $db->query($sql);
            // Get the id of the new record
            $this->id = $db->insert_id();
            // Set the values of the object properties
            $this->getObjectProperties();
        }
        return $this;
    }
}