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

/**
 * Inventory notifications based on recent product demand.
 */
function anbarak_get_inventory_notifications()
{
    $notifications = anbarak_get_option('inventory_notifications', []);
    return is_array($notifications) ? $notifications : [];
}

function anbarak_save_inventory_notifications($notifications)
{
    anbarak_update_option('inventory_notifications', array_values($notifications));
}

function anbarak_cleanup_inventory_notifications($notifications, $cutoff)
{
    return array_values(array_filter($notifications, function ($notification) use ($cutoff) {
        return !empty($notification['created']) && (int) $notification['created'] >= $cutoff;
    }));
}

function anbarak_update_inventory_notifications()
{
    $now = time();
    $cutoff = $now - (14 * DAY_IN_SECONDS);
    $notifications = anbarak_cleanup_inventory_notifications(anbarak_get_inventory_notifications(), $cutoff);

    if (!class_exists('WooCommerce') || '1' !== (string) anbarak_get_option('inventory_notifications_enabled', 1)) {
        anbarak_save_inventory_notifications($notifications);
        return;
    }

    $known_product_ids = [];

    foreach ($notifications as $notification) {
        if (!empty($notification['product_id'])) {
            $known_product_ids[(int) $notification['product_id']] = true;
        }
    }

    $sales = anbarak_get_sales($cutoff, $now);
    $demand = [];
    foreach ((array) $sales as $sale) {
        $order = !empty($sale['order_id']) ? wc_get_order((int) $sale['order_id']) : false;
        if (!$order) {
            continue;
        }

        foreach ($order->get_items() as $item) {
            $product = $item->get_product();
            if (!$product || !$product->managing_stock()) {
                continue;
            }

            $product_id = (int) $product->get_id();
            $quantity = (int) $item->get_quantity();
            if ($product_id && $quantity > 0) {
                $demand[$product_id] = isset($demand[$product_id]) ? $demand[$product_id] + $quantity : $quantity;
            }
        }
    }

    arsort($demand, SORT_NUMERIC);
    $created = 0;
    foreach ($demand as $product_id => $quantity) {
        if ($created >= 5 || isset($known_product_ids[$product_id])) {
            continue;
        }

        $product = wc_get_product($product_id);
        if (!$product || !$product->managing_stock()) {
            continue;
        }

        $stock = $product->get_stock_quantity();
        $low_stock_amount = (int) $product->get_low_stock_amount();
        $low_stock_amount = $low_stock_amount ?: (int) ANBARAK_PRODUCTS_LOW_STOCK_THRESHOLD;
        $out_of_stock = 'outofstock' === $product->get_stock_status() || (null !== $stock && $stock <= 0);
        $low_stock = !$out_of_stock && null !== $stock && $stock <= $low_stock_amount;
        if (!$out_of_stock && !$low_stock) {
            continue;
        }

        $notifications[] = [
            'product_id' => $product_id,
            'created'    => $now,
            'read'       => 0,
            'status'     => $out_of_stock ? 'out' : 'low',
        ];
        $known_product_ids[$product_id] = true;
        $created++;
    }

    anbarak_save_inventory_notifications($notifications);
}

function anbarak_get_unread_inventory_notifications()
{
    $notifications = anbarak_cleanup_inventory_notifications(
        anbarak_get_inventory_notifications(),
        time() - (14 * DAY_IN_SECONDS)
    );
    anbarak_save_inventory_notifications($notifications);
    return array_values(array_filter($notifications, function ($notification) {
        return empty($notification['read']);
    }));
}

function anbarak_mark_inventory_notification_read($product_id)
{
    $notifications = anbarak_get_inventory_notifications();
    foreach ($notifications as &$notification) {
        if ((int) ($notification['product_id'] ?? 0) === (int) $product_id) {
            $notification['read'] = 1;
        }
    }
    unset($notification);
    anbarak_save_inventory_notifications($notifications);
}

add_filter('cron_schedules', function ($schedules) {
    $schedules['anbarak_twice_daily'] = [
        'interval' => 12 * HOUR_IN_SECONDS,
        'display'  => __('Every 12 hours', 'anbarak'),
    ];
    return $schedules;
});

add_action('init', function () {
    if (!wp_next_scheduled('anbarak_inventory_notifications_cron')) {
        wp_schedule_event(time(), 'anbarak_twice_daily', 'anbarak_inventory_notifications_cron');
    }
});
add_action('anbarak_inventory_notifications_cron', 'anbarak_update_inventory_notifications');
register_deactivation_hook('anbarak/anbarak.php', function () {
    wp_clear_scheduled_hook('anbarak_inventory_notifications_cron');
});

add_action('wp_ajax_anbarak_mark_notification_read', function () {
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_app_access();
    $product_id = isset($_POST['product_id']) ? (int) sanitize_text_field(wp_unslash($_POST['product_id'])) : 0;
    if ($product_id > 0) {
        anbarak_mark_inventory_notification_read($product_id);
    }
    wp_send_json_success();
});
