<?php

namespace App\Http\Controllers\SuperAdmin;

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;

use App\Models\RfqFile;

class SuperAdminRfqController extends Controller
{
    public function rfq()
    {
        $customers = CustomerVendor::whereIn('company_role',['Customer','Both'])->get();
        $rfqTypes = RfqType::all();
        $productTypes = ProductType::all();
        $rawmaterials = RawMaterial::all();
        return view('superadmin.salesbom.rfq.rfq', compact('customers', 'rfqTypes', 'productTypes', 'rawmaterials'));
    }

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

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

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

    public function store(Request $request)
    {
        try {
            Log::info('[RFQ STORE] Incoming request data:', $request->all());
    
            $validated = $request->validate([
                'rfqNo' => 'required|string',
                'rfqDate' => 'required|date',
                'customer' => 'required|string',
                'cusRefNo' => 'nullable|string',
                'rfqType' => 'required|string',
                'productType' => 'required|string',
                'partNo' => 'nullable|string',
                'project_materialNo' => 'nullable|string',
                'description' => 'nullable|string',
                'drawingNo' => 'nullable|string',
                'drawingRev' => 'nullable|string',
                'quantity' => 'required|numeric',
                'uom' => 'required|string',
                'note' => 'nullable|string',
                'rawmaterials' => 'required|array',
                'rawmaterials.*' => 'required|string',
    
                // File validations (multiple)
                'drawingFiles.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png',
                'materialSpecificationFiles.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png',
                'rfqFormFiles.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png',
                'annexureFiles.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png',
            ]);
    
            Log::info('[RFQ STORE] Validation passed', $validated);
    
            // Replace 'other' values if needed
            if ($request->rfqType == 'other') {
                $validated['rfqType'] = $request->input('other_rfq_type');
            }
            if ($request->productType == 'other') {
                $validated['productType'] = $request->input('other_product_type');
            }
    
            // Prepare RFQ data (without files)
            $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,
                'description' => $request->description,
                'drawing_no' => $request->drawingNo,
                'drawing_rev' => $request->drawingRev,
                'quantity' => $request->quantity,
                'uom' => $request->uom,
                'note' => $request->note,
                'raw_material' => json_encode($request->rawmaterials),
            ];
    
            Log::info('[RFQ STORE] Final data for insert:', $data);
    
            // Create RFQ
            $rfq = Rfq::create($data);
            Log::info('[RFQ STORE] RFQ created successfully. ID: ' . $rfq->id);
    
            // Store files in separate table
            $fileInputs = [
                'drawingFiles' => 'drawing',
                'materialSpecificationFiles' => 'material_spec',
                'rfqFormFiles' => 'rfq_form',
                'annexureFiles' => 'annexure',
            ];
            
            foreach ($fileInputs as $inputName => $type) {
                if ($request->hasFile($inputName)) {
                    foreach ($request->file($inputName) as $file) {
                        $path = $file->store("rfq_files/{$type}", 'public');
            
                        RfqFile::create([
                            'rfq_id' => $rfq->id,
                            'file_path' => $path,
                            'file_name' => $file->getClientOriginalName(),
                            'file_type' => $type,
                        ]);
            
                        Log::info("[RFQ STORE] File saved for type {$type}: {$path}");
                    }
                }
            }
    
            return redirect()->route('superadmin.salesbom.rfq.rfqdetails')->with('success', 'RFQ created successfully.');
    
        } catch (\Illuminate\Validation\ValidationException $ve) {
            Log::error('[RFQ STORE] Validation Error:', $ve->errors());
            return back()->withErrors($ve->errors())->withInput();
        } catch (\Exception $e) {
            Log::error('[RFQ STORE] General Error: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);
            return back()->with('error', 'Something went wrong while creating RFQ.');
        }
    }

    public function approve($id)
    {
        $rfq = Rfq::findOrFail($id);
        $rfq->status = 'approved';
        $rfq->save();
        return response()->json(['message' => 'RFQ approved!']);
    }

    public function reject($id)
    {
        $rfq = Rfq::findOrFail($id);
        $rfq->status = 'rejected';
        $rfq->save();
        return response()->json(['message' => 'RFQ rejected!']);
    }

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

    public function view($id)
    {
        $rfq = Rfq::with(['customerInfo', 'rfqFiles'])->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('rm_grade', 'id')
                    ->toArray();
            }
        }

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

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

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

    public function update_old(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' => 'nullable|string',
                'project_materialNo' => 'nullable|string',
                'description'=> 'nullable|string',
                'drawingNo' => 'nullable|string',
                'drawingRev' => 'nullable|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,
                'description' => $request->description,
                '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('superadmin.salesbom.rfq.rfqdetails')->with('success', 'RFQ updated successfully.');
        } catch (\Exception $e) {
            Log::error('SuperAdmin RFQ Update Error: ' . $e->getMessage());
            return back()->with('error', 'Something went wrong while updating RFQ.');
        }
    }
    
    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' => 'nullable|string',
                'project_materialNo' => 'nullable|string',
                'description' => 'nullable|string',
                'drawingNo' => 'nullable|string',
                'drawingRev' => 'nullable|string',
                'quantity' => 'required|numeric',
                'uom' => 'required|string',
                'note' => 'nullable|string',
                'rawmaterials' => 'required|array',
                'rawmaterials.*' => 'required|string',
    
                // Optional file validations
                'drawingFiles.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png',
                'materialSpecificationFiles.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png',
                'rfqFormFiles.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png',
                'annexureFiles.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png',
            ]);
    
            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,
                'description' => $request->description,
                'drawing_no' => $request->drawingNo,
                'drawing_rev' => $request->drawingRev,
                'quantity' => $request->quantity,
                'uom' => $request->uom,
                'note' => $request->note,
                'raw_material' => json_encode($request->rawmaterials),
            ];
    
            // Update RFQ data (excluding files)
            $rfq->update($data);
    
            // Handle new file uploads
            $fileInputs = [
                'drawingFiles' => 'drawing',
                'materialSpecificationFiles' => 'material_spec',
                'rfqFormFiles' => 'rfq_form',
                'annexureFiles' => 'annexure',
            ];
    
            foreach ($fileInputs as $inputName => $type) {
                if ($request->hasFile($inputName)) {
                    foreach ($request->file($inputName) as $file) {
                        $path = $file->store("rfq_files/{$type}", 'public');
    
                        RfqFile::create([
                            'rfq_id' => $rfq->id,
                            'file_path' => $path,
                            'file_name' => $file->getClientOriginalName(),
                            'file_type' => $type,
                        ]);
                    }
                }
            }
    
            return redirect()->route('superadmin.salesbom.rfq.rfqdetails')->with('success', 'RFQ updated successfully.');
        } catch (\Illuminate\Validation\ValidationException $ve) {
            Log::error('[RFQ UPDATE] Validation Error:', $ve->errors());
            return back()->withErrors($ve->errors())->withInput();
        } catch (\Exception $e) {
            Log::error('[RFQ UPDATE] General Error: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);
            return back()->with('error', 'Something went wrong while updating RFQ.');
        }
    }

    public function destroy($id)
    {
        try {
            $rfq = Rfq::with('rfqFiles')->findOrFail($id);

            // Delete files from rfqFiles table
            foreach ($rfq->rfqFiles as $file) {
                if (Storage::disk('public')->exists($file->file_path)) {
                    Storage::disk('public')->delete($file->file_path);
                }
                $file->delete();
            }

            // Delete legacy file fields (if any)
            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('SuperAdmin 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('superadmin.salesbom.rfq.print', compact('rfq', 'rawMaterialNames'));
    }
    
    public function deleteFile($id)
    {
        $file = RfqFile::find($id);
    
        if (!$file) {
            return response()->json(['success' => false, 'message' => 'File not found.']);
        }
    
        if (Storage::disk('public')->exists($file->file_path)) {
            Storage::disk('public')->delete($file->file_path);
        }
    
        $file->delete();
    
        return response()->json(['success' => true, 'message' => 'File deleted successfully.']);
    }


}
