<?php

namespace Modules\ProductCompat\Http\Controllers;

use Illuminate\Support\Facades\Schema;
use Nwidart\Menus\Facades\Menu;
use Modules\ProductCompat\Entities\Services\ProductCompatService;
use Modules\ProductCompat\Entities\Services\SearchQueueService;
use Modules\ProductCompat\Entities\Services\Settings;

class DataController
{
    /**
     * Inject the part-numbers + device-models tables into the product add/edit
     * forms (rendered via $pos_module_data). Gated to the create/edit screens
     * so it never appears on the product index list, and to users who may edit.
     *
     * @return array
     */
    public function get_product_screen_top_view()
    {
        $action = optional(request()->route())->getActionMethod();
        if (! in_array($action, ['create', 'edit'], true)) {
            return [];
        }
        if (! auth()->check() || ! auth()->user()->can('productcompat.edit')) {
            return [];
        }

        return [
            'view_path' => 'productcompat::product.form_fields',
            'view_data' => [],
        ];
    }

    /**
     * Persist the embedded compatibility tables when a product is saved
     * (fires for both create and update via the core after_product_saved hook).
     *
     * @param  array  $data  ['product' => Product, 'request' => Request]
     * @return void
     */
    public function after_product_saved($data)
    {
        $request = $data['request'] ?? null;
        $product = $data['product'] ?? null;
        if (! $request || ! $product) {
            return;
        }

        // AI search queue hook — create auto-enqueues, edit asks via checkbox.
        // Runs BEFORE the pc_* input guard below (a plain save carries no pc_*
        // rows) and must NEVER break a product save: everything in try/catch.
        try {
            if (Schema::hasTable('pc_search_queue') && auth()->check() && auth()->user()->can('productcompat.edit')) {
                $action = optional($request->route())->getActionMethod();

                if ($action === 'store' && Settings::bool('ai_auto_queue_on_create', true)) {
                    app(SearchQueueService::class)->enqueue(
                        (int) $product->business_id, (int) $product->id, 'new', 0, auth()->id()
                    );
                } elseif ($action === 'update' && $request->input('pc_queue_recheck') === '1') {
                    app(SearchQueueService::class)->enqueue(
                        (int) $product->business_id, (int) $product->id, 'edited', 5, auth()->id()
                    );
                }
            }
        } catch (\Throwable $e) {
            \Log::warning('[ProductCompat] enqueue failed: ' . $e->getMessage());
        }

        if (! $request->has('pc_part_numbers') && ! $request->has('pc_device_models') && ! $request->has('pc_compatible_products')) {
            return;
        }
        if (! auth()->check() || ! auth()->user()->can('productcompat.edit')) {
            return;
        }

        app(ProductCompatService::class)->saveManualData(
            (int) $product->business_id,
            (int) $product->id,
            (array) $request->input('pc_part_numbers', []),
            (array) $request->input('pc_device_models', []),
            (array) $request->input('pc_compatible_products', []),
            (int) auth()->id()
        );
    }

    /**
     * Add the ProductCompat entry to the admin sidebar.
     *
     * @return null
     */
    public function modifyAdminMenu()
    {
        if (auth()->user()->can('productcompat.view') || auth()->user()->can('productcompat.edit') || auth()->user()->can('productcompat.queue')) {
            Menu::modify('admin-sidebar-menu', function ($menu) {
                $menu->dropdown(
                    __('productcompat::lang.product_compatibility'),
                    function ($sub) {
                        $sub->url(route('productcompat.panel'), 'Control Panel');
                        $sub->url(route('productcompat.index'), __('productcompat::lang.editor'));
                        $sub->url(route('productcompat.review'), __('productcompat::lang.review_queue'));
                        if (auth()->user()->can('productcompat.queue')) {
                            $sub->url(route('productcompat.queue'), __('productcompat::lang.ai_search_queue'));
                            $sub->url(route('productcompat.batches'), __('productcompat::lang.offline_batches'));
                        }
                        $sub->url(route('productcompat.report'), __('productcompat::lang.change_report'));
                        $sub->url(route('productcompat.settings'), 'Settings');
                    },
                    88,
                    [
                        'icon'   => 'fa fas fa-microchip',
                        'active' => request()->segment(1) == 'product-compat',
                    ]
                );
            });
        }
    }

    /**
     * Module permissions surfaced in role management.
     *
     * @return array
     */
    public function user_permissions()
    {
        return [
            [
                'value'   => 'productcompat.view',
                'label'   => 'View product compatibility data',
                'default' => false,
            ],
            [
                'value'   => 'productcompat.edit',
                'label'   => 'Edit product part numbers & compatibility',
                'default' => false,
            ],
            [
                'value'   => 'productcompat.review',
                'label'   => 'Review / verify and clean up legacy custom fields',
                'default' => false,
            ],
            [
                'value'   => 'productcompat.queue',
                'label'   => 'View & manage the AI search queue',
                'default' => false,
            ],
        ];
    }
}
