<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ScannerController extends Controller
{
    /**
     * Display scanner interface
     */
    public function index()
    {
        // Fetch all unique product names for the datalist suggestion
        $productNames = Product::query()
            ->whereNotNull('product_name')
            ->distinct()
            ->orderBy('product_name')
            ->pluck('product_name');

        // Fetch all unique colors from the products table.
        // The 'color' column can be a JSON array or a simple string.
        $productColors = Product::query()
            ->whereNotNull('color')
            ->pluck('color')
            ->flatten() // Handles both single string and array of strings
            ->unique()
            ->filter() // Removes any null or empty values
            ->sort()->values();

        return view('admin.scanner.index', compact('productNames', 'productColors'));
    }

    /**
     * Get available colors for a given product name.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getColorsForProduct(Request $request)
    {
        $request->validate([
            'product_name' => 'required|string',
        ]);

        $colors = Product::where('product_name', $request->product_name)
                         ->whereNotNull('color')
                         ->distinct()
                         ->pluck('color');

        return response()->json($colors);
    }

    /**
     * Handle scan data from barcode/IMEI scanner
     */
    public function scan(Request $request)
    {
        $request->validate([
            'scan_data' => 'required|string|max:255',
            'scanner_type' => 'sometimes|in:barcode,imei,serial'
        ]);

        try {
            $rawScanData = $request->scan_data;
            $scannerType = $request->scanner_type ?? 'auto';
            $scannedBy = auth()->check() ? auth()->user()->name : 'Web Scanner';

            // Clean the scanned data to extract the core identifier (e.g., from a URL)
            $scanData = $rawScanData;
            try {
                $url = new \URL($rawScanData); // Using a generic URL parser
                $extracted = $url->searchParams->get('serial') ?? $url->searchParams->get('serial_no') ?? $url->searchParams->get('code') ?? $url->searchParams->get('id');
                if ($extracted) {
                    $scanData = $extracted;
                }
            } catch (\Exception $e) {
                // Not a valid URL, proceed with the raw data
            }
            $scanData = trim($scanData);

            Log::info('Scan received', [
                'data' => $rawScanData,
                'type' => $scannerType,
                'by' => $scannedBy
            ]);

            // First, check if a product with this serial/IMEI already exists and has been fully created (not just a placeholder)
            $existingProduct = Product::where(function($query) use ($scanData) {
                $query->where('serial_no', $scanData)
                    ->orWhere('imei', $scanData)
                    ->orWhere('barcode', $scanData);
            })->first(); // Check if any record exists

            if ($existingProduct) {
                // Product already exists, return an 'exists' action with the product data.
                return response()->json([
                    'success' => true, // The check was successful, even if the product exists.
                    'action'  => 'exists',
                    'message' => 'This product already exists in the database.',
                    'product' => $existingProduct,
                ]);
            } else {
                // Return a new, unsaved Product instance with pre-filled data
                $product = new Product();
                $product->fillFromScan($scanData);
                $action = 'new';
                $message = 'New product detected.';
            }
            // If it's an AJAX request, return JSON
            if ($request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => $message,
                    'product' => $product,
                    'action'  => $action
                ]);
            }

            // If it's a form submission, return view
            return view('scanner.scan', compact('product'));

        } catch (\Exception $e) {
            Log::error('Scan error: ' . $e->getMessage());

            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error processing scan: ' . $e->getMessage()
                ], 500);
            }

            return redirect()->route('scanner.index')
                ->with('error', 'Error processing scan: ' . $e->getMessage());
        }
    }

    /**
     * Display bulk scan interface
     */
    public function bulkScanPage()
    {
        return view('scanner.bulk-scan'); // resources/views/scanner/bulk-scan.blade.php
    }

    /**
     * Bulk scan endpoint for multiple products
     */
    public function bulkScan(Request $request)
    {
        $request->validate([
            'scans' => 'required|array',
            'scans.*.data' => 'required|string|max:255',
            'scans.*.type' => 'sometimes|in:barcode,imei,serial'
        ]);

        $results = [];
        $scannedBy = auth()->check() ? auth()->user()->name : 'Bulk Scanner';

        foreach ($request->scans as $scan) {
            try {
                $product = Product::createFromScan($scan['data'], $scannedBy);
                $results[] = [
                    'success' => true,
                    'data' => $scan['data'],
                    'product_id' => $product->id,
                    'action' => $product->wasRecentlyCreated ? 'created' : 'updated'
                ];
            } catch (\Exception $e) {
                $results[] = [
                    'success' => false,
                    'data' => $scan['data'],
                    'error' => $e->getMessage()
                ];
            }
        }

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Bulk scan completed',
                'results' => $results,
                'total' => count($results),
                'successful' => count(array_filter($results, function($r) { return $r['success']; }))
            ]);
        }

        return view('scanner.bulk-scan-results', compact('results'));
    }

    /**
     * Display recently scanned products page
     */
    public function recentScansPage()
    {
        $recentProducts = Product::recentlyScanned(24) // Last 24 hours
                                ->orderBy('scanned_at', 'desc')
                                ->paginate(20);

        return view('scanner.recent-scans', compact('recentProducts')); // resources/views/scanner/recent-scans.blade.php
    }

    /**
     * Get recently scanned products (API endpoint)
     */
    public function recentScans()
    {
        $recentProducts = Product::recentlyScanned(24)
                                ->orderBy('scanned_at', 'desc')
                                ->limit(50)
                                ->get();

        return response()->json([
            'success' => true,
            'products' => $recentProducts
        ]);
    }

    /**
     * Simulate hardware scanner input (for testing)
     */
    public function simulateScan(Request $request)
    {
        $request->validate([
            'imei' => 'sometimes|string|size:15',
            'serial' => 'sometimes|string|max:255',
            'barcode' => 'sometimes|string|max:255'
        ]);

        $scanData = $request->imei ?? $request->serial ?? $request->barcode;

        if (!$scanData) {
            return response()->json([
                'success' => false,
                'message' => 'No scan data provided'
            ], 400);
        }

        // Process the scan
        return $this->scan(new Request([
            'scan_data' => $scanData,
            'scanner_type' => $request->imei ? 'imei' : ($request->serial ? 'serial' : 'barcode')
        ]));
    }

    /**
     * Scanner settings/configuration page
     */
    public function settings()
    {
        return view('scanner.settings'); // resources/views/scanner/settings.blade.php
    }

    /**
     * Search for products by serial or IMEI for autocomplete.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function search(Request $request)
    {
        $request->validate(['term' => 'required|string|min:2']);

        $term = $request->term;

        $products = Product::where('serial_no', 'LIKE', "%{$term}%")
                            ->orWhere('imei', 'LIKE', "%{$term}%")
                            ->select('id', 'serial_no', 'imei', 'product_name')
                            ->limit(10)
                            ->get();

        return response()->json($products);
    }
}
