<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\PurchaseQuotation;
use App\Models\PurchaseRFQ;
use App\Models\CustomerVendor;
use App\Models\ProductType;
use App\Models\ConversionProcess;
use Illuminate\Support\Facades\Log;

class SuperAdminPurchaseQuotationController extends Controller
{
    public function quotationPage()
    {
        $vendors = CustomerVendor::where('company_role', 'Vendor')->orWhere('company_role', 'Both')->get();
        $productTypes = ProductType::all();
        // Fetch only Purchase RFQs that are not yet assigned in quotations
        $assignedRfqIds = PurchaseQuotation::whereNotNull('rfq_no')->pluck('rfq_no')->toArray();
        $unassignedRfqs = PurchaseRFQ::whereNotIn('rfq_no', $assignedRfqIds)->where('status', 'approved')->get();
        $conversionCosts = ConversionProcess::pluck('process_name')->toArray();
        $allRawMaterials = \App\Models\RawMaterial::all();
        return view('superadmin.purchasebom.quotation.quotationorder', compact('vendors', 'unassignedRfqs', 'conversionCosts', 'allRawMaterials', 'productTypes'));
    }

    public function getRfqDetails($id)
    {
        Log::info('Purchase getRfqDetails called with id:', ['id' => $id]);

        $rfq = PurchaseRFQ::with(['items', 'vendor'])->findOrFail($id);
        Log::info('Purchase RFQ retrieved:', $rfq->toArray());

        $vendor = $rfq->vendor;
        if ($vendor) {
            Log::info('Vendor retrieved:', $vendor->toArray());
        } else {
            Log::warning('No vendor found for Purchase RFQ id: ' . $id);
        }

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

    public function quotationDetails()
    {
        $quotations = PurchaseQuotation::with('vendor')->latest()->get();
        $assignedRfqIds = PurchaseQuotation::whereNotNull('rfq_no')->pluck('rfq_no')->toArray();
        $unassignedRfqs = PurchaseRFQ::whereNotIn('rfq_no', $assignedRfqIds)->get();
        return view('superadmin.purchasebom.quotation.quotationdetails', compact('quotations', 'unassignedRfqs'));
    }

    public function print($id)
    {
        $quotation = PurchaseQuotation::with(['vendor', 'items'])->findOrFail($id);
        return view('superadmin.purchasebom.quotation.print', compact('quotation'));
    }

    public function store(Request $request)
    {
        Log::info('Purchase Quotation store', ['data' => $request->all()]);
        try {
            $validated = $request->validate([
                'quotation_no' => 'required|unique:purchase_quotations,quotation_no',
                'quotation_date' => 'required|date',
                'vendor_id' => 'required|exists:customer_vendors,id',
                'address' => 'nullable|string',
                'gst' => 'nullable|string',
                'email' => 'nullable|email',
                'phone' => 'nullable|string|max:15',
            ]);

            $quotation = PurchaseQuotation::create([
                'quotation_no' => $request->quotation_no,
                'quotation_date' => $request->quotation_date,
                'vendor_id' => $request->vendor_id,
                'vendor_name' => $request->vendor_name,
                'address' => $request->address,
                'gst' => $request->gst,
                'email' => $request->email,
                'phone' => $request->phone,
                'rfq_no' => $request->rfq_no,
                'rfq_date' => $request->rfq_date,
                'vendor_reference_no' => $request->vendor_reference_no,
                'delivery_terms' => $request->delivery_terms,
                'part_no' => $request->part_no,
                'project_material_no' => $request->project_material_no,
                'drawing_no' => $request->drawing_no,
                'drawing_rev' => $request->drawing_rev,
                'quantity' => $request->quantity,
                'quantity_uom' => $request->quantity_uom,
                'description' => $request->description,
                'note' => $request->note,
                'sub_total' => $request->sub_total,
                'discount' => $request->discount,
                'round_up' => $request->round_up,
                'grand_total' => $request->grand_total,
                'inr_in_words' => $request->inr_in_words,
                'additional_charges' => $request->additional_charges,
                'status' => 'pending',
            ]);

            Log::info('Purchase Quotation created', ['quotation_id' => $quotation->id]);
            return redirect()->route('superadmin.purchasebom.quotation.quotationdetails')->with('success', 'Purchase Quotation created successfully!');
        } catch (\Exception $e) {
            Log::error('Error in SuperAdminPurchaseQuotationController@store', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'data' => $request->all(),
            ]);
            return redirect()->back()->with('error', 'Failed to create quotation: ' . $e->getMessage());
        }
    }

    public function view($id)
    {
        $quotation = PurchaseQuotation::with(['vendor', 'items'])->findOrFail($id);
        return view('superadmin.purchasebom.quotation.view', compact('quotation'));
    }

    public function approve($id)
    {
        $quotation = PurchaseQuotation::findOrFail($id);
        $quotation->status = 'approved';
        $quotation->save();

        return response()->json(['success' => true, 'message' => 'Purchase Quotation approved!']);
    }

    public function reject($id)
    {
        $quotation = PurchaseQuotation::findOrFail($id);
        $quotation->status = 'rejected';
        $quotation->save();

        return response()->json(['success' => true, 'message' => 'Purchase Quotation rejected!']);
    }

    public function edit($id)
    {
        $quotation = PurchaseQuotation::with(['vendor', 'items'])->findOrFail($id);
        $vendors = CustomerVendor::where('company_role', 'Vendor')->orWhere('company_role', 'Both')->get();

        $vendor = $quotation->vendor;

        $assignedRfqIds = PurchaseQuotation::whereNotNull('rfq_no')->where('id', '!=', $id)->pluck('rfq_no')->toArray();
        $unassignedRfqs = PurchaseRFQ::whereNotIn('rfq_no', $assignedRfqIds)->where('status', 'approved')->get();
        $conversionprocesses = ConversionProcess::pluck('process_name')->toArray();
        $allRawMaterials = \App\Models\RawMaterial::all();

        return view('superadmin.purchasebom.quotation.edit', compact('quotation', 'vendors', 'unassignedRfqs', 'vendor', 'conversionprocesses', 'allRawMaterials'));
    }

    public function update(Request $request, $id)
    {
        $quotation = PurchaseQuotation::findOrFail($id);

        $validated = $request->validate([
            'quotation_no' => [
                'required',
                'string',
                'max:30',
                \Illuminate\Validation\Rule::unique('purchase_quotations', 'quotation_no')->ignore($id)
            ],
            'quotation_date' => ['required', 'date'],
            'vendor_id' => ['required', 'exists:customer_vendors,id'],
            'address' => ['nullable', 'string'],
            'gst' => ['nullable', 'string', 'max:25'],
            'phone' => ['nullable', 'string', 'max:25'],
            'email' => ['nullable', 'email', 'max:255'],
            'rfq_no' => ['nullable', 'string', 'max:100'],
            'rfq_date' => ['nullable', 'date'],
            'vendor_reference_no' => ['nullable', 'string', 'max:100'],
            'delivery_terms' => ['nullable', 'string'],
            'part_no' => ['nullable', 'string', 'max:100'],
            'project_material_no' => ['nullable', 'string', 'max:100'],
            'drawing_no' => ['nullable', 'string', 'max:100'],
            'drawing_rev' => ['nullable', 'string', 'max:50'],
            'quantity' => ['nullable', 'integer', 'min:0'],
            'quantity_uom' => ['nullable', 'string', 'max:20'],
            'description' => ['nullable', 'string'],
            'note' => ['nullable', 'string'],
            'sub_total' => ['nullable', 'numeric', 'min:0'],
            'discount' => ['nullable', 'numeric', 'min:0', 'max:100'],
            'round_up' => ['nullable', 'numeric'],
            'grand_total' => ['required', 'numeric', 'min:0'],
        ]);

        $quotation->update([
            'quotation_no' => $request->quotation_no,
            'quotation_date' => $request->quotation_date,
            'vendor_id' => $request->vendor_id,
            'vendor_name' => $request->vendor_name,
            'address' => $request->address,
            'gst' => $request->gst,
            'email' => $request->email,
            'phone' => $request->phone,
            'rfq_no' => $request->rfq_no,
            'rfq_date' => $request->rfq_date,
            'vendor_reference_no' => $request->vendor_reference_no,
            'delivery_terms' => $request->delivery_terms,
            'part_no' => $request->part_no,
            'project_material_no' => $request->project_material_no,
            'drawing_no' => $request->drawing_no,
            'drawing_rev' => $request->drawing_rev,
            'quantity' => $request->quantity,
            'quantity_uom' => $request->quantity_uom,
            'description' => $request->description,
            'note' => $request->note,
            'sub_total' => $request->sub_total,
            'discount' => $request->discount,
            'round_up' => $request->round_up,
            'grand_total' => $request->grand_total,
            'inr_in_words' => $request->inr_in_words,
            'additional_charges' => $request->additional_charges,
        ]);

        return back()->with('success', 'Purchase Quotation updated.');
    }

    public function destroy($id)
    {
        $quotation = PurchaseQuotation::findOrFail($id);
        $quotation->items()->delete();
        $quotation->files()->delete();
        $quotation->delete();

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

    // DataTables AJAX support
    public function quotationListAjax(Request $request)
    {
        $quotations = PurchaseQuotation::with('vendor')->latest()->get();

        return datatables()->of($quotations)
            ->addColumn('vendor_name', function ($q) {
                return $q->vendor ? $q->vendor->company : $q->vendor_name;
            })
            ->addColumn('view_pdf', function ($q) {
                $pdfUrl = asset('storage/purchase_quotations/' . $q->quotation_no . '.pdf');
                return '<button class="btn btn-success view-pdf" data-url="' . $pdfUrl . '">View</button>';
            })
            ->addColumn('convert', function () {
                return '<button class="btn btn-warning">Convert</button>';
            })
            ->rawColumns(['view_pdf', 'convert'])
            ->make(true);
    }
}
