<?php
/**
 * Action Logger
 *
 * @package AIContentGenerator
 */

namespace AICG;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Handles logging for scheduler actions
 */
class Action_Logger
{
    /**
     * Get table name
     */
    private static function get_table()
    {
        global $wpdb;
        return $wpdb->prefix . 'roidaico_logs';
    }

    /**
     * Log an action
     */
    public static function log($action, $message, $status = 'info', $schedule_id = null)
    {
        global $wpdb;

        return $wpdb->insert(
            self::get_table(),
            array(
                'action' => $action,
                'message' => $message,
                'status' => $status,
                'schedule_id' => $schedule_id,
                'created_at' => current_time('mysql'),
            ),
            array('%s', '%s', '%s', '%d', '%s')
        );
    }

    /**
     * Get logs
     */
    public static function get_logs($limit = 100, $offset = 0)
    {
        global $wpdb;
        $table = self::get_table();

        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table ORDER BY created_at DESC LIMIT %d OFFSET %d",
            $limit,
            $offset
        ));
    }

    /**
     * Clear old logs
     */
    public static function clear_old_logs($days = 30)
    {
        global $wpdb;
        $table = self::get_table();

        return $wpdb->query($wpdb->prepare(
            "DELETE FROM $table WHERE created_at < DATE_SUB(NOW(), INTERVAL %d DAY)",
            $days
        ));
    }

    /**
     * Get logs count
     */
    public static function get_logs_count($status = null)
    {
        global $wpdb;
        $table = self::get_table();

        if ($status) {
            return $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $table WHERE status = %s",
                $status
            ));
        }

        return $wpdb->get_var("SELECT COUNT(*) FROM $table");
    }

    /**
     * Clear all logs
     */
    public static function clear_all_logs()
    {
        global $wpdb;
        $table = self::get_table();

        return $wpdb->query("TRUNCATE TABLE $table");
    }

    /**
     * Get logs by status
     */
    public static function get_logs_by_status($status, $limit = 100, $offset = 0)
    {
        global $wpdb;
        $table = self::get_table();

        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table WHERE status = %s ORDER BY created_at DESC LIMIT %d OFFSET %d",
            $status,
            $limit,
            $offset
        ));
    }
}
