<?php

defined('ABSPATH') || exit;

class ShopCentral_Logger
{
    private static $instance = null;

    const LEVEL_INFO    = 'info';
    const LEVEL_SUCCESS = 'success';
    const LEVEL_WARNING = 'warning';
    const LEVEL_ERROR   = 'error';

    const FEATURE_ORDER_SYNC    = 'order_sync';
    const FEATURE_PRODUCT_SYNC  = 'product_sync';
    const FEATURE_CUSTOMER_SYNC = 'customer_sync';
    const FEATURE_INVENTORY     = 'inventory';
    const FEATURE_CONNECTION    = 'connection';
    const FEATURE_IMPORT        = 'import';
    const FEATURE_EXPORT        = 'export';
    const FEATURE_GENERAL       = 'general';

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

    public static function log($feature, $message, $level = self::LEVEL_INFO, $context = null, $store_id = null)
    {
        global $wpdb;
        $logs_table = $wpdb->prefix . 'shopcentral_logs';

        if (is_array($context) || is_object($context)) {
            $context = wp_json_encode($context);
        }

        return $wpdb->insert(
            $logs_table,
            [
                'feature'    => substr(sanitize_text_field($feature), 0, 100),
                'level'      => substr(sanitize_text_field($level), 0, 20),
                'message'    => wp_kses_post($message),
                'context'    => $context ? wp_kses_post($context) : null,
                'store_id'   => $store_id ? intval($store_id) : null,
                'created_at' => current_time('mysql'),
            ],
            ['%s', '%s', '%s', '%s', '%d', '%s']
        );
    }

    public static function info($feature, $message, $context = null, $store_id = null)
    {
        return self::log($feature, $message, self::LEVEL_INFO, $context, $store_id);
    }

    public static function success($feature, $message, $context = null, $store_id = null)
    {
        return self::log($feature, $message, self::LEVEL_SUCCESS, $context, $store_id);
    }

    public static function warning($feature, $message, $context = null, $store_id = null)
    {
        return self::log($feature, $message, self::LEVEL_WARNING, $context, $store_id);
    }

    public static function error($feature, $message, $context = null, $store_id = null)
    {
        return self::log($feature, $message, self::LEVEL_ERROR, $context, $store_id);
    }

    public static function get_logs($args = [])
    {
        global $wpdb;
        $table = $wpdb->prefix . 'shopcentral_logs';

        $defaults = [
            'feature'   => '',
            'level'     => '',
            'store_id'  => null,
            'after'     => '',
            'before'    => '',
            'search'    => '',
            'per_page'  => 50,
            'page'      => 1,
            'orderby'   => 'created_at',
            'order'     => 'DESC',
        ];

        $args = wp_parse_args($args, $defaults);

        $where = 'WHERE 1=1';
        $prepare_args = [];

        if (!empty($args['feature'])) {
            $where .= ' AND feature = %s';
            $prepare_args[] = $args['feature'];
        }

        if (!empty($args['level'])) {
            $where .= ' AND level = %s';
            $prepare_args[] = $args['level'];
        }

        if ($args['store_id'] !== null && $args['store_id'] !== '') {
            $where .= ' AND store_id = %d';
            $prepare_args[] = intval($args['store_id']);
        }

        if (!empty($args['after'])) {
            $where .= ' AND created_at >= %s';
            $prepare_args[] = $args['after'];
        }

        if (!empty($args['before'])) {
            $where .= ' AND created_at <= %s';
            $prepare_args[] = $args['before'];
        }

        if (!empty($args['search'])) {
            $where .= ' AND (message LIKE %s OR context LIKE %s)';
            $search = '%' . $wpdb->esc_like($args['search']) . '%';
            $prepare_args[] = $search;
            $prepare_args[] = $search;
        }

        $allowed_orderby = ['id', 'created_at', 'feature', 'level'];
        $orderby = in_array($args['orderby'], $allowed_orderby) ? $args['orderby'] : 'created_at';
        $order = strtoupper($args['order']) === 'ASC' ? 'ASC' : 'DESC';

        $offset = (intval($args['page']) - 1) * intval($args['per_page']);
        $per_page = intval($args['per_page']);

        $total = $wpdb->get_var(
            empty($prepare_args)
                ? "SELECT COUNT(*) FROM $table $where"
                : $wpdb->prepare("SELECT COUNT(*) FROM $table $where", $prepare_args)
        );

        $query = "SELECT * FROM $table $where ORDER BY $orderby $order LIMIT %d OFFSET %d";
        $prepare_args[] = $per_page;
        $prepare_args[] = $offset;

        $results = $wpdb->get_results(
            $wpdb->prepare($query, $prepare_args)
        );

        return [
            'data'  => $results,
            'total' => intval($total),
            'pages' => ceil(intval($total) / $per_page),
        ];
    }

    public static function delete_log($id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'shopcentral_logs';
        return $wpdb->delete($table, ['id' => intval($id)], ['%d']);
    }

    public static function bulk_delete($ids)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'shopcentral_logs';

        if (empty($ids)) {
            return 0;
        }

        $ids = array_map('intval', $ids);
        $placeholders = implode(',', array_fill(0, count($ids), '%d'));

        return $wpdb->query(
            $wpdb->prepare("DELETE FROM $table WHERE id IN ($placeholders)", $ids)
        );
    }

    public static function clear_all()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'shopcentral_logs';
        return $wpdb->query("TRUNCATE TABLE $table");
    }

    public static function delete_old_logs($days = 30)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'shopcentral_logs';
        $cutoff = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        return $wpdb->query(
            $wpdb->prepare("DELETE FROM $table WHERE created_at < %s", $cutoff)
        );
    }

    public static function get_features()
    {
        return [
            self::FEATURE_ORDER_SYNC    => __('Order Sync', 'shopcentral'),
            self::FEATURE_PRODUCT_SYNC  => __('Product Sync', 'shopcentral'),
            self::FEATURE_CUSTOMER_SYNC => __('Customer Sync', 'shopcentral'),
            self::FEATURE_INVENTORY     => __('Inventory', 'shopcentral'),
            self::FEATURE_CONNECTION    => __('Connection', 'shopcentral'),
            self::FEATURE_IMPORT        => __('Import', 'shopcentral'),
            self::FEATURE_EXPORT        => __('Export', 'shopcentral'),
            self::FEATURE_GENERAL       => __('General', 'shopcentral'),
        ];
    }

    public static function get_levels()
    {
        return [
            self::LEVEL_INFO    => __('Info', 'shopcentral'),
            self::LEVEL_SUCCESS => __('Success', 'shopcentral'),
            self::LEVEL_WARNING => __('Warning', 'shopcentral'),
            self::LEVEL_ERROR   => __('Error', 'shopcentral'),
        ];
    }
}
