<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\CustomerVendor;
use App\Models\PurchaseRFQ as RFQ;
use App\Models\PurchaseRFQItem as RFQItem;
use App\Models\PurchaseRFQFiles as RfqFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use App\Models\RfqType;
use App\Models\StockItem;

use App\Models\ProductType;
use App\Models\RawMaterial;
use Barryvdh\DomPDF\Facade\Pdf;

class SuperAdminPurchaseRFQController extends Controller
{
    public function rfq()
    {
        $vendors = CustomerVendor::whereIn('company_role',['Vendor','Both'])->get();
        $rfqTypes = RfqType::all();
        $stock_items = StockItem::all();
        return view('superadmin.purchasebom.rfq.rfq', compact('vendors', 'rfqTypes','stock_items'));
    }

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

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

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

    public function store(Request $request)
    {
        try {
            Log::info('[RFQ STORE] Incoming request:', $request->all());

            // Validate the main RFQ form
            $validated = $request->validate([
                'rfqNo' => 'required|string|unique:purchase_rfqs,rfq_no',
                'rfqDate' => 'required|date',
                'vendor' => 'required|exists:customer_vendors,id',
                'venRefNo' => 'nullable|string',
                'rfqType' => 'required|string',

                'description_main' => 'nullable|string',
                'deliveryTerms' => 'nullable|string',
                'note' => 'nullable|string',

                'item' => 'nullable|array',
                'description' => 'nullable|array',
                'quantity' => 'nullable|array',
                'uom' => 'nullable|array',
                'requiredBy' => 'nullable|array',

                // Files
                'annexureFiles.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png',
            ]);

            Log::info('[RFQ STORE] Validation passed');

            DB::beginTransaction();

            // Create RFQ
            $rfq = RFQ::create([
                'rfq_no' => $request->rfqNo,
                'rfq_date' => $request->rfqDate,
                'vendor_id' => $request->vendor,
                'vendor_reference_no' => $request->venRefNo,
                'rfq_type' => $request->rfqType,
                'description' => $request->input('description_main'),
                'delivery_terms' => $request->deliveryTerms,
                'note' => $request->note,
            ]);

            Log::info("[RFQ STORE] RFQ created with ID: {$rfq->id}");

            // Store RFQ Items
            foreach ($request->item as $index => $item) {
                RFQItem::create([
                    'rfq_id' => $rfq->id,
                    'item' => $item,
                    'description' => $request->description[$index] ?? null,
                    'quantity' => $request->quantity[$index] ?? 0,
                    'uom' => $request->uom[$index] ?? '',
                    'required_by' => $request->requiredBy[$index] ?? null,
                ]);
            }

            Log::info('[RFQ STORE] RFQ items stored successfully');

            // Handle annexure file uploads
            if ($request->hasFile('annexureFiles')) {
                foreach ($request->file('annexureFiles') as $file) {
                    $path = $file->store("rfq_files/annexure", 'public');

                    RfqFile::create([
                        'rfq_id' => $rfq->id,
                        'file_path' => $path,
                        'file_name' => $file->getClientOriginalName(),
                        'file_type' => 'annexure',
                    ]);

                    Log::info("[RFQ STORE] Annexure file saved: {$path}");
                }
            }

            DB::commit();

            return redirect()->route('superadmin.purchasebom.rfq.rfqdetails')->with('success', 'RFQ created successfully.');

        } catch (\Illuminate\Validation\ValidationException $ve) {
            Log::error('[RFQ STORE] Validation failed:', $ve->errors());
            return back()->withErrors($ve->errors())->withInput();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('[RFQ STORE] Exception:', [
                'message' => $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.purchasebom.rfq.rfqdetails', compact('rfqs'));
    }

    public function view($id)
    {
        $rfq = Rfq::with(['customerInfo', 'rfqFiles', 'items.stockItem'])->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.purchasebom.rfq.view', compact('rfq', 'rawMaterialNames'));
    }

    public function edit($id)
    {
        $rfq = RFQ::with('customerInfo', 'rfqFiles', 'items')->findOrFail($id);
        $vendors = CustomerVendor::whereIn('company_role',['Vendor','Both'])->get();
        $rfqTypes = RfqType::all();
        $stock_items = StockItem::all();
        
        //dd($rfq->items);
        
        return view('superadmin.purchasebom.rfq.edit', compact('rfq', 'vendors', 'rfqTypes', 'stock_items'));
    }

    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' => 'nullable|numeric',
                'uom' => 'nullable|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.purchasebom.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 {
            Log::info("[RFQ UPDATE] Incoming request:", $request->all());
    
            $rfq = RFQ::findOrFail($id);
    
            $validated = $request->validate([
                'rfqNo' => 'required|string|unique:purchase_rfqs,rfq_no,' . $rfq->id,
                'rfqDate' => 'required|date',
                'vendor' => 'required|exists:customer_vendors,id',
                'venRefNo' => 'nullable|string',
                'rfqType' => 'required|string',
    
                'description_main' => 'nullable|string',
                'deliveryTerms' => 'nullable|string',
                'note' => 'nullable|string',
    
                'item' => 'nullable|array',
                'description' => 'nullable|array',
                'quantity' => 'nullable|array',
                'uom' => 'nullable|array',
                'requiredBy' => 'nullable|array',
    
                'annexureFiles.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png',
            ]);
    
            Log::info("[RFQ UPDATE] Validation passed");
    
            DB::beginTransaction();
    
            // Update main RFQ
            $rfq->update([
                'rfq_no' => $request->rfqNo,
                'rfq_date' => $request->rfqDate,
                'vendor_id' => $request->vendor,
                'vendor_reference_no' => $request->venRefNo,
                'rfq_type' => $request->rfqType,
                'description' => $request->input('description_main'),
                'delivery_terms' => $request->deliveryTerms,
                'note' => $request->note,
            ]);
    
            Log::info("[RFQ UPDATE] RFQ updated successfully for ID: {$rfq->id}");
    
            // Delete existing items to re-insert
            $rfq->items()->delete();
    
            if ($request->item) {
                foreach ($request->item as $index => $item) {
                    RFQItem::create([
                        'rfq_id' => $rfq->id,
                        'item' => $item,
                        'description' => $request->description[$index] ?? null,
                        'quantity' => $request->quantity[$index] ?? 0,
                        'uom' => $request->uom[$index] ?? '',
                        'required_by' => $request->requiredBy[$index] ?? null,
                    ]);
                }
                Log::info("[RFQ UPDATE] RFQ items updated");
            }
    
            // Upload new annexure files if any
            if ($request->hasFile('annexureFiles')) {
                foreach ($request->file('annexureFiles') as $file) {
                    $path = $file->store("rfq_files/annexure", 'public');
    
                    RfqFile::create([
                        'rfq_id' => $rfq->id,
                        'file_path' => $path,
                        'file_name' => $file->getClientOriginalName(),
                        'file_type' => 'annexure',
                    ]);
    
                    Log::info("[RFQ UPDATE] Annexure file uploaded: {$path}");
                }
            }
    
            DB::commit();
    
            return redirect()->route('superadmin.purchasebom.rfq.rfqdetails')->with('success', 'RFQ updated successfully.');
    
        } catch (\Illuminate\Validation\ValidationException $ve) {
            Log::error('[RFQ UPDATE] Validation failed:', $ve->errors());
            return back()->withErrors($ve->errors())->withInput();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('[RFQ UPDATE] Exception:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return back()->with('error', 'Something went wrong while updating the RFQ.');
        }
    }

    public function destroy_old($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('SuperAdmin RFQ Delete Error: ' . $e->getMessage());
            return response()->json(['message' => 'Failed to delete RFQ.'], 500);
        }
    }
    
    public function destroy($id)
    {
        try {
            $rfq = RFQ::with('customerInfo', 'rfqFiles', 'items')->findOrFail($id);
    
            // Delete associated files from storage and database
            if ($rfq->rfqFiles && $rfq->rfqFiles->count()) {
                foreach ($rfq->rfqFiles as $file) {
                    if (Storage::disk('public')->exists($file->file_path)) {
                        Storage::disk('public')->delete($file->file_path);
                    }
                    $file->delete();
                }
            }
    
            // Delete associated items
            if ($rfq->items && $rfq->items->count()) {
                foreach ($rfq->items as $item) {
                    $item->delete();
                }
            }
    
            // Finally, delete the main RFQ
            $rfq->delete();
    
            return response()->json(['message' => 'RFQ and related data deleted successfully.']);
    
        } catch (\Exception $e) {
            Log::error('[RFQ DESTROY] Exception: ' . $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 = RFQ::with(['customerInfo', 'rfqFiles', 'items.stockItem'])->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 = \App\Models\RawMaterial::whereIn('id', $rawMaterialIds)
                    ->pluck('rm_grade', 'id')
                    ->toArray();
            }
        }
    
        return view('superadmin.purchasebom.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.']);
    }


}
