<?php

namespace App\Http\Controllers\Manager;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Grn;
use App\Models\GrnProductDetail;
use App\Models\CustomerVendor;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ManagerGRNController extends Controller
{
    // Show create GRN form
    public function grnPage()
    {
        $lastGRN = Grn::orderBy('id', 'desc')->first();
        $nextNumber = $lastGRN ? ((int)explode('/', $lastGRN->grn_no)[2]) + 1 : 1;
        $grnNo = 'UEPL/GRN/' . str_pad($nextNumber, 4, '0', STR_PAD_LEFT);

        $companies = CustomerVendor::all();
        return view('manager.grn.grnorder', compact('grnNo', 'companies'));
    }

    // Show list of all GRNs
    public function grnDetails()
    {
        $grns = Grn::with('products')->orderBy('id', 'desc')->get();
        $companies = CustomerVendor::all();
        return view('manager.grn.grndetails', compact('grns', 'companies'));
    }

    // 1. Get all unused Sales and Purchase Order IDs
    public function availableOrders()
    {
        // Get all order_nos already in GRN table
        $usedOrderNos = \App\Models\Grn::pluck('order_no')->toArray();

        $salesOrders = \App\Models\SalesOrder::whereNotIn('sales_order_no', $usedOrderNos)
            ->select('sales_order_no as order_no', 'sales_order_date', DB::raw("'sales' as order_type"))
            ->get();

        $purchaseOrders = \App\Models\PurchaseOrder::whereNotIn('purchase_order_no', $usedOrderNos)
            ->select('purchase_order_no as order_no', 'purchase_order_date as order_date', DB::raw("'purchase' as order_type"))
            ->get();

        $orders = $salesOrders->concat($purchaseOrders)->values();
        return response()->json($orders);
    }

    // 2. Get full details for a given order_no and type
    public function orderDetails(Request $request)
    {
        $type = $request->query('type');
        $orderNo = $request->query('order_no');
        if ($type === 'sales') {
            $order = \App\Models\SalesOrder::where('sales_order_no', $orderNo)->with('customer')->first();
        } else {
            $order = \App\Models\PurchaseOrder::where('purchase_order_no', $orderNo)->with('vendor')->first();
        }
        if (!$order) {
            return response()->json(['error' => 'Order not found'], 404);
        }
        return response()->json($order);
    }


    // Store a new GRN
    public function store(Request $request)
    {
        $validated = $request->validate([
            'grn_no' => 'required|unique:grns,grn_no',
            'grn_date' => 'required|date',
            'order_no' => 'required',
            'order_date' => 'required|date',
            'company_name' => 'required',
            'product_type' => 'nullable|string',
            'challan' => 'nullable|file|mimes:pdf|max:2048',
            'products.*.description' => 'required|string',
            'products.*.quantity' => 'required|numeric',
            'products.*.unit' => 'required|string',
            'products.*.date' => 'required|date',
        ]);

        // Handle Challan file
        $challanPath = null;
        if ($request->hasFile('challan')) {
            $challanPath = $request->file('challan')->store('challans', 'public');
        }

        $grn = Grn::create([
            'grn_no' => $request->grn_no,
            'grn_date' => $request->grn_date,
            'order_no' => $request->order_no,
            'order_date' => $request->order_date,
            'company_name' => $request->company_name,
            'order_ref_no' => $request->order_ref_no,
            'company_address' => $request->company_address,
            'company_gst' => $request->company_gstn,
            'company_email' => $request->company_email,
            'company_phone' => $request->company_phone,
            'quotation_no' => $request->quotation_no,
            'quotation_date' => $request->quotation_date,
            'rfq_no' => $request->rfq_no,
            'rfq_date' => $request->rfq_date,
            'part_no' => $request->part_no,
            'project_material_no' => $request->project_material_no,
            'drawing_no' => $request->drawing_no,
            'drawing_rev' => $request->drawing_rev,
            'description' => $request->description,
            'product_type' => $request->product_type,
            'challan' => $challanPath,
        ]);

        foreach ($request->products as $index => $product) {
            GrnProductDetail::create([
                'grn_id' => $grn->id,
                'sl_no' => $index + 1,
                'description' => $product['description'],
                'quantity' => $product['quantity'],
                'unit' => $product['unit'],
                'date' => $product['date'],
                'supplier' => $product['supplier'] ?? null,
                'remarks' => $product['remarks'] ?? null,
            ]);
        }

        return redirect()->route('manager.grn.grnorder')->with('success', 'GRN saved successfully!');
    }

    // Edit GRN (show edit form)
    public function edit($id)
    {
        $grn = Grn::with('products')->findOrFail($id);
        $companies = CustomerVendor::all();
        return view('manager.grn.edit', compact('grn', 'companies'));
    }

    // Update GRN
    public function update(Request $request, $id)
    {
        $grn = Grn::findOrFail($id);

        $grn->update($request->only([
            'grn_date',
            'order_no',
            'order_date',
            'company_name',
            'order_ref_no',
            'company_address',
            'company_gst',
            'company_email',
            'company_phone',
            'quotation_no',
            'quotation_date',
            'rfq_no',
            'rfq_date',
            'part_no',
            'project_material_no',
            'drawing_no',
            'drawing_rev',
            'description',
            'product_type'
        ]));

        if ($request->hasFile('challan')) {
            $path = $request->file('challan')->store('challans', 'public');
            $grn->update(['challan' => $path]);
        }

        // Delete old products
        GrnProductDetail::where('grn_id', $grn->id)->delete();

        foreach ($request->products as $index => $product) {
            GrnProductDetail::create([
                'grn_id' => $grn->id,
                'sl_no' => $index + 1,
                'description' => $product['description'],
                'quantity' => $product['quantity'],
                'unit' => $product['unit'],
                'date' => $product['date'],
                'supplier' => $product['supplier'] ?? null,
                'remarks' => $product['remarks'] ?? null,
            ]);
        }

        return redirect()->route('manager.grn.grndetails')->with('success', 'GRN updated successfully.');
    }

    // Show GRN details (view)
    public function show($id)
    {
        $grn = Grn::with('products')->findOrFail($id);
        return view('manager.grn.view', compact('grn'));
    }

    // Delete GRN
    public function destroy($id)
    {
        $grn = Grn::findOrFail($id);
        $grn->products()->delete();
        $grn->delete();

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

    // Import GRNs from Excel
    public function import(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xls,xlsx'
        ]);

        try {
            $file = $request->file('file');
            $spreadsheet = IOFactory::load($file->getRealPath());
            $sheet = $spreadsheet->getActiveSheet();
            $rows = $sheet->toArray();

            $header = array_shift($rows);

            foreach ($rows as $row) {
                $data = array_combine($header, $row);

                if (empty($data['grn_no'])) continue;

                Grn::updateOrCreate(
                    ['grn_no' => $data['grn_no']],
                    [
                        'grn_date' => $data['grn_date'],
                        'order_no' => $data['order_no'],
                        'order_date' => $data['order_date'],
                        'company_name' => $data['company_name'],
                        'order_ref_no' => $data['order_ref_no'],
                        'company_address' => $data['company_address'],
                        'company_gst' => $data['company_gstn'],
                        'company_email' => $data['company_email'],
                        'company_phone' => $data['company_phone'],
                        'quotation_no' => $data['quotation_no'],
                        'quotation_date' => $data['quotation_date'],
                        'rfq_no' => $data['rfq_no'],
                        'rfq_date' => $data['rfq_date'],
                        'part_no' => $data['part_no'],
                        'project_material_no' => $data['project_material_no'],
                        'drawing_no' => $data['drawing_no'],
                        'drawing_rev' => $data['drawing_rev'],
                        'description' => $data['description'],
                        'product_type' => $data['product_type'],
                    ]
                );
            }

            return redirect()->back()->with('success', 'GRNs imported successfully.');
        } catch (\Throwable $e) {
            Log::error('GRN Import Error: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Failed to import: ' . $e->getMessage());
        }
    }
}
