<?php
// File: includes/api/class-surftrust-public-controller.php
// Description: This file contains the corrected logic for fetching public notification data.

/**
 * Controller for handling all public-facing API requests.
 *
 * @package Surftrust
 * @subpackage Surftrust/includes/api
 */
class Surftrust_Public_Controller
{
    /**
     * Retrieves all active, published notifications and their corresponding live data.
     */
    public function get_notification_data(WP_REST_Request $request)
    {
        require_once(ABSPATH . 'wp-includes/load.php');
        // Safety Check: If WooCommerce isn't active, none of the data-driven notifications can work.
        if (!function_exists('wc_get_product')) {
           // error_log('SurfPop Warning: WooCommerce is not active. Some notification types may not function.');
        }

        $notification_data = [];
        $args = [
            'post_type'      => 'st_notification',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
        ];
        $query = new WP_Query($args);

        if (!$query->have_posts()) {
            return new WP_REST_Response([], 200);
        }

        $current_page_id = absint($request->get_param('current_page_id'));

        while ($query->have_posts()) {
            $query->the_post();
            $post_id = get_the_ID();
            $settings = get_post_meta($post_id, '_surftrust_settings', true);

            if (empty($settings) || empty($settings['type'])) {
                continue;
            }
            $type = $settings['type'];

            // Display Rules Logic
            $display_rules = null;
            foreach ($settings as $key => $value) {
                if (is_array($value) && isset($value['display_rules'])) {
                    $display_rules = $value['display_rules'];
                    break;
                }
            }
            if ($display_rules) {
                // Rule 1: "Hide On" always takes priority. If the current page is in the Hide list, skip this notification immediately.
                if (!empty($display_rules['hide_on'])) {
                    $hide_on_ids = wp_list_pluck($display_rules['hide_on'], 'id');
                    if (in_array($current_page_id, $hide_on_ids)) {
                        continue; // Skip this notification
                    }
                }

                // Rule 2: If "Show On" has pages, the current page MUST be one of them.
                // If the "Show On" list is empty, this rule is ignored, and the notification can show everywhere (except where hidden).
                if (!empty($display_rules['show_on'])) {
                    $show_on_ids = wp_list_pluck($display_rules['show_on'], 'id');
                    if (!in_array($current_page_id, $show_on_ids)) {
                        continue; // Skip this notification
                    }
                }
            }

            $data_to_add = null;
            switch ($type) {
                case 'sale':
                    $data_to_add = $this->get_single_recent_sale();
                    break;
            }

            if ($data_to_add) {
                $notification_data[] = ['id' => $post_id, 'type' => $type, 'settings' => $settings, 'data' => $data_to_add];
            }
        }
        wp_reset_postdata();

        return new WP_REST_Response($notification_data, 200);
    }

    private function get_single_recent_sale()
    {
        if (!function_exists('wc_get_orders')) return false;

        $args = array('limit' => 1, 'status' => 'completed', 'orderby' => 'date_created', 'order' => 'DESC');
        $orders = wc_get_orders($args);
        if (empty($orders)) return false;

        $order = reset($orders);
        $items = $order->get_items();
        if (empty($items)) return false;

        $first_item = reset($items);
        $product = $first_item->get_product();
        if (!$product) return false;

        return [
            'product_name'      => $product->get_name(),
            'product_id'        => $product->get_id(),
            'first_name'        => $order->get_billing_first_name(),
            'city'              => $order->get_billing_city(),
            'product_image_url' => wp_get_attachment_image_url($product->get_image_id(), 'thumbnail'),
            'product_url'       => $product->get_permalink(),
        ];
    }
}
