<?php

namespace Modules\ProductCompat\Http\Controllers;

use App\Product;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\ProductCompat\Entities\PcPartNumber;
use Modules\ProductCompat\Entities\PcDeviceCompat;
use Modules\ProductCompat\Entities\PcCompatible;
use Modules\ProductCompat\Entities\PcProductStatus;
use Modules\ProductCompat\Entities\Services\ProductCompatService;
use Modules\ProductCompat\Entities\Services\EnrichmentManager;

class ProductCompatController extends Controller
{
    protected ProductCompatService $service;

    public function __construct(ProductCompatService $service)
    {
        $this->service = $service;
    }

    /**
     * Search screen.
     */
    public function index()
    {
        if (! auth()->user()->can('productcompat.edit')) {
            abort(403, 'Unauthorized action.');
        }

        return view('productcompat::editor.index');
    }

    /**
     * Structured editor for a single product (looked up by SKU).
     */
    public function edit(Request $request)
    {
        if (! auth()->user()->can('productcompat.edit')) {
            abort(403, 'Unauthorized action.');
        }

        $business_id = $request->session()->get('user.business_id');
        $sku = $request->input('product_sku');

        $product = Product::where('business_id', $business_id)
            ->where('sku', 'like', '%' . $sku . '%')
            ->first();

        if (! $product) {
            return redirect()->action('\Modules\ProductCompat\Http\Controllers\ProductCompatController@index')
                ->with('status', ['success' => 0, 'msg' => 'Product not found for SKU: ' . $sku]);
        }

        $partNumbers = PcPartNumber::where('product_id', $product->id)->orderByDesc('is_primary')->get();
        $deviceModels = PcDeviceCompat::with('deviceModel')->where('product_id', $product->id)->get();
        $compatibles = PcCompatible::with('compatibleProduct')->where('product_id', $product->id)->get();
        $status = PcProductStatus::where('product_id', $product->id)->first();

        // Legacy custom fields for reference during transition.
        $customFields = [];
        for ($i = 1; $i <= 20; $i++) {
            $col = 'product_custom_field' . $i;
            if (! empty($product->{$col})) {
                $customFields[$col] = $product->{$col};
            }
        }

        return view('productcompat::editor.edit', compact(
            'product', 'partNumbers', 'deviceModels', 'compatibles', 'status', 'customFields'
        ));
    }

    /**
     * Persist the manually-curated data. The editor is the source of truth:
     * rows not present in the form are removed; present rows are upserted as
     * verified manual data.
     */
    public function store(Request $request)
    {
        if (! auth()->user()->can('productcompat.edit')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate([
            'product_id'      => 'required|exists:products,id',
            'part_numbers'    => 'nullable|array',
            'device_models'   => 'nullable|array',
            'compatible_products' => 'nullable|array',
        ]);

        $product = Product::findOrFail($request->input('product_id'));

        $this->service->saveManualData(
            (int) $product->business_id,
            (int) $product->id,
            (array) $request->input('part_numbers', []),
            (array) $request->input('device_models', []),
            (array) $request->input('compatible_products', []),
            (int) auth()->id()
        );

        return redirect()->back()->with('status', ['success' => 1, 'msg' => __('productcompat::lang.saved')]);
    }

    /**
     * On-demand enrichment for a single product (the "Enrich now" button).
     */
    public function enrich(Request $request, EnrichmentManager $manager)
    {
        if (! auth()->user()->can('productcompat.edit')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate(['product_id' => 'required|exists:products,id']);
        $product = Product::findOrFail($request->input('product_id'));

        $r = $manager->enrichProduct($product);

        if ($r['status'] === 'success') {
            $msg = "Enriched via {$r['provider']}: +{$r['parts']} part number(s), +{$r['devices']} device model(s) — flagged for review.";
        } elseif ($r['status'] === 'no_provider') {
            $msg = 'No enrichment provider is configured. Add a paid API key or brand/trusted URL templates in config/productcompat.php.';
        } else {
            $msg = 'Enrichment ran but found nothing to add (' . $r['status'] . ').';
        }

        return redirect()->back()->with('status', ['success' => $r['status'] === 'success' ? 1 : 0, 'msg' => $msg]);
    }
}
