<?php

namespace App\Http\Controllers\Manager;

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

class ManagerQuotationController extends Controller
{
    public function quotationPage()
    {
        $customers = CustomerVendor::all();
        $productTypes = ProductType::all();
        // Fetch only RFQs that are not yet assigned in quotations
        $assignedRfqIds = Quotation::whereNotNull('rfq_no')->pluck('rfq_no')->toArray();
        $unassignedRfqs = Rfq::whereNotIn('rfq_no', $assignedRfqIds)->get();
        $conversionCosts = ConversionProcess::pluck('process_name')->toArray();
        $allRawMaterials = \App\Models\RawMaterial::all();
        return view('manager.quotation.quotationorder', compact('customers', 'unassignedRfqs', 'conversionCosts', 'allRawMaterials','productTypes'));
    }

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

        $rfq = \App\Models\Rfq::findOrFail($id);
        Log::info('RFQ retrieved:', $rfq->toArray());

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

        // Parse the raw_material string as array of IDs
        $rawMaterialIds = [];
        if ($rfq->raw_material) {
            if (is_array($rfq->raw_material)) {
                $rawMaterialIds = $rfq->raw_material;
            } else {
                $rawMaterialIds = json_decode($rfq->raw_material, true);
            }
            Log::info('Parsed raw_material IDs:', $rawMaterialIds);
        } else {
            Log::info('No raw_material found for RFQ id: ' . $id);
        }

        // Fetch raw materials from the model
        $rawMaterials = [];
        if ($rawMaterialIds && count($rawMaterialIds)) {
            $rawMaterials = \App\Models\RawMaterial::whereIn('id', $rawMaterialIds)->get();
            Log::info('Raw materials found:', $rawMaterials->toArray());
        } else {
            Log::info('No raw material IDs to fetch for RFQ id: ' . $id);
        }

        // You can log the final response if desired (be careful if response is large)
        // \Log::info('Returning RFQ details response', [
        //     'rfq' => $rfq->id,
        //     'customer' => $customer ? $customer->id : null,
        //     'raw_materials_count' => count($rawMaterials)
        // ]);

        return response()->json([
            'success' => true,
            'rfq' => $rfq,
            'customer' => $customer,
            'raw_materials' => $rawMaterials,
        ]);
    }



    public function quotationDetails()
    {
        $quotations = Quotation::with('customer')->latest()->get();
        $assignedRfqIds = Quotation::whereNotNull('rfq_no')->pluck('rfq_no')->toArray();
        $unassignedRfqs = Rfq::whereNotIn('rfq_no', $assignedRfqIds)->get();
        return view('manager.quotation.quotationdetails', compact('quotations', 'unassignedRfqs'));
    }

    public function print($id)
    {
        $quotation = Quotation::findOrFail($id);
        $quotation->raw_materials = $quotation->raw_materials ? json_decode($quotation->raw_materials, true) : [];
        $quotation->conversion_costs = $quotation->conversion_costs ? json_decode($quotation->conversion_costs, true) : [];
        $quotation->packing_charges = $quotation->packing_charges ? json_decode($quotation->packing_charges, true) : [];
        return view('manager.quotation.print', compact('quotation'));
    }

    public function store(Request $request)
    {
        Log::info('Starting validation', ['data' => $request->all()]);
        try {
            $validated = $request->validate([
                'quotation_no' => 'required|unique:quotations,quotation_no',
                'quotation_date' => 'required|date',
                'customer_name' => 'required|exists:customer_vendors,id',
                'address' => 'required|string',
                'gst' => 'required|string',
                'email' => 'required|email',
                'phone' => 'required|string|max:15',
            ]);
            Log::info('Validation passed', ['data' => $validated]);
            $rawMaterials = $request->has('raw_material') ? array_values($request->raw_material) : [];
            $conversionCosts = $request->has('conversion_cost') ? array_values($request->conversion_cost) : [];
            $packingCharges = $request->has('packing') ? array_values($request->packing) : [];

            $quotation = Quotation::create([
                'quotation_no' => $request->quotation_no,
                'quotation_date' => $request->quotation_date,
                'customer_name' => $request->customer_name,
                'address' => $request->address,
                'gst' => $request->gst,
                'email' => $request->email,
                'phone' => $request->phone,
                'cust_ref_no' => $request->cust_ref_no,
                '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,
                'quantity' => $request->quantity,
                'quantity_uom' => $request->quantity_uom,
                'description' => $request->description,
                'product_type' => $request->product_type,
                'note' => $request->note,
                'sub_total' => $request->sub_total,
                'discount' => $request->discount,
                'round_up' => $request->round_up,
                'grand_total' => $request->grand_total,
                'raw_materials' => json_encode($rawMaterials),
                'conversion_costs' => json_encode($conversionCosts),
                'packing_charges' => json_encode($packingCharges),
            ]);
            Log::info('Quotation created', ['quotation_id' => $quotation->id]);
            return redirect()->route('manager.quotation.quotationdetails')->with('success', 'Quotation created successfully!');
        } catch (\Exception $e) {
            Log::error('Error in ManagerQuotationController@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 = Quotation::findOrFail($id);
        return view('manager.quotation.view', compact('quotation'));
    }

    public function edit($id)
    {
        $quotation = Quotation::findOrFail($id);
        $customers = CustomerVendor::all();

        // Get the customer id (assume stored as customer_id, if not, use customer_name for legacy)
        $customerId = $quotation->customer_id ?? $quotation->customer_name;
        $customer = CustomerVendor::find($customerId);

        $assignedRfqIds = Quotation::whereNotNull('rfq_no')->pluck('rfq_no')->toArray();
        $unassignedRfqs = Rfq::whereNotIn('rfq_no', $assignedRfqIds)->get();
        $conversionprocesses = ConversionProcess::pluck('process_name')->toArray();
        $allRawMaterials = \App\Models\RawMaterial::all();
        // PASS $customer to the view!
        return view('manager.quotation.edit', compact('quotation', 'customers', 'unassignedRfqs', 'customer', 'conversionprocesses','allRawMaterials'));
    }

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

        $validated = $request->validate([
            'quotation_no'   => [
                'required',
                'string',
                'max:30',
                \Illuminate\Validation\Rule::unique('quotations', 'quotation_no')->ignore($id)
            ],
            'quotation_date' => ['required', 'date'],
            'customer_name'  => ['required', 'string', 'max:255'],
            'address'        => ['required', 'string'],
            'gst'            => ['nullable', 'string', 'max:25'],
            'phone'          => ['nullable', 'string', 'max:25'],
            'email'          => ['nullable', 'email', 'max:255'],
            'cust_ref_no'    => ['nullable', 'string', 'max:100'],
            'rfq_no'         => ['nullable', 'string', 'max:100'],
            'rfq_date'       => ['nullable', 'date'],
            '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'],
            'product_type'   => ['nullable', 'string', 'max:100'],
            '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,
            'customer_name' => $request->customer_name,
            'address' => $request->address,
            'gst' => $request->gst,
            'email' => $request->email,
            'phone' => $request->phone,
            'cust_ref_no' => $request->cust_ref_no,
            '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,
            'quantity' => $request->quantity,
            'quantity_uom' => $request->quantity_uom,
            'description' => $request->description,
            'product_type' => $request->product_type,
            'note' => $request->note,
            'sub_total' => $request->sub_total,
            'discount' => $request->discount,
            'round_up' => $request->round_up,
            'grand_total' => $request->grand_total,
            'raw_materials' => $request->has('raw_material') ? json_encode(array_values($request->raw_material)) : null,
            'conversion_costs' => $request->has('conversion_cost') ? json_encode(array_values($request->conversion_cost)) : null,
            'packing_charges' => $request->has('packing') ? json_encode(array_values($request->packing)) : null,
        ]);

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

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

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

    // If you need datatables AJAX support:
    public function quotationListAjax(Request $request)
    {
        $quotations = Quotation::latest()->get();

        return datatables()->of($quotations)
            ->addColumn('view_pdf', function ($q) {
                $pdfUrl = asset('storage/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);
    }
}
