<?php
/**
 * DBA Logger - Stores generation logs in custom DB table
 */
class DBA_Logger {

    private static $instance = null;

    public static function get_instance() {
        if (null === self::$instance) self::$instance = new self();
        return self::$instance;
    }

    private function __construct() {}

    /**
     * Log a generation run
     */
    public function log($data) {
        global $wpdb;
        $table = $wpdb->prefix . DBA_LOG_TABLE;

        $wpdb->insert($table, array(
            'run_date'          => isset($data['run_date']) ? $data['run_date'] : current_time('Y-m-d'),
            'run_time'          => isset($data['run_time']) ? $data['run_time'] : current_time('mysql'),
            'theme'             => isset($data['theme']) ? sanitize_text_field($data['theme']) : '',
            'title'             => isset($data['title']) ? sanitize_text_field($data['title']) : '',
            'slug'              => isset($data['slug']) ? sanitize_text_field($data['slug']) : '',
            'post_id'           => isset($data['post_id']) ? intval($data['post_id']) : 0,
            'media_id'          => isset($data['media_id']) ? intval($data['media_id']) : 0,
            'language'          => isset($data['language']) ? sanitize_text_field($data['language']) : 'en',
            'json_output'       => isset($data['json_output']) ? $data['json_output'] : '',
            'validation_result' => isset($data['validation_result']) ? $data['validation_result'] : '',
            'retry_attempts'    => isset($data['retry_attempts']) ? intval($data['retry_attempts']) : 0,
            'status'            => isset($data['status']) ? sanitize_text_field($data['status']) : 'pending',
            'error_trace'       => isset($data['error_trace']) ? $data['error_trace'] : '',
        ), array('%s','%s','%s','%s','%s','%d','%d','%s','%s','%s','%d','%s','%s'));

        return $wpdb->insert_id;
    }

    /**
     * Update log entry
     */
    public function update_log($id, $data) {
        global $wpdb;
        $table = $wpdb->prefix . DBA_LOG_TABLE;

        $update = array();
        $formats = array();

        foreach ($data as $key => $val) {
            $update[$key] = $val;
            $formats[] = is_int($val) ? '%d' : '%s';
        }

        $wpdb->update($table, $update, array('id' => $id), $formats, array('%d'));
    }

    /**
     * Get recent logs
     */
    public function get_logs($limit = 50, $offset = 0) {
        global $wpdb;
        $table = $wpdb->prefix . DBA_LOG_TABLE;
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$table} ORDER BY run_time DESC LIMIT %d OFFSET %d",
            $limit, $offset
        ), ARRAY_A);
    }

    /**
     * Get today's post count
     */
    public function get_today_count() {
        global $wpdb;
        $table = $wpdb->prefix . DBA_LOG_TABLE;
        return (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE run_date = %s AND status = 'published'",
            current_time('Y-m-d')
        ));
    }

    /**
     * Get slugs created today (for dedup)
     */
    public function get_today_slugs() {
        global $wpdb;
        $table = $wpdb->prefix . DBA_LOG_TABLE;
        $results = $wpdb->get_col($wpdb->prepare(
            "SELECT slug FROM {$table} WHERE run_date = %s AND status IN ('published','scheduled','draft')",
            current_time('Y-m-d')
        ));
        return $results ?: array();
    }

    /**
     * Get themes used today (for rotation)
     */
    public function get_today_themes() {
        global $wpdb;
        $table = $wpdb->prefix . DBA_LOG_TABLE;
        $results = $wpdb->get_col($wpdb->prepare(
            "SELECT DISTINCT theme FROM {$table} WHERE run_date = %s AND status IN ('published','scheduled','draft')",
            current_time('Y-m-d')
        ));
        return $results ?: array();
    }
}
