<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Qc\StoreQcRequest;
use App\Models\Qc;
use App\Models\Uom;
use App\Models\GatePass;
use App\Models\Warehouse;
use App\Services\QcService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class QcController extends Controller
{
    protected QcService $qcService;

    public function __construct(QcService $qcService)
    {
        $this->qcService = $qcService;
    }

    /**
     * Create QC inspection
     */
    public function store(StoreQcRequest $request): JsonResponse
    {
        try {
            $result = $this->qcService->createQcInspection($request->validated());

            return response()->json([
                'success' => true,
                'message' => 'QC inspection submitted successfully!',
                'data' => $result,
                'redirect' => route('qcs.create')
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to submit QC inspection: ' . $e->getMessage() . $e->getLine() . $e->getFile()
            ], 500);
        }
    }

    /**
     * Show QC inspection details
     */
    public function show(Qc $qc): JsonResponse
    {
        $qc->load([
            'qcItems.item',
            'qcItems.warehouse',
            'qcItems.bin',
            'qcItems.inspector',
            'qcItems.stockLedger',
            'igp.purchaseOrder.vendor',
            'inspector',
            'grns.grnItems'
        ]);

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

    /**
     * Search available IGPs for QC
     */
    public function searchIgps(Request $request): JsonResponse
    {
        // dd($request->all());
        try {
            $query = GatePass::query()
                ->where('type', 'inward')
                // ->whereIn('status', ['linked', 'partially_received']) // Only show IGPs that are not completed
                ->with(['purchaseOrder.vendor', 'purchaseOrder']);
                // ->whereHas('purchaseOrder', function($q) {
                    $query->where('status', '!=', 'closed'); // Don't show IGPs for completed POs
                // });
                // dd($query );
            if ($request->filled('q')) {
                $searchTerm = $request->q;
                $query->where(function($q) use ($searchTerm) {
                    $q->where('gate_pass_number', 'like', "%{$searchTerm}%");
                    // ->orWhereHas('purchaseOrder', function($po) use ($searchTerm) {
                    //     $po->where('po_number', 'like', "%{$searchTerm}%")
                    //        ->orWhereHas('contact', function($contact) use ($searchTerm) {
                    //            $contact->where('name', 'like', "%{$searchTerm}%");
                    //        });
                    // });
                });
            }

            $igps = $query->limit(10)->get();
            // dd($igps);
            $results = $igps->map(function($igp) {
                // dd($igp->purchaseOrder->contact);
                return [
                    'id' => $igp->id,
                    'text' => $igp->gate_pass_number . ' - ' . ($igp->purchaseOrder->po_number ?? 'N/A') . ' (' . ($igp->purchaseOrder->contact->name ?? 'Unknown Vendor') . ')',
                    'gate_pass_number' => $igp->gate_pass_number,
                    'po_number' => $igp->purchaseOrder->po_number ?? 'N/A',
                    'vendor_name' => $igp->purchaseOrder->vendor->name ?? 'Unknown Vendor',
                    'purchase_order_id' => $igp->purchase_order_id,
                    'date' => $igp->created_at->format('Y-m-d'),
                ];
            });

            return response()->json($results);

        } catch (\Exception $e) {
            Log::error('IGP search failed', [
                'error' => $e->getMessage(),
                'query' => $request->q ?? 'none'
            ]);

            return response()->json([], 500);
        }
    }

    /**
     * Search QC numbers
     */
    public function search(Request $request): JsonResponse
    {
        try {
            $search = $request->input('q', '');

            $qcs = Qc::where('qc_number', 'like', "%{$search}%")
                ->with(['igp.purchaseOrder.contact'])
                ->limit(20)
                ->get()
                ->map(function($qc) {
                    return [
                        'id' => $qc->id,
                        'text' => $qc->qc_number . ' - ' .
                                ($qc->igp ? $qc->igp->gate_pass_number : 'N/A') . ' - ' .
                                ($qc->igp && $qc->igp->purchaseOrder ? $qc->igp->purchaseOrder->po_number : 'N/A'),
                        'qc_number' => $qc->qc_number,
                        'igp_number' => $qc->igp ? $qc->igp->gate_pass_number : 'N/A',
                        'po_number' => $qc->igp && $qc->igp->purchaseOrder ? $qc->igp->purchaseOrder->po_number : 'N/A',
                        'vendor_name' => $qc->igp && $qc->igp->purchaseOrder && $qc->igp->purchaseOrder->contact ? $qc->igp->purchaseOrder->contact->name : 'N/A'
                    ];
                });

            return response()->json([
                'results' => $qcs
            ]);
        } catch (\Exception $e) {
            \Log::error('QC search failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return response()->json([
                'results' => []
            ]);
        }
    }

    /**
     * Get warehouse bins for selected warehouse
     */
    public function getWarehouseBins(Warehouse $warehouse): JsonResponse
    {
        $bins = $warehouse->bins()
            ->where('is_active', true)
            ->orderBy('code')
            ->get(['id', 'code', 'name', 'type']);

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

    /**
     * Get PO items for selected IGP
     */
    public function getIgpItems(GatePass $igp): JsonResponse
    {

        dd("dd");
        if ($igp->type !== 'inward' || !$igp->purchase_order_id) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid IGP or no PO linked'
            ], 400);
        }

        $po = $igp->purchaseOrder;
        $items = $po->items->map(function($item) {
            // Try to find UOM by code, fallback to item's UOM if not found
            $uom_id = Uom::where('code', $item->unit_code)->value('id');
            if (!$uom_id) {
                // Fallback: try to get UOM from the item itself
                $uom_id = $item->uom_id ?? null;
            }

            return [
                'item_id' => $item->item_id,
                'purchase_order_item_id' => $item->id,
                'item_name' => $item->item->name,
                'uom_id' => $item->item->uom->id,
                'unit_code' => $item->item->uom->unit_code,
                'uom_name' => $item->item->uom->name,
                'ordered_qty' => $item->quantity,
                'dn_qty' => $item->gatePassItem->dn_quantity,
                'igp_qty' => $item->quantity, // For now, assume IGP qty equals PO qty
                // 'accepted_qty' => 0,
                // 'rejected_qty' => 0,
                // 'status' => 'pending',
                'remarks' => ''
            ];
        });

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