<?php

namespace App\Http\Controllers\Manager;

use App\Http\Controllers\Controller;
use App\Models\CustomerVendor;
use App\Models\Rfq;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use App\Models\RfqType;
use App\Models\ProductType;
use App\Models\RawMaterial;
use Barryvdh\DomPDF\Facade\Pdf;

class ManagerRfqController extends Controller
{
    public function rfq()
    {
        $customers = CustomerVendor::all();
        $rfqTypes = RfqType::all();
        $productTypes = ProductType::all();
        $rawmaterials = RawMaterial::all();
        return view('manager.rfq.rfq', compact('customers', 'rfqTypes', 'productTypes', 'rawmaterials'));
    }

    public function generateRfqId()
    {
        $latest = Rfq::latest('id')->first();
        $lastNumber = 0;

        if ($latest && preg_match('/UEPL\/RFQ\/(\d+)/', $latest->rfq_no, $matches)) {
            $lastNumber = (int) $matches[1];
        }
        $newId = str_pad($lastNumber + 1, 4, '0', STR_PAD_LEFT);
        $rfqId = "UEPL/RFQ/{$newId}";

        return response()->json(['rfqId' => $rfqId]);
    }

    public function store(Request $request)
    {
        try {
            $validated = $request->validate([
                'rfqNo' => 'required|string',
                'rfqDate' => 'required|date',
                'customer' => 'required|string',
                'cusRefNo' => 'nullable|string',
                'rfqType' => 'required|string',
                'productType' => 'required|string',
                'partNo' => 'required|string',
                'project_materialNo' => 'required|string',
                'drawingFile' => 'required|file|mimes:pdf',
                'drawingNo' => 'required|string',
                'drawingRev' => 'required|string',
                'quantity' => 'required|numeric',
                'uom' => 'required|string',
                'note' => 'nullable|string',
                'rawmaterials' => 'required|array',
                'rawmaterials.*' => 'required|string',
            ]);
            if ($request->rfqType == 'other') {
                $validated['rfqType'] = $request->input('other_rfq_type');
            }
            if ($request->productType == 'other') {
                $validated['productType'] = $request->input('other_product_type');
            }
            $data = [
                'rfq_no' => $request->rfqNo,
                'rfq_date' => $request->rfqDate,
                'customer' => $request->customer,
                'cus_ref_no' => $request->cusRefNo,
                'rfq_type' => $validated['rfqType'],
                'product_type' => $validated['productType'],
                'part_no' => $request->partNo,
                'project_material_no' => $request->project_materialNo,
                'drawing_no' => $request->drawingNo,
                'drawing_rev' => $request->drawingRev,
                'quantity' => $request->quantity,
                'annexure_file' => $request->file('annexure_file') ? $request->file('annexure_file')->store('rfq_annexures', 'public') : null,
                'uom' => $request->uom,
                'note' => $request->note,
                'raw_material' => json_encode($request->rawmaterials),
            ];

            // Handle file uploads
            if ($request->hasFile('drawingFile')) {
                $data['drawing_file'] = $request->file('drawingFile')->store('rfq_drawings', 'public');
            }
            if ($request->hasFile('material-specificationFile')) {
                $data['material_specification_file'] = $request->file('material-specificationFile')->store('rfq_material_specs', 'public');
            }
            if ($request->hasFile('rfqformFile')) {
                $data['rfq_form_file'] = $request->file('rfqformFile')->store('rfq_forms', 'public');
            }
            if ($request->hasFile('annexureFile')) {
                $data['annexure_file'] = $request->file('annexureFile')->store('rfq_annexures', 'public');
            }

            Rfq::create($data);

            return redirect()->route('manager.rfq.rfqdetails')->with('success', 'RFQ created successfully.');
        } catch (\Exception $e) {
            Log::error('Manager RFQ Store Error: ' . $e->getMessage());
            return back()->with('error', 'Something went wrong while creating RFQ.');
        }
    }

    public function rfqDetails()
    {
        $rfqs = Rfq::with('customerInfo')->latest()->get();
        return view('manager.rfq.rfqdetails', compact('rfqs'));
    }

    public function view($id)
    {
        $rfq = Rfq::with('customerInfo')->findOrFail($id);
        $rawMaterialNames = [];

        if ($rfq->raw_material) {
            $rawMaterialIds = json_decode($rfq->raw_material, true);

            // Only fetch if array and not empty
            if (is_array($rawMaterialIds) && count($rawMaterialIds)) {
                $rawMaterialNames = RawMaterial::whereIn('id', $rawMaterialIds)
                    ->pluck('name', 'id')
                    ->toArray();
            }
        }

        return view('manager.rfq.view', compact('rfq', 'rawMaterialNames'));
    }

    public function edit($id)
    {
        $rfq = Rfq::with('customerInfo')->findOrFail($id);
        $customers = CustomerVendor::all();
        $rfqTypes = RfqType::all();
        $productTypes = ProductType::all();
        $rawmaterials = RawMaterial::all();

        return view('manager.rfq.edit', compact('rfq', 'customers', 'rfqTypes', 'productTypes', 'rawmaterials'));
    }

    public function update(Request $request, $id)
    {
        try {
            $rfq = Rfq::findOrFail($id);

            $validated = $request->validate([
                'rfqNo' => 'required|string',
                'rfqDate' => 'required|date',
                'customer' => 'required|string',
                'cusRefNo' => 'nullable|string',
                'rfqType' => 'required|string',
                'productType' => 'required|string',
                'partNo' => 'required|string',
                'project_materialNo' => 'required|string',
                'drawingNo' => 'required|string',
                'drawingRev' => 'required|string',
                'quantity' => 'required|numeric',
                'uom' => 'required|string',
                'note' => 'nullable|string',
                'rawmaterials' => 'required|array',
                'rawmaterials.*' => 'required|string',
            ]);
            if ($request->rfqType == 'other') {
                $validated['rfqType'] = $request->input('other_rfq_type');
            }
            if ($request->productType == 'other') {
                $validated['productType'] = $request->input('other_product_type');
            }

            $data = [
                'rfq_no' => $request->rfqNo,
                'rfq_date' => $request->rfqDate,
                'customer' => $request->customer,
                'cus_ref_no' => $request->cusRefNo,
                'rfq_type' => $validated['rfqType'], // use from $validated
                'product_type' => $validated['productType'], // use from $validated
                'part_no' => $request->partNo,
                'project_material_no' => $request->project_materialNo,
                'drawing_no' => $request->drawingNo,
                'drawing_rev' => $request->drawingRev,
                'quantity' => $request->quantity,
                'uom' => $request->uom,
                'note' => $request->note,
                'raw_material' => json_encode($request->rawmaterials),
            ];

            // Handle file re-upload (optional update)
            if ($request->hasFile('drawingFile')) {
                if ($rfq->drawing_file)
                    Storage::disk('public')->delete($rfq->drawing_file);
                $data['drawing_file'] = $request->file('drawingFile')->store('rfq_drawings', 'public');
            }
            if ($request->hasFile('material-specificationFile')) {
                if ($rfq->material_specification_file)
                    Storage::disk('public')->delete($rfq->material_specification_file);
                $data['material_specification_file'] = $request->file('material-specificationFile')->store('rfq_material_specs', 'public');
            }
            if ($request->hasFile('rfqformFile')) {
                if ($rfq->rfq_form_file)
                    Storage::disk('public')->delete($rfq->rfq_form_file);
                $data['rfq_form_file'] = $request->file('rfqformFile')->store('rfq_forms', 'public');
            }
            if ($request->hasFile('annexureFile')) {
                if ($rfq->annexure_file)
                    Storage::disk('public')->delete($rfq->annexure_file);
                $data['annexure_file'] = $request->file('annexureFile')->store('rfq_annexures', 'public');
            }

            $rfq->update($data);

            return redirect()->route('manager.rfq.rfqdetails')->with('success', 'RFQ updated successfully.');
        } catch (\Exception $e) {
            Log::error('Manager RFQ Update Error: ' . $e->getMessage());
            return back()->with('error', 'Something went wrong while updating RFQ.');
        }
    }

    public function destroy($id)
    {
        try {
            $rfq = Rfq::findOrFail($id);
            if ($rfq->drawing_file)
                Storage::disk('public')->delete($rfq->drawing_file);
            if ($rfq->material_specification_file)
                Storage::disk('public')->delete($rfq->material_specification_file);
            if ($rfq->rfq_form_file)
                Storage::disk('public')->delete($rfq->rfq_form_file);
            if ($rfq->annexure_file)
                Storage::disk('public')->delete($rfq->annexure_file);

            $rfq->delete();
            return response()->json(['message' => 'RFQ deleted successfully.']);
        } catch (\Exception $e) {
            Log::error('Manager RFQ Delete Error: ' . $e->getMessage());
            return response()->json(['message' => 'Failed to delete RFQ.'], 500);
        }
    }
    public function getRawMaterials()
    {
        return response()->json(RawMaterial::all());
    }

    // Store new raw material
    public function storeRawMaterial(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'iso_specification' => 'required|string|max:255',
            'density' => 'nullable|string|max:255',
            'mechanical_properties' => 'nullable|string|max:255',
        ]);

        $material = RawMaterial::create($request->all());

        return response()->json(['success' => true, 'material' => $material]);
    }
    public function printRfq($id)
    {
        $rfq = \App\Models\Rfq::with('customerInfo')->findOrFail($id);

        $rawMaterialNames = [];
        if ($rfq->raw_material) {
            $rawMaterialIds = json_decode($rfq->raw_material, true);
            if (is_array($rawMaterialIds) && count($rawMaterialIds)) {
                $rawMaterialNames = \App\Models\RawMaterial::whereIn('id', $rawMaterialIds)
                    ->pluck('name', 'id')
                    ->toArray();
            }
        }

        return view('manager.rfq.print', compact('rfq', 'rawMaterialNames'));
    }
}
