<?php
namespace App\Http\Controllers\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\Models\CustomerVendor;
use App\Models\PurchaseQuotation;
use App\Models\PurchaseQuotationItem;
use App\Models\StockItem;
use App\Models\PurchaseRFQ;

class PurchaseQuotationController extends Controller
{
    // List all quotations
    public function list()
    {
        $quotations = PurchaseQuotation::withCount('items')->orderByDesc('id')->get();
        return view('v1.purchasequotation.list', compact('quotations'));
    }

    // Show create or edit form
    public function index($id = null)
    {
        $quotation = null;
         if ($id) {
            $quotation = PurchaseQuotation::with(['items','items.stockItem'])->findOrFail($id);
        }
        //quotation_no will be in for UEPL/P/QT/0001 quotation_no will be in the format of UEPL/P/QT/0001 we need extract the number from the quotation_no
        // get next quotation_no
        $nextQuotationNo = PurchaseQuotation::max('quotation_no');
        $nextQuotationNo = explode('/', $nextQuotationNo);
        $nextQuotationNo = count($nextQuotationNo) > 3 ? $nextQuotationNo[3] + 1 : 1;
        $newQuotationNo = 'UEPL/P/QT/' . str_pad($nextQuotationNo, 4, '0', STR_PAD_LEFT);
        
        $vendors = CustomerVendor::where('company_role', 'Vendor')->get();
        $stockItems = StockItem::all();
        $purchaseRfqs =  $id ? collect() : PurchaseRFQ::where('status', 'approved')
        ->with('quotation','items','items.stockItem')
        ->whereDoesntHave('quotation')
        ->get();
        
        return view('v1.purchasequotation.index', compact('quotation', 'newQuotationNo', 'vendors', 'stockItems', 'purchaseRfqs'));
    }

    // Store new quotation
    public function store(Request $request)
    {
        $data = $request->validate([
            'quotation_no' => 'required|unique:purchase_quotations,quotation_no',
            'quotation_date' => 'required|date',
            'vendor_name' => 'required|string',
            'vendor_id' => 'nullable|integer',
            'address' => 'nullable|string',
            'gst' => 'nullable|string',
            'phone' => 'nullable|string',
            'email' => 'nullable|string',
            'rfq_no' => 'nullable|string',
            'rfq_date' => 'nullable|date',
            'vendor_reference_no' => 'nullable|string',
            'delivery_terms' => 'nullable|string',
            'additional_charges' => 'nullable|string',
            'part_no' => 'nullable|string',
            'project_material_no' => 'nullable|string',
            'drawing_no' => 'nullable|string',
            'drawing_rev' => 'nullable|string',
            'quantity' => 'nullable|numeric',
            'quantity_uom' => 'nullable|string',
            'description' => 'nullable|string',
            'product_type' => 'nullable|string',
            'note' => 'nullable|string',
            'sub_total' => 'nullable|numeric',
            'discount' => 'nullable|numeric',
            'round_up' => 'nullable|numeric',
            'grand_total' => 'nullable|numeric',
            'inr_in_words' => 'nullable|string',
    
            'items' => 'required|array|min:1',
            'items.*.stock_item' => 'required|exists:stock_items,id',
            'items.*.description' => 'nullable|string',
            'items.*.quantity' => 'nullable|numeric',
            'items.*.uom' => 'nullable|string',
            'items.*.supply_lead_time' => 'nullable|string',
            'items.*.unit_rate' => 'nullable|numeric',
            'items.*.tds' => 'nullable|numeric',
            'items.*.discount' => 'nullable|numeric',
            'items.*.value' => 'nullable|numeric',
            'items.*.sgst' => 'nullable|numeric',
            'items.*.cgst' => 'nullable|numeric',
            'items.*.igst' => 'nullable|numeric',
            'items.*.amount' => 'nullable|numeric',
    
            'vendorqtFiles' => 'nullable|array',
            'vendorqtFiles.*' => 'file|mimes:pdf,jpg,jpeg,png|max:2048',
        ]);
    
        DB::transaction(function () use ($data) {
            $quotation = PurchaseQuotation::create($data);
    
            foreach ($data['items'] as $item) {
                $item['purchase_quotation_id'] = $quotation->id;
                $item['stock_item_name'] = StockItem::findOrFail($item['stock_item'])->item_name;
                PurchaseQuotationItem::create($item);
            }
    
            if (request()->hasFile('vendorqtFiles')) {
                foreach (request()->file('vendorqtFiles') as $file) {
                    $path = $file->store('vendor_quotations', 'public');
    
                    \App\Models\PurchaseQuotationFile::create([
                        'purchase_quotation_id' => $quotation->id,
                        'file_path' => $path,
                        'file_name' => $file->getClientOriginalName(),
                    ]);
                }
            }
        });
    
        return redirect()->route('superadmin.purchasequotation.list')
            ->with('success', 'Purchase Quotation created successfully!');
    }

    // Show a single quotation
    public function show($id)
    { 
        
        $quotation = PurchaseQuotation::with(['items.stockItem','files'])->findOrFail($id);
        return view('v1.purchasequotation.show', compact('quotation'));
    }
    
    
    // public function rfq_Files()
    // {
    // return $this->hasMany(PurchaseRFQFile::class, 'purchase_rfq_id');
    // }
    
    public function update(Request $request, $id)
    {
        $data = $request->validate([
            'quotation_no' => 'required|unique:purchase_quotations,quotation_no,' . $id,
            'quotation_date' => 'required|date',
            'vendor_name' => 'required|string',
            'vendor_id' => 'nullable|integer',
            'address' => 'nullable|string',
            'gst' => 'nullable|string',
            'phone' => 'nullable|string',
            'email' => 'nullable|string',
            'rfq_no' => 'nullable|string',
            'rfq_date' => 'nullable|date',
            'vendor_reference_no' => 'nullable|string',
            'delivery_terms' => 'nullable|string',
            'additional_charges' => 'nullable|string',
            'part_no' => 'nullable|string',
            'project_material_no' => 'nullable|string',
            'drawing_no' => 'nullable|string',
            'drawing_rev' => 'nullable|string',
            'quantity' => 'nullable|numeric',
            'quantity_uom' => 'nullable|string',
            'description' => 'nullable|string',
            'product_type' => 'nullable|string',
            'note' => 'nullable|string',
            'sub_total' => 'nullable|numeric',
            'discount' => 'nullable|numeric',
            'round_up' => 'nullable|numeric',
            'grand_total' => 'nullable|numeric',
            'inr_in_words' => 'nullable|string',
    
            'items' => 'required|array|min:1',
            'items.*.stock_item' => 'required|exists:stock_items,id',
            'items.*.description' => 'nullable|string',
            'items.*.quantity' => 'nullable|numeric',
            'items.*.uom' => 'nullable|string',
            'items.*.supply_lead_time' => 'nullable|string',
            'items.*.unit_rate' => 'nullable|numeric',
            'items.*.tds' => 'nullable|numeric',
            'items.*.discount' => 'nullable|numeric',
            'items.*.value' => 'nullable|numeric',
            'items.*.sgst' => 'nullable|numeric',
            'items.*.cgst' => 'nullable|numeric',
            'items.*.igst' => 'nullable|numeric',
            'items.*.amount' => 'nullable|numeric',
    
            'vendorqtFiles' => 'nullable|array',
            'vendorqtFiles.*' => 'file|mimes:pdf,jpg,jpeg,png|max:2048',
        ]);
    
        DB::transaction(function () use ($data, $id) {
            $quotation = PurchaseQuotation::findOrFail($id);
    
            // Update quotation main fields
            $quotation->update($data);
    
            // Delete and recreate items
            $quotation->items()->delete();
            foreach ($data['items'] as $item) {
                $item['purchase_quotation_id'] = $quotation->id;
                $item['stock_item_name'] = StockItem::findOrFail($item['stock_item'])->item_name;
                PurchaseQuotationItem::create($item);
            }
    
            // Handle new file uploads (if any)
            if (request()->hasFile('vendorqtFiles')) {
                foreach (request()->file('vendorqtFiles') as $file) {
                    $path = $file->store('vendor_quotations', 'public');
    
                    \App\Models\PurchaseQuotationFile::create([
                        'purchase_quotation_id' => $quotation->id,
                        'file_path' => $path,
                        'file_name' => $file->getClientOriginalName(),
                    ]);
                }
            }
        });
    
        return redirect()->route('superadmin.purchasequotation.list')
            ->with('success', 'Purchase Quotation updated successfully!');
    }


    // Delete a quotation
    public function destroy($id)
    {
        try {
            $quotation = PurchaseQuotation::findOrFail($id);

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

            // Delete items
            $quotation->items()->delete();

            // Delete quotation
            $quotation->delete();

            return response()->json(['success' => true, 'message' => 'Purchase Quotation deleted successfully.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Failed to delete quotation.', 'error' => $e->getMessage()], 500);
        }
    }


    // Print a quotation
    public function print($id)
    {
        $quotation = PurchaseQuotation::with(['items.stockItem'])->findOrFail($id);
        return view('v1.purchasequotation.print', compact('quotation'));
    }

    // Approve a quotation
    public function approve($id)
    {
        $quotation = PurchaseQuotation::findOrFail($id);
        $quotation->status = 'approved';
        $quotation->save();
        return redirect()->route('superadmin.purchasequotation.list')->with('success', 'Purchase Quotation approved successfully!');
    }

    // Reject a quotation
    public function reject($id)
    {
        $quotation = PurchaseQuotation::findOrFail($id);
        $quotation->status = 'rejected';
        $quotation->save();
        return redirect()->route('superadmin.purchasequotation.list')->with('success', 'Purchase Quotation rejected successfully!');
    }
    public function stockItem()
    {

    return $this->belongsTo(StockItem::class, 'stock_item');
    }
    
    public function deleteFile(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:purchase_quotation_files,id',
        ]);
    
        $file = \App\Models\PurchaseQuotationFile::findOrFail($request->id);
    
        if (Storage::disk('public')->exists($file->file_path)) {
            Storage::disk('public')->delete($file->file_path);
        }
    
        $file->delete();
    
        return response()->json(['success' => true]);
    }


}