<?php

namespace App\Http\Controllers;

use App\Models\GoodsReceiving;
use App\Http\Requests\GoodsReceivingRequest;
use App\Models\GoodsReceivingItem;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Services\GoodsReceivingService;
use App\Services\CompanyService;
use App\Services\InvoiceService;
use App\Services\BatchService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class GoodsReceivingController extends Controller
{
    protected $goodsReceivingService;
    protected $invoiceService;
    protected $companyService;
    protected $batchService;

    public function __construct(GoodsReceivingService $goodsReceivingService, InvoiceService $invoiceService, CompanyService $companyService, BatchService $batchService)
    {
        $this->goodsReceivingService = $goodsReceivingService;
        $this->invoiceService = $invoiceService;
        $this->companyService = $companyService;
        $this->batchService = $batchService;
    }

    public function index()
    {
        if (!auth()->user()->hasPermission('Goods Receiving List')) {
            abort(403, 'Unauthorized action.');
        }
        $goodsReceivings = $this->goodsReceivingService->getAllGoodsReceivings();
        return view('admin.goods-receivings.index', compact('goodsReceivings'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        if (!auth()->user()->hasPermission('Goods Receiving Create')) {
            abort(403, 'Unauthorized action.');
        }
        if (auth()->user()->hasRole('Superadmin')) {
            $newGoodsReceivingCode = "GRN";
        } else {
            $newGoodsReceivingCode = $this->goodsReceivingService->createGoodsReceivingCode(auth()->user()->employee->company_id);
        }
        $invoices = $this->invoiceService->getAllInvoices('purchase')
            ?->filter(fn($invoice) => strtolower($invoice->status) !== 'completed');

        $companies = $this->companyService->getAllCompanies();
        $batches = $this->batchService->getAllBatches();
        $defaultCompanyId = null;
        // if (isset(Auth::user()->employee->company_id) && !is_null(Auth::user()->employee->company_id)) {
        //     $defaultCompanyId = Auth::user()->employee->company_id;
        // } else {
        $defaultCompany = $companies->where('name', 'Benson Pharmaceuticals')->first();
        $defaultCompanyId = $defaultCompany->id;
        // dd($defaultCompanyId);
        // }
        return view('admin.goods-receivings.create', compact('invoices', 'batches', 'companies', 'newGoodsReceivingCode', 'defaultCompanyId'));
    }

    public function fetchPoItems(Request $request)
    {
        $invoice = Invoice::find($request->id); //with('items.productVariation', 'items.rawMaterialItem', 'party')->where('id', $invoiceId)->first();
        // dd($request->all(), $invoice->items->toArray());

        if (!$invoice) {
            return response()->json(['error' => 'Invoice not found'], 404);
        }

        $items = [];
        foreach ($invoice->items as $item) {
            $items[] = [
                'id' => $item->id,
                'name' => $item->rawMaterialItem?->name ?? ''
            ];
        }

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

    public function itemsDetailView(Request $request)
    {
        // dd($request->all());
        if ($request->filled('isEdit')) {
            $grnItem = GoodsReceivingItem::find($request->id);
            // dd($grnItem);
            if (!$grnItem) {
                return response()->json(['error' => 'GRN Item not found'], 404);
            }
            $data = [
                'grnItem' => $grnItem,
                'isEdit' => true
            ];
        } else {
            $item = InvoiceItem::find($request->id);
            if (!$item) {
                return response()->json(['error' => 'Item not found'], 404);
            }
            $data = [
                'item' => $item
            ];
        }
        $view = view('admin.goods-receivings.item-details', $data)->render();

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(GoodsReceivingRequest $request)
    {
        
        if (!auth()->user()->hasPermission('Goods Receiving Create')) {
            abort(403, 'Unauthorized action.');
        }
        $goodsReceiving = $this->goodsReceivingService->createGoodsReceiving($request->validated());
        // dd($goodsReceiving);
        return redirect()->route('goods-receivings.show', $goodsReceiving->id)->with('success', 'Goods Receiving Note created successfully!');
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        if (!auth()->user()->hasPermission('Goods Receiving View')) {
            abort(403, 'Unauthorized action.');
        }
        $goodsReceiving = $this->goodsReceivingService->getGoodsReceivingById($id);

        // Get previous and next GRNs for navigation
        $previous = GoodsReceiving::where('id', '<', $goodsReceiving->id)
            ->orderBy('id', 'desc')
            ->first();

        $next = GoodsReceiving::where('id', '>', $goodsReceiving->id)
            ->orderBy('id', 'asc')
            ->first();

        // Get all GRNs for the dropdown (ordered by creation date, newest first)
        $allGRNs = GoodsReceiving::orderBy('created_at', 'desc')
            ->select('id', 'code', 'created_at')
            ->get();

        return view('admin.goods-receivings.show', compact('goodsReceiving', 'previous', 'next', 'allGRNs'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        if (!auth()->user()->hasPermission('Goods Receiving Update')) {
            abort(403, 'Unauthorized action.');
        }
        $goodsReceiving = $this->goodsReceivingService->getGoodsReceivingById($id);
        $invoices = $this->invoiceService->getInvoiceById($goodsReceiving->invoice_id);
        $companies = $this->companyService->getAllCompanies();
        $batches = $this->batchService->getAllBatches();
        return view('admin.goods-receivings.edit', compact('goodsReceiving', 'invoices', 'companies', 'batches'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(GoodsReceivingRequest $request, GoodsReceiving $goodsReceiving)
    {
        // dd($request->all(), $goodsReceiving);
        if (!auth()->user()->hasPermission('Goods Receiving Update')) {
            abort(403, 'Unauthorized action.');
        }
        $goodsReceiving = $this->goodsReceivingService->updateGoodsReceiving($goodsReceiving, $request);
        return redirect()->route('goods-receivings.show', $goodsReceiving->id)->with('success', 'Goods Receiving Note updated successfully!');
    }

    public function destroy(GoodsReceiving $goodsReceiving)
    {
        if (!auth()->user()->hasPermission('Goods Receiving Delete')) {
            abort(403, 'Unauthorized action.');
        }
        $goodsReceiving = $this->goodsReceivingService->deleteGoodsReceiving($goodsReceiving);
        return redirect()->route('goods-receivings.index')->with('success', 'Goods Receiving deleted successfully');
    }

    public function getGoodReceivingsByInvoice($invoiceId)
    {
        $goodsReceivings = GoodsReceiving::where('invoice_id', $invoiceId)->orderBy('supplier_bill_no', 'asc')->get();
        return response()->json(['goodsReceivings' => $goodsReceivings]);
    }

    public function createCodeByCompany($companyId)
    {
        $goods_receiving_code = $this->goodsReceivingService->createGoodsReceivingCode($companyId);
        return response()->json(['goods_receiving_code' => $goods_receiving_code]);
    }
}
