<?php
if (!defined('ABSPATH')) exit;

/**
 * Pinery Flow — Cron Scheduler & Run Logging
 */
class Pinery_Flow_Cron {

    public static function init() {
        add_action('pinery_flow_daily_run', [__CLASS__, 'execute']);
    }

    public static function execute() {
        if (!get_option('pinery_flow_auto_enabled', 0)) return;

        $api_key = Pinery_Flow_Pipeline::get_api_key();
        if (empty($api_key)) {
            self::log(0, 'error: no API key');
            return;
        }

        $result = Pinery_Flow_Pipeline::run();
        $count  = is_wp_error($result) ? 0 : count($result);
        $status = is_wp_error($result) ? 'error: ' . $result->get_error_message() : 'ok';

        self::log($count, $status);
    }

    public static function log($count, $status) {
        $logs = get_option('pinery_flow_run_logs', []);
        $logs[] = [
            'time'   => current_time('mysql'),
            'count'  => $count,
            'status' => $status,
        ];
        // Keep last 10 entries
        if (count($logs) > 10) $logs = array_slice($logs, -10);
        update_option('pinery_flow_run_logs', $logs);
    }

    public static function maybe_create_log_table() {
        // Using options for simplicity — no custom table needed
        add_option('pinery_flow_run_logs', []);
        add_option('pinery_flow_detail_logs', []);
        add_option('pinery_flow_published_products', []);
    }
}
