<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Grn;
use App\Models\Qc;
use App\Models\GrnItem;
use App\Models\InventoryMove;
use App\Models\InventoryBalance;
use App\Services\WarehouseService;
use App\Services\NumberGenerationService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class GrnController extends Controller
{
    protected WarehouseService $warehouseService;
    protected NumberGenerationService $numberService;

    public function __construct(WarehouseService $warehouseService, NumberGenerationService $numberService)
    {
        $this->warehouseService = $warehouseService;
        $this->numberService = $numberService;
    }

    /**
     * Create GRN from QC
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'qc_id' => 'required|exists:qcs,id',
                'grn_number' => 'required|string|unique:good_received_notes,grn_number',
                'remarks' => 'nullable|string|max:1000',
                'items' => 'required|array|min:1',
                'items.*.item_id' => 'required|exists:items,id',
                'items.*.purchase_order_item_id' => 'required|exists:purchase_order_items,id',
                'items.*.uom_id' => 'required|exists:uoms,id',
                'items.*.unit_code' => 'required|string|max:50',
                'items.*.quantity_received' => 'required|numeric|min:0',
                'items.*.warehouse_id' => 'required|exists:warehouses,id',
                'items.*.bin_id' => 'required|exists:warehouse_bins,id',
            ]);

            $result = DB::transaction(function () use ($validated) {
                // Get QC details
                $qc = Qc::with(['igp.purchaseOrder'])->findOrFail($validated['qc_id']);

                // Create GRN
                $grn = Grn::create([
                    'grn_number' => $validated['grn_number'],
                    'purchase_order_id' => $qc->igp->purchase_order_id,
                    'qc_id' => $qc->id,
                    'status' => 'accepted',
                    'received_by' => Auth::id(),
                    'received_at' => now(),
                    'remarks' => $validated['remarks'],
                ]);

                // Create GRN items and update stock
                foreach ($validated['items'] as $itemData) {
                    // Create GRN item
                    $grnItem = GrnItem::create([
                        'grn_id' => $grn->id,
                        'item_id' => $itemData['item_id'],
                        'purchase_order_item_id' => $itemData['purchase_order_item_id'],
                        'uom_id' => $itemData['uom_id'],
                        'unit_code' => $itemData['unit_code'],
                        'quantity_received' => $itemData['quantity_received'],
                        'warehouse_id' => $itemData['warehouse_id'],
                        'bin_id' => $itemData['bin_id'],
                    ]);

                    // Update warehouse stock
                    $this->warehouseService->addStock(
                        $itemData['item_id'],
                        $itemData['warehouse_id'],
                        $itemData['bin_id'],
                        $itemData['quantity_received'],
                        $itemData['uom_id'],
                        'grn',
                        $grn->id,
                        'QC Accepted - ' . $grn->grn_number
                    );
                }

                // Update QC status if all items are processed
                $this->updateQcStatus($qc);

                return $grn->load(['grnItems.item', 'grnItems.warehouse', 'grnItems.bin']);
            });

            return response()->json([
                'success' => true,
                'message' => 'GRN created successfully!',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create GRN: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Show GRN details
     */
    public function show(Grn $grn): JsonResponse
    {
        $grn->load([
            'grnItems.item',
            'grnItems.warehouse',
            'grnItems.bin',
            'qc.igp.purchaseOrder.vendor',
            'purchaseOrder.vendor'
        ]);

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

    /**
     * Update QC status after GRN creation
     */
    protected function updateQcStatus(Qc $qc): void
    {
        // Check if all QC items have been processed through GRN
        $totalQcItems = $qc->qcItems()->where('accepted_qty', '>', 0)->count();
        $processedItems = $qc->grns()->withCount('grnItems')->get()->sum('grn_items_count');

        if ($processedItems >= $totalQcItems) {
            $qc->update(['status' => 'completed']);
        }
    }
}
