<?php

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

class ShopCentral_Notification_System
{
    private $namespace;

    public function __construct($namespace = 'shopcentral/v1')
    {
        $this->namespace = $namespace;
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes()
    {
        register_rest_route($this->namespace, '/api/store-manager/notifications', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_notifications'],
            'permission_callback' => [$this, 'check_permission'],
        ]);
        
        register_rest_route($this->namespace, '/api/store-manager/notifications/mark-read', [
            'methods' => WP_REST_Server::CREATABLE,
            'callback' => [$this, 'mark_read'],
            'permission_callback' => [$this, 'check_permission'],
        ]);
    }

    public function check_permission()
    {
        return current_user_can('manage_options');
    }

    public function get_notifications($request)
    {
        $force = $request->get_param('force');
        $transient_key = 'shopcentral_active_notifications';
        
        $notifications = get_transient($transient_key);
        
        if ($force || $notifications === false) {
            $notifications = $this->generate_notifications();
            set_transient($transient_key, $notifications, 5 * MINUTE_IN_SECONDS); // Cache for 5 mins
        }

        // Return only unread ones by default, or all if we implement mark as read differently
        // We'll manage read status in a separate option
        $read_ids = get_option('shopcentral_read_notifications', []);
        
        $unread = array_filter($notifications, function($n) use ($read_ids) {
            return !in_array($n['id'], $read_ids);
        });

        return new WP_REST_Response([
            'status' => 'success',
            'notifications' => array_values($unread)
        ], 200);
    }

    public function mark_read($request)
    {
        $params = $request->get_json_params();
        if (isset($params['id'])) {
            $read_ids = get_option('shopcentral_read_notifications', []);
            $read_ids[] = $params['id'];
            update_option('shopcentral_read_notifications', array_unique($read_ids));
        } else if (isset($params['all']) && $params['all'] === true) {
            $transient_key = 'shopcentral_active_notifications';
            $notifications = get_transient($transient_key);
            if ($notifications) {
                $read_ids = get_option('shopcentral_read_notifications', []);
                foreach($notifications as $n) {
                    $read_ids[] = $n['id'];
                }
                update_option('shopcentral_read_notifications', array_unique($read_ids));
            }
        }
        
        return new WP_REST_Response(['status' => 'success'], 200);
    }

    private function generate_notifications()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'shopcentral_stores';
        $stores = $wpdb->get_results("SELECT * FROM $table");
        $store_api = new ShopCentral_Store_API($this->namespace);

        $notifications = [];
        $after_date = date('Y-m-d\TH:i:s\Z', strtotime('-24 hours')); // Check last 24h

        foreach ($stores as $store) {
            $store_is_down = false;
            
            if (!$store_api->is_store_local($store)) {
                // Health Check
                try {
                    $status_res = $store_api->get_remote_wc_data($store, 'wc/v3/system_status');
                    // Check if it's an error object or empty
                    if (!$status_res || (is_object($status_res) && isset($status_res->code)) || (is_array($status_res) && isset($status_res['code']))) {
                        $store_is_down = true;
                    }
                } catch (Exception $e) {
                    $store_is_down = true;
                }
            }

            if ($store_is_down) {
                $notifications[] = [
                    'id' => 'down_' . $store->id . '_' . date('YmdH'),
                    'store' => $store->name,
                    'type' => 'error',
                    'title' => 'Store Down Alert',
                    'message' => "The store {$store->name} could not be reached or REST API is down.",
                    'time' => current_time('mysql')
                ];
                continue; // Skip further checks if down
            }

            // Low Stock
            if ($store_api->is_store_local($store)) {
                $low_stock = count(wc_get_products(['stock_status' => 'lowstock', 'limit' => -1]));
                if ($low_stock == 0) {
                     // Sometimes lowstock status isn't used, check manually based on threshold
                     $low_stock = count(wc_get_products([
                         'limit' => -1,
                         'manage_stock' => true,
                         'stock_quantity' => '<= 5' // rough threshold
                     ]));
                }
            } else {
                // Remote WC REST API does not support stock_status=lowstock filter in v3
                $low_stock = 0;
            }

            if ($low_stock > 0) {
                $notifications[] = [
                    'id' => 'stock_' . $store->id . '_' . date('YmdH'),
                    'store' => $store->name,
                    'type' => 'warning',
                    'title' => 'Low Stock Alert',
                    'message' => "{$store->name} has products running low on stock.",
                    'time' => current_time('mysql')
                ];
            }

            // New Orders & Refunds
            if ($store_api->is_store_local($store)) {
                $recent_orders = wc_get_orders([
                    'date_created' => '>=' . strtotime('-24 hours'),
                    'limit' => -1
                ]);
            } else {
                $recent_orders = $store_api->get_remote_wc_data($store, 'wc/v3/orders', ['after' => $after_date]);
            }

            if (is_array($recent_orders) && !isset($recent_orders['code'])) {
                $new_orders = 0;
                $refunds = 0;

                foreach ($recent_orders as $order) {
                    if (is_object($order)) {
                        $status = method_exists($order, 'get_status') ? $order->get_status() : ($order->status ?? '');
                    } else {
                        $status = $order['status'] ?? '';
                    }

                    if (in_array($status, ['processing', 'completed', 'pending'])) {
                        $new_orders++;
                    } elseif ($status === 'refunded') {
                        $refunds++;
                    }
                }

                if ($new_orders > 0) {
                    $notifications[] = [
                        'id' => 'orders_' . $store->id . '_' . date('YmdH'),
                        'store' => $store->name,
                        'type' => 'info',
                        'title' => 'New Orders',
                        'message' => "{$store->name} received {$new_orders} new order(s) in the last 24h.",
                        'time' => current_time('mysql')
                    ];
                }

                if ($refunds > 0) {
                    $notifications[] = [
                        'id' => 'refunds_' . $store->id . '_' . date('YmdH'),
                        'store' => $store->name,
                        'type' => 'error',
                        'title' => 'Refund Alert',
                        'message' => "{$store->name} processed {$refunds} refund(s) in the last 24h.",
                        'time' => current_time('mysql')
                    ];
                }
            }
        }

        return $notifications;
    }
}
