<?php

namespace App\Http\Controllers\V1\Quotation;

use App\Http\Controllers\Controller;
use App\Models\RequestForQuotation;
use App\Models\RFQ_Details;
use App\Models\RFQExtraCharges;
use App\Models\RFQPayment;
use App\Models\RFQSupllierMappingProduct;
use App\Models\RFQSupplier;
use DB;
use Exception;
use File;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Image;
use Illuminate\Support\Facades\Mail;

class RequestForQuotationController extends Controller
{
    public function getRequestForQuotationNextId(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [

            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $response = 'RFQ' . '000' . (RequestForQuotation::query()->count() + 1);
            return $this->sendResponse(["next_id" => $response], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addRequestForQuotation(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'string',
                'bidding_start_date' => 'required|date',
                'bidding_end_date' => 'required|date',
                'delivery_date' => 'required|date',
                'file' => 'string',
                'reviewed_by_user_id' => 'numeric|numeric|exists:users,id',
                'tnc_id' => 'numeric|exists:terms_and_conditaions,id',
                'overall_comment' => 'nullable|string',
                'delivery_address_id' => 'required|numeric|exists:client_address,id',
                'attachment_file' => 'string',
//                'status' => ['required', Rule::in(['open', 'close','cancel'])],
                'products' => 'required|array',
                'products.*.requested_qty' => 'required|numeric|gt:0',
                'products.*.delivery_date' => 'nullable|date',
                'products.*.each_comment' => 'nullable|string',
                'supplier' => 'required|array',
                'supplier.*.client_id' => 'required|numeric|exists:clients,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newRequestForQuotation = new RequestForQuotation();
            $newRequestForQuotation->name = $request->name;
            $newRequestForQuotation->bidding_start_date = $request->bidding_start_date;
            $newRequestForQuotation->bidding_end_date = $request->bidding_end_date;
            $newRequestForQuotation->delivery_date = $request->delivery_date;
            $newRequestForQuotation->created_by_user_id = Auth::user()->id;
            if ($request->file != "") {
                if (!str_contains($request->file, "http")) {
                    $newRequestForQuotation->file = $this->saveImage($request->file, $request->bidding_start_date);
                }
            }
            $count = RequestForQuotation::count() + 1;
            $reference_no = 'RFQ' . str_pad($count, 4, '0', STR_PAD_LEFT);
            $newRequestForQuotation->reference_no = $reference_no;
            $newRequestForQuotation->tnc_id = $request->tnc_id;
            $newRequestForQuotation->overall_comment = $request->overall_comment;
            $newRequestForQuotation->delivery_address_id = $request->delivery_address_id;
            if ($request->attachment_file != "") {
                if (!str_contains($request->attachment_file, "http")) {
                    $newRequestForQuotation->attachment_file = $this->saveImage($request->attachment_file, $request->bidding_start_date);
                }
            }
            $newRequestForQuotation->status = 'open';
            $newRequestForQuotation->save();
            foreach ($request->products as $eachProduct) {
                $newRFQ_Details = new RFQ_Details();
                $newRFQ_Details->rfq_id = $newRequestForQuotation->id;
                $newRFQ_Details->product_id = $eachProduct['product_id'];
                $newRFQ_Details->requested_qty = $eachProduct['requested_qty'];
                $newRFQ_Details->delivery_date = $eachProduct['delivery_date'];
                $newRFQ_Details->each_comment = $eachProduct['each_comment'];
                $newRFQ_Details->save();
            }
            foreach ($request->supplier as $eachSupplier) {
                $newRFQSupplier = new RFQSupplier();
                $newRFQSupplier->rfq_id = $newRequestForQuotation->id;
                $newRFQSupplier->client_id = $eachSupplier['client_id'];
                $newRFQSupplier->save();
            }
            return $this->sendResponse($newRequestForQuotation->id, 'Request for quotation created successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function saveImage($image, $productName)
    {
        $imageName = $productName . '-' . rand(100, 9999) . '.webp';

        $destinationPath = public_path('productimage\\' . $imageName);
        if (env('APP_ENV') == 'prod') {
            $destinationPath = public_path('productimage/' . $imageName);
        }
        $img = Image::make(file_get_contents($image))
            ->resize(300, null)
            ->save($destinationPath, 80, 'webp');

        return '/productimage/' . $imageName;
    }
    public function editStatusInRequestForQuotation(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:request_for_quotations,id',
                'status' => [Rule::in(['open', 'close', 'cancel'])],
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editStatus = RequestForQuotation::query()
                ->where('id', $request->id)->first();
            if ($request->has('status')) {
                $editStatus->status = $request->status;
            }
            $editStatus->save();
            return $this->sendResponse([], 'Status update successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function editRequestForQuotation(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'integer|exists:request_for_quotations,id',
                'client_id' => 'numeric|exists:clients,id',
                'name' => 'string',
                'bidding_start_date' => 'date',
                'bidding_end_date' => 'date',
                'delivery_date' => 'date',
                'file' => 'nullable|string',
                'reviewed_by_user_id' => 'numeric|numeric|exists:users,id',
                'tnc_id' => 'numeric|exists:terms_and_conditaions,id',
                'overall_comment' => 'nullable|string',
                'delivery_address_id' => 'numeric|exists:client_address,id',
                'attachment_file' => 'nullable|string',
                'status' => [Rule::in(['open', 'close', 'cancel'])],
                'products' => 'array',
                'products.*.requested_qty' => 'numeric|gt:0',
                'products.*.delivery_date' => 'nullable|date',
                'products.*.each_comment' => 'nullable|string',
                'supplier' => 'array',
                'supplier.*.client_id' => 'numeric|exists:clients,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editRequestForQuotation = RequestForQuotation::query()->where('id', $request->id)->first();
            if ($request->has('client_id')) {
                $editRequestForQuotation->client_id = $request->client_id;
            }
            if ($request->has('name')) {
                $editRequestForQuotation->name = $request->name;
            }
            if ($request->has('bidding_start_date')) {
                $editRequestForQuotation->bidding_start_date = $request->bidding_start_date;
            }
            if ($request->has('bidding_end_date')) {
                $editRequestForQuotation->bidding_end_date = $request->bidding_end_date;
            }
            if ($request->has('delivery_date')) {
                $editRequestForQuotation->delivery_date = $request->delivery_date;
            }
            if ($request->file != "") {
                if (!str_contains($request->file, "http")) {
                    $editRequestForQuotation->file = $this->saveImage($request->file, $request->bidding_start_date);
                }
            }
            // $editRequestForQuotation->file=$this->saveImage($request->file,$request->bidding_start_date);
            if ($request->has('reviewed_by_user_id')) {
                $editRequestForQuotation->reviewed_by_user_id = $request->reviewed_by_user_id;
            }
            if ($request->has('tnc_id')) {
                $editRequestForQuotation->tnc_id = $request->tnc_id;
            }
            if ($request->has('overall_comment')) {
                $editRequestForQuotation->overall_comment = $request->overall_comment;
            }
            if ($request->has('delivery_address_id')) {
                $editRequestForQuotation->delivery_address_id = $request->delivery_address_id;
            }
            if ($request->attachment_file != "") {
                if (!str_contains($request->attachment_file, "http")) {
                    $editRequestForQuotation->attachment_file = $this->saveImage($request->attachment_file, $request->bidding_start_date);
                }
            }
            //    $editRequestForQuotation->attachment_file=$this->saveImage($request->attachment_file,$request->bidding_start_date);
            if ($request->has('is_accepted')) {
                $editRequestForQuotation->is_accepted = $request->is_accepted;
            }
            if ($request->has('status')) {
                $editRequestForQuotation->status = $request->status;
            }
            $editRequestForQuotation->save();
            RFQ_Details::where('rfq_id', $editRequestForQuotation->id)->delete();
            foreach ($request->products as $eachProduct) {
                $newRFQ_Details = new RFQ_Details();
                $newRFQ_Details->rfq_id = $editRequestForQuotation->id;
                $newRFQ_Details->product_id = $eachProduct['product_id'];
                $newRFQ_Details->requested_qty = $eachProduct['requested_qty'];
                $newRFQ_Details->delivery_date = $eachProduct['delivery_date'];
                $newRFQ_Details->each_comment = $eachProduct['each_comment'];
                $newRFQ_Details->save();
            }
            foreach ($request->supplier as $eachSupplier) {
                $newRFQSupplier = new RFQSupplier();
                $newRFQSupplier->rfq_id = $editRequestForQuotation->id;
                $newRFQSupplier->client_id = $eachSupplier['client_id'];
                $newRFQSupplier->save();
            }
            return $this->sendResponse([], 'Request for quotation updated successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getTrace(), 413);
        }
    }
    public function getRequestForQuotation(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'pageNo' => 'numeric',
                'limit' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors(), 400);
            }
            $query = RequestForQuotation::query()->with(['created_by_user', 'reviewed_by_user', 'tnc', 'indirect_tax', 'delivery_address']);
            if ($request->has('reference_no')) {
                $query = $query->where('reference_no', 'like', '%' . $request->reference_no . '%');
            }
            if ($request->has('start_date') && $request->has('end_date')) {
                $query = $query->whereDate('created_at', '>=', $request->start_date)->whereDate('created_at', '<=', $request->end_date);
            }
            if ($request->has('bidding_start_date')) {
                $query = $query->whereDate('bidding_start_date', '=', $request->bidding_start_date);
            }
            if ($request->has('bidding_end_date')) {
                $query = $query->whereDate('bidding_end_date', '=', $request->bidding_end_date);
            }
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $data = $query->orderBy('id', 'DESC')->get();
            if ($request->has('created_date_sort')) {
                if ($request->created_date_sort) {
                    $query = $query->orderBy('created_at', 'ASC');
                } else {
                    $query = $query->orderBy('created_at', 'DESC');
                }
            }
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = RFQ_Details::query()->where('rfq_id', $user['id'])
                        ->with(['products'])->get();
                    $user['request_for_quotation_details'] = $product;
                }
            }
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = RFQSupplier::query()->where('rfq_id', $user['id'])
                        ->with(['client', 'client.client_address', 'payment_term'])->get();
                    $user['request_for_quotation_details'] = $product;
                }
            }
            if (count($data) > 0) {
                $response['request_for_quotation'] = $data;
                $response['count'] = $count;
                return $this->sendResponse($response, 'Data Fetched Successfully', true);
            } else {
                return $this->sendResponse('No Data Available', [], false);
            }
        } catch (Exception $e) {
            return $this->sendError($e->getMessage(), $e->getTrace(), 500);
        }
    }
    public function deleteRequestForQuotationById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:request_for_quotations,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteRequestForQuotation = RequestForQuotation::query()
                ->where('id', $request->id)->first();
            $deleteRequestForQuotation->delete();
            return $this->sendResponse([], 'Request for quotation deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getRequestForQuotationId(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:request_for_quotations,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getRequestForQuotation = RequestForQuotation::query()->where('id', $request->id)->with(['created_by_user', 'reviewed_by_user', 'tnc', 'indirect_tax', 'delivery_address'])->first();
            if ($getRequestForQuotation['id'] != null) {
                $product = RFQ_Details::query()->where('rfq_id', $getRequestForQuotation['id'])
                    ->with(['products'])->get();
                $getRequestForQuotation['request_for_quotation_details'] = $product;
            }
            if ($getRequestForQuotation['id'] != null) {
                $product = RFQSupplier::query()->where('rfq_id', $getRequestForQuotation['id'])
                    ->with(['client', 'client.client_address'])->get();
                $getRequestForQuotation['request_for_quotation_Supplier'] = $product;
            }
            if ($getRequestForQuotation['id'] != null) {
                $product = RFQSupplier::query()->where('rfq_id', $getRequestForQuotation['id'])
                    ->with(['client', 'client.client_address', 'payment_term'])->get();
                $user['request_for_quotation_details'] = $product;
            }
            return $this->sendResponse(['request_for_quotation' => $getRequestForQuotation], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addRequestForQuotationSupplier(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'delivery_date' => 'nullable|date',
                'kind_attention' => 'nullable|string',
                'payment_term_id' => 'nullable|exists:payment_terms,id',
                'overall_comment' => 'string',
                'is_draftsave' => 'nullable|boolean',
                'products' => 'required|array',
                'products.*.quoted_qty' => 'required|numeric|gt:0',
                'products.*.total_tax' => 'nullable|integer|gt:0',
                'products.*.each_comment' => 'nullable|string',
                'products.*.modified_amount' => 'nullable|numeric|gt:0',
                'products.*.discount' => 'nullable|numeric',
                'products.*.total_amount' => 'nullable|numeric',
                'products.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'products.*.delivery_date' => 'nullable|date',
                'amount' => 'nullable|numeric|gt:0',
                'charges' => 'array',
                'charges.*.description' => 'nullable|string',
                'charges.*.total_amount' => 'nullable|gt:0',
                'charges.*.indirect_tax_id' => 'nullable|exists:indirect_tax,id',
                'charges.*.total_tax' => 'nullable|gt:0',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newRFQSupplier = RFQSupplier::query()->where('rfq_id', $request->rfq_id)
                ->where('client_id', $request->client_id)
                ->first();
            if ($request->has('delivery_date')) {
                $newRFQSupplier->delivery_date = $request->delivery_date;
            }
            if ($request->has('kind_attention')) {
                $newRFQSupplier->kind_attention = $request->kind_attention;
            }
            if ($request->has('payment_term_id')) {
                $newRFQSupplier->payment_term_id = $request->payment_term_id;
            }
            if ($request->has('overall_comment')) {
                $newRFQSupplier->overall_comment = $request->overall_comment;
            }
            $count = RFQSupplier::count() + 1;
            $reference_no = 'RFQS' . str_pad($count, 4, '0', STR_PAD_LEFT);
            $newRFQSupplier->supplier_reference_no = $reference_no;

            if ($request->has('is_draftsave')) {
                $newRFQSupplier->is_draftsave = $request->is_draftsave;
            }
            $newRFQSupplier->save();
            foreach ($request->products as $eachProduct) {
                $newRFQSupllierMappingProduct = new RFQSupllierMappingProduct();
                $newRFQSupllierMappingProduct->rfq_supplier_id = $newRFQSupplier->id;
                $newRFQSupllierMappingProduct->product_id = $eachProduct['product_id'];
                $newRFQSupllierMappingProduct->quoted_qty = $eachProduct['quoted_qty'];
                $newRFQSupllierMappingProduct->total_tax = $eachProduct['total_tax'];
                $newRFQSupllierMappingProduct->comment = $eachProduct['comment'];
                $newRFQSupllierMappingProduct->modified_amount = $eachProduct['modified_amount'];
                $totalamount = $newRFQSupllierMappingProduct->quoted_qty * $newRFQSupllierMappingProduct->modified_amount;
                $newRFQSupllierMappingProduct->total_before_tax = $totalamount;
                $newRFQSupllierMappingProduct->discount = $eachProduct['discount'];
                $newRFQSupllierMappingProduct->total_amount = $eachProduct['total_amount'];
                $newRFQSupllierMappingProduct->indirect_tax_id = $eachProduct['indirect_tax_id'];
                $newRFQSupllierMappingProduct->delivery_date = $eachProduct['delivery_date'];
                $newRFQSupllierMappingProduct->save();
            }
            $newRFQPayment = new RFQPayment();
            $newRFQPayment->rfq_supplier_id = $newRFQSupplier->id;
            $newRFQPayment->amount = $request->amount;
            if ($newRFQPayment->amount > $newRFQSupllierMappingProduct->total_amount) {
                return $this->sendResponse([], 'The amount cannot be greater than the total amount', false);
            }
            $newRFQPayment->save();
            if (is_array($request->charges) || is_object($request->charges)) {
                foreach ($request->charges as $eachcharges) {
                    $charges = new RFQExtraCharges();
                    $charges->rfq_supplier_id = $newRFQSupplier->id;
                    $charges->description = $eachcharges['description'];
                    $charges->total_amount = $eachcharges['total_amount'];
                    $charges->indirect_tax_id = $eachcharges['indirect_tax_id'];
                    $charges->total_tax = $eachcharges['total_tax'];
                    $charges->save();
                }
            }
            return $this->sendResponse([], 'Request for quotation supplier created successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getTrace(), 413);
        }
    }
    //   public function editRFQSupplier(Request $request): JsonResponse
    //   {

    //       try {
    //           $validator = Validator::make($request->all(), [
    //               'id' => 'required|integer|exists:request_for_quotations,id',
    //               'rfq_id' => 'required|numeric|exists:clients,id',
    //               'client_id' => 'required|numeric|exists:clients,id',
    //               'additional_charges_amount'=>'required|integer|gt:0',
    //               'total_before_tax'=>'required|integer',
    //               'total_tax'=>'required|integer',
    //               'grant_total' => 'required|integer',
    //               'overall_comment' => 'string',
    //               'products' => 'required|array',
    //               'products.*.quoted_qty' => 'required|numeric|gt:0',
    //               'products.*.total_before_tax' => 'required|numeric|gt:0',
    //               'products.*.total_tax' => 'nullable|intger|gt:0',
    //               'products.*.each_comment' => 'nullable|string',
    //               'products.*.price' => 'required|numeric|gt:0',
    //               'products.*.discount' => 'required|numeric',
    //               'payment' => 'required|array',
    //               'payment.*.amount' => 'required|numeric|gt:0',
    //               'payment.*.is_really_given' => 'required|numeric|boolean',
    //           ]);
    //           if ($validator->fails()) {
    //               return $this->sendError('Validation Error.', $validator->errors());
    //           }

    //           $editRFQSupplier = RFQSupplier::query()->where('rfq_id',$request->rfq_id)
    //           ->where('client_id',$request->client_id)
    //           ->first();
    //           if ($request->has('client_id')) {
    //               $editRFQSupplier->client_id = $request->client_id;
    //           }
    //           if ($request->has('name')) {
    //               $editRFQSupplier->name = $request->name;
    //           }
    //           if ($request->has('bidding_start_date')) {
    //               $editRFQSupplier->bidding_start_date = $request->bidding_start_date;
    //           }
    //           if ($request->has('bidding_end_date')) {
    //               $editRFQSupplier->bidding_end_date = $request->bidding_end_date;
    //           }
    //           if ($request->has('delivery_date')) {
    //               $editRFQSupplier->delivery_date = $request->delivery_date;
    //           }
    //          // $editRFQSupplier->file=$this->saveImage($request->file,$request->bidding_start_date);
    //           if ($request->has('reviewed_by_user_id')) {
    //               $editRFQSupplier->reviewed_by_user_id = $request->reviewed_by_user_id;
    //           }
    //           if ($request->has('tnc_id')) {
    //               $editRFQSupplier->tnc_id = $request->tnc_id;
    //           }
    //           if ($request->has('overall_comment')) {
    //               $editRFQSupplier->overall_comment = $request->overall_comment;
    //           }
    //           if ($request->has('delivery_address_id')) {
    //               $editRFQSupplier->delivery_address_id = $request->delivery_address_id;
    //           }
    //       //    $editRFQSupplier->attachment_file=$this->saveImage($request->attachment_file,$request->bidding_start_date);
    //           if ($request->has('is_accepted')) {
    //               $editRFQSupplier->is_accepted = $request->is_accepted;
    //           }
    //           $editRFQSupplier->save();
    //           RFQ_Details::where('rfq_id', $editRFQSupplier->id)->delete();
    //          foreach ($request->products as $eachProduct) {
    //           $newRFQ_Details = new RFQ_Details();
    //           $newRFQ_Details->rfq_id = $editRFQSupplier->id;
    //           $newRFQ_Details->product_id = $eachProduct['product_id'];
    //           $newRFQ_Details->requested_qty = $eachProduct['requested_qty'];
    //           $newRFQ_Details->delivery_date = $eachProduct['delivery_date'];
    //           $newRFQ_Details->each_comment = $eachProduct['each_comment'];
    //           $newRFQ_Details->save();
    //       }

    //           return $this->sendResponse([], 'Request for quotation updated successfully', true);
    //       } catch (Exception $e) {
    //           return $this->sendError('Something went wrong', $e->getTrace(), 413);
    //       }
    //   }
    public function getRFQSupplier(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'pageNo' => 'numeric',
                'limit' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors(), 400);
            }
            $query = RFQSupplier::query()->with(['request_for_quotation', 'client', 'client.client_address']);
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $data = $query->orderBy('id', 'DESC')->get();
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = RFQSupllierMappingProduct::query()->where('rfq_supplier_id', $user['id'])
                        ->with(['products', 'indirect_tax'])->get();
                    $user['request_for_quotation_supplier_mapping_products'] = $product;
                }
            }
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = RFQPayment::query()->where('rfq_supplier_id', $user['id'])
                        ->get();
                    $user['request_for_quotation_payment'] = $product;
                }
            }
            if (count($data) > 0) {
                $response['request_for_quotation_supplier'] = $data;
                $response['count'] = $count;
                return $this->sendResponse($response, 'Data Fetched Successfully', true);
            } else {
                return $this->sendResponse('No Data Available', [], false);
            }
        } catch (Exception $e) {
            return $this->sendError($e->getMessage(), $e->getTrace(), 500);
        }
    }
    public function getRFQSupplierByRFQId(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'pageNo' => 'numeric',
                'limit' => 'numeric',
                'rfq_id' => 'numeric',
                'client_id'=>'nullable|exists:clients,id'
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors(), 400);
            }
            $query = RFQSupplier::query()->where('rfq_id', $request->rfq_id)
                ->with(['request_for_quotation', 'client', 'client.client_address', 'payment_term']);
                if ($request->has('client_id')) {
                    $query->where('client_id', $request->client_id);
                }
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $data = $query->orderBy('id', 'DESC')->get();
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = RFQSupllierMappingProduct::query()->where('rfq_supplier_id', $user['id'])
                        ->with(['products', 'indirect_tax'])->get();
                    $user['request_for_quotation_supplier_mapping_products'] = $product;
                }
            }
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = RFQExtraCharges::query()->where('rfq_supplier_id', $user['id'])->with(['indirect_tax'])
                        ->get();
                    $user['request_for_quotation_supplier_extra_charges'] = $product;
                }
            }
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = RFQPayment::query()->where('rfq_supplier_id', $user['id'])
                        ->get();
                    $user['request_for_quotation_payment'] = $product;
                }
            }
            if (count($data) > 0) {
                $response['request_for_quotation_supplier'] = $data;
                $response['count'] = $count;
                return $this->sendResponse($response, 'Data Fetched Successfully', true);
            } else {
                return $this->sendResponse('No Data Available', [], false);
            }
        } catch (Exception $e) {
            return $this->sendError($e->getMessage(), $e->getTrace(), 500);
        }
    }
    public function getRFQSupplierByRFQIdExportInExcel(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'pageNo' => 'numeric',
                'limit' => 'numeric',
                'rfq_id' => 'numeric'
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors(), 400);
            }
            $query = RFQSupplier::query()->where('rfq_id', $request->rfq_id)
                ->with(['request_for_quotation', 'client', 'client.client_address', 'payment_term']);
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $data = $query->orderBy('id', 'DESC')->get();
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = RFQSupllierMappingProduct::query()->where('rfq_supplier_id', $user['id'])
                        ->with(['products', 'indirect_tax'])->get();
                    $user['request_for_quotation_supplier_mapping_products'] = $product;
                }
            }
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = RFQExtraCharges::query()->where('rfq_supplier_id', $user['id'])->with(['indirect_tax'])
                        ->get();
                    $user['request_for_quotation_supplier_extra_charges'] = $product;
                }
            }
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = RFQPayment::query()->where('rfq_supplier_id', $user['id'])
                        ->get();
                    $user['request_for_quotation_payment'] = $product;
                }
            }
            if (count($data) > 0) {
                $response['request_for_quotation_supplier'] = $data;
                $response['count'] = $count;
                $path = public_path() . '/uploads';
                if (!File::exists($path)) {
                    File::makeDirectory($path);
                }
                $fileName = time() . '-' . 'result' . '.csv';
                $file = fopen($path . $fileName, 'w');
                $columns = array('RFQ Details', 'item details', 'supplier 1', 'supplier 2', 'supplier 3');
                fputcsv($file, $columns);
                foreach ($data as $task) {
                    $row['RFQ Details'] = $task['rfq_id'];
                    $row['item details'] = $task['client_id'];
                    $row['supplier 1'] = $task['supplier_reference_no'];
                    $row['supplier 2'] = $task['overall_comment'];
                    $row['supplier 3'] = $task['rfq_supplier_id'];
                    fputcsv($file, array($row['RFQ Details'], $row['item details'], $row['supplier 1'], $row['supplier 2'], $row['supplier 3']));
                }
                fclose($file);
                $fileURL = env('RESULT') . '/uploads/' . $fileName;
                return $this->sendResponse([], 'CSV file save in public', $fileURL);
            } else {
                return $this->sendResponse('No Data Available', [], false);
            }
        } catch (Exception $e) {
            return $this->sendError($e->getMessage(), $e->getTrace(), 500);
        }
    }
    public function deleteRFQSupplierById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:rfq_suppliers,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteRFQSupplier = RFQSupplier::query()
                ->where('id', $request->id)->first();
            $deleteRFQSupplier->delete();
            return $this->sendResponse([], 'Request for quotation supplier deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getRFQSupplierById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:rfq_suppliers,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getRFQSupplier = RFQSupplier::query()->where('id', $request->id)->with(['request_for_quotation', 'client', 'client.client_address'])->first();
            if ($getRFQSupplier['id'] != null) {
                $product = RFQSupllierMappingProduct::query()->where('rfq_supplier_id', $getRFQSupplier['id'])
                    ->with(['products'])->get();
                $getRFQSupplier['request_for_quotation_supplier_mapping_products'] = $product;
            }
            if ($getRFQSupplier['id'] != null) {
                $product = RFQPayment::query()->where('rfq_supplier_id', $getRFQSupplier['id'])
                    ->get();
                $getRFQSupplier['request_for_quotation_payment'] = $product;
            }
            return $this->sendResponse(['request_for_quotation_supplier' => $getRFQSupplier], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function sendQuotation(Request $request)
{
    $validator = Validator::make($request->all(), [
        'quotation_id' => 'required|numeric',
        'emails' => 'nullable|array',
        'emails.*' => 'nullable|email',
        'pdf_file' => 'required|mimes:pdf',
    ]);
    if ($validator->fails()) {
        return $this->sendError('Validation Error.', $validator->errors());
    }
    $quotation = RequestForQuotation::with('client')->findOrFail($request->quotation_id);
    $client_email = $quotation->client->company_email;
    $to_email = $client_email;
    if (!empty($request->emails)) {
        $valid_emails = array_filter($request->emails, function ($email) {
            return filter_var($email, FILTER_VALIDATE_EMAIL);
        });
        $additional_emails = implode(',', $valid_emails);
        $to_email .= ',' . $additional_emails;
    }
    $to_email = explode(',', $to_email);
    $pdf_path = $request->pdf_file->store('pdfs');
    $data = ['pdf_path' => $pdf_path];
    Mail::send('emails.sendQuotation', $data, function ($message) use ($to_email, $pdf_path) {
        $message->to($to_email)
            ->subject('Quotation');
        $message->attach(storage_path('app/' . $pdf_path));
        $message->from(env('MAIL_FROM_ADDRESS'), 'NEURO ERP System Mail');
    });
    return $this->sendResponse([], 'Quotation Sent Successfully', true);
}
}







