<?php

namespace App\Http\Controllers;

use App\Models\DocumentLibrary;
use App\Models\TenderEntry;
use App\Models\VendInvParameter;
use App\Models\WorkAllocationBook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class TenderEntryController extends Controller
{

public function index(Request $request)
    {
        $query = TenderEntry::with(['department', 'ledger', 'budgetHead', 'tendertype']);

        if ($request->filled('Dpt_id')) {
            $query->where('Dpt_id', $request->Dpt_id);
        }

        if ($request->filled('Lg_Id')) {
            $query->where('Lg_Id', $request->Lg_Id);
        }

        if ($request->filled('Bh_Id')) {
            $query->where('Bh_Id', $request->Bh_Id);
        }

        if ($request->filled('search')) {

            $search = $request->search;

            $query->where(function ($q) use ($search) {

                $q->where('Description', 'LIKE', "%$search%")
                    ->orWhere('Proposal_Amount', 'LIKE', "%$search%")
                    ->orWhere('Approved_Amount', 'LIKE', "%$search%")

                    ->orWhereHas('department', function ($q2) use ($search) {
                        $q2->where('Dpt_Name', 'LIKE', "%{$search}%")
                           ->orWhere('Dpt_Desc', 'LIKE', "%{$search}%");
                    })

                    ->orWhereHas('ledger', function ($q3) use ($search) {
                        $q3->where('Lg_Name', 'LIKE', "%{$search}%");
                    })

                    ->orWhereHas('budgetHead', function ($q4) use ($search) {
                        $q4->where('Gr_Cd', 'LIKE', "%{$search}%")
                           ->orWhere('Gr_Nm', 'LIKE', "%{$search}%");
                    })

                    ->orWhereHas('tendertype', function ($q5) use ($search) {
                        $q5->where('TnT_Name', 'LIKE', "%{$search}%");
                    });

            });
        }

        $entries = $query->orderBy('TE_Id', 'desc')->paginate($request->get('per_page', 10));

        return response()->json([
            'success' => true,
            'data' => $entries
        ]);
    }


  public function getBranchesLedgers()
{
    try {

        $branches = TenderEntry::with(['department', 'ledger'])
            ->get()
            ->groupBy('Dpt_id')
            ->map(function ($items) {

                $department = $items->first()->department;

                return [
                    'department' => $department,

                    'ledgers' => $items->unique('Lg_Id')
                        ->map(function ($row) {
                            return $row->ledger;
                        })
                        ->values()
                ];
            })->values();

        return response()->json([
            'success' => true,
            'data' => $branches
        ]);

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'message' => 'Something went wrong. Please try again later.'
        ], 500);
    }
}


public function getAllData(Request $request)
{
    try {

        // Base query with relations
        $query = TenderEntry::with([
            'department',
            'ledger',
            'budgetHead',
            'tendertype'
        ]);

        if ($request->has('search')) {

            $search = $request->search;

            $query->where(function ($q) use ($search) {

                $q->where('Description', 'LIKE', "%{$search}%")
                  ->orWhere('Proposal_Amount', 'LIKE', "%{$search}%")
                  ->orWhere('Approved_Amount', 'LIKE', "%{$search}%")

                  ->orWhereHas('department', function ($q2) use ($search) {
                      $q2->where('Dpt_Name', 'LIKE', "%{$search}%")
                         ->orWhere('Dpt_Desc', 'LIKE', "%{$search}%");
                  })

                  ->orWhereHas('ledger', function ($q3) use ($search) {
                      $q3->where('Lg_Name', 'LIKE', "%{$search}%");
                  })

                  ->orWhereHas('budgetHead', function ($q4) use ($search) {
                      $q4->where('Gr_Cd', 'LIKE', "%{$search}%")
                         ->orWhere('Gr_Nm', 'LIKE', "%{$search}%");
                  })

                  ->orWhereHas('tendertype', function ($q5) use ($search) {
                      $q5->where('TnT_Name', 'LIKE', "%{$search}%");
                  });
            });
        }

        // Filter by department
        if ($request->has('Dpt_id')) {
            $query->where('Dpt_id', $request->Dpt_id);
        }

        // Filter by ledger
        if ($request->has('Lg_Id')) {
            $query->where('Lg_Id', $request->Lg_Id);
        }

        // Filter by budget head
        if ($request->has('Bh_Id')) {
            $query->where('Bh_Id', $request->Bh_Id);
        }

        // Filter by tender type
        if ($request->has('TnT_ID')) {
            $query->where('TnT_ID', $request->TnT_ID);
        }

        // ✅ UPDATED: Filter by date range
        if ($request->has('start_date') && $request->has('end_date')) {
            $query->whereBetween('TE_St_Date', [$request->start_date, $request->end_date]);
        }

        // ✅ UPDATED: Order by new date
        $query->orderBy('TE_St_Date', 'desc')->orderBy('TE_Id', 'desc');

        // Get all records
        $tenders = $query->get();

        // Format each tender with related data
        $allData = [];

        foreach ($tenders as $tender) {

            $tenderData = $tender->toArray();

            // Total Allocated Amount
            $allocatedTotal = WorkAllocationBook::where('TE_Id', $tender->TE_Id)
                ->sum('WO_Amount');

            // Remaining Amount
            $tenderData['remaining_amount'] =
                (float)$tender->Approved_Amount - (float)$allocatedTotal;

            // Documents logic
            if ($tender->uploadedDocuments && $tender->uploadedDocuments->count() > 0) {

                $uploadedDocuments = [];

                foreach ($tender->uploadedDocuments as $doc) {

                    $docData = $doc->toArray();

                    if (is_string($docData['Doc_Upload'] ?? null)) {
                        $docData['Doc_Upload'] = json_decode($docData['Doc_Upload'], true);
                    }

                    $uploadedDocuments[] = $docData;
                }

                $tenderData['uploaded_documents'] = $uploadedDocuments;

            } else {

                $tenderData['uploaded_documents'] = [];
            }

            // ✅ (Optional explicit add – already included via toArray)
            $tenderData['TE_St_Date'] = $tender->TE_St_Date;
            $tenderData['TE_Ed_Date'] = $tender->TE_Ed_Date;
            $tenderData['BG_Per']     = $tender->BG_Per;
            $tenderData['EMD_Per']    = $tender->EMD_Per;
            $tenderData['TE_Fee']     = $tender->TE_Fee;

            $allData[] = $tenderData;
        }

        return response()->json([
            'success' => true,
            'data' => $allData,
            'count' => count($allData),
            'message' => 'All tender data retrieved successfully.'
        ]);

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'message' => 'Error retrieving tender data.',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}

public function getDepartmentLedgerTenderStructure(Request $request)
{
    try {

        $query = TenderEntry::with([
            'department',
            'ledger',
            'tendertype'
        ]);

        if ($request->filled('Dpt_id')) {
            $query->where('Dpt_id', $request->Dpt_id);
        }

        if ($request->filled('Lg_Id')) {
            $query->where('Lg_Id', $request->Lg_Id);
        }

        $tenders = $query->get();

        $groupedData = $tenders
            ->groupBy('Dpt_id')
            ->map(function ($deptItems) {

                $department = $deptItems->first()->department;

                return [
                    'Dpt_id'   => $department->Dpt_id ?? null,
                    'Dpt_Name' => $department->Dpt_Name ?? null,
                    'Dpt_Desc' => $department->Dpt_Desc ?? null,

                    'ledgers' => $deptItems
                        ->groupBy('Lg_Id')
                        ->map(function ($ledgerItems) {

                            $ledger = $ledgerItems->first()->ledger;

                            return [
                                'Lg_Id'        => $ledger->Lg_Id ?? null,
                                'Lg_Name'      => $ledger->Lg_Name ?? null,
                                'Lg_Eng_Name'  => $ledger->Lg_Eng_Name ?? null, // ✅ Added
                                'Lg_Code'      => $ledger->Lg_Code ?? null,   // ✅ Added

                                'tender_entries' => $ledgerItems->map(function ($entry) {

                                    $allocatedTotal = WorkAllocationBook::where('TE_Id', $entry->TE_Id)
                                        ->sum('WO_Amount');

                                    $remainingAmount =
                                        (float)$entry->Approved_Amount - (float)$allocatedTotal;

                                    return [
                                        'TE_Id' => $entry->TE_Id,
                                        'TnT_ID' => $entry->TnT_ID,
                                        'Proposal_Amount' => $entry->Proposal_Amount,
                                        'Approved_Amount' => $entry->Approved_Amount,
                                        'allocated_amount' => $allocatedTotal,
                                        'remaining_amount' => $remainingAmount,
                                        'Tnd_Date' => $entry->Tnd_Date,
                                        'Description' => $entry->Description,
                                    ];
                                })->values()
                            ];

                        })->values()
                ];

            })->values();

        return response()->json([
            'success' => true,
            'message' => 'Department → Ledger → Tender structure fetched successfully',
            'data' => $groupedData
        ]);

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'message' => 'Something went wrong',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}


public function getTenderEntriesByBranch(Request $request)
{
    try {

        $validator = Validator::make($request->all(), [
            'Dpt_id' => 'required|integer|exists:dept_master,Dpt_id',
            'Lg_Id'  => 'nullable|integer|exists:ledger_master,Lg_Id'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors'  => $validator->errors()
            ], 422);
        }

        $departmentId = $request->Dpt_id;
        $ledgerId     = $request->Lg_Id;

        /*
        |--------------------------------------------------------------------------
        | Base Query
        |--------------------------------------------------------------------------
        */

        $query = TenderEntry::with([
            'department',
            'ledger',
            'tendertype'
        ])->where('Dpt_id', $departmentId);

        if ($ledgerId) {
            $query->where('Lg_Id', $ledgerId);
        }

        $tenderEntries = $query->get();

        /*
        |--------------------------------------------------------------------------
        | Format Response
        |--------------------------------------------------------------------------
        */

        $formattedEntries = $tenderEntries->map(function ($entry) {

            /*
            |--------------------------------------------------------------------------
            | Vendor Allocations
            |--------------------------------------------------------------------------
            */

            $vendorAllocations = WorkAllocationBook::with(['subledger'])
                ->where('TE_Id', $entry->TE_Id)
                ->get();

            /*
            |--------------------------------------------------------------------------
            | Vendor Invoice Parameters
            |--------------------------------------------------------------------------
            */

            $vendorInvoiceParameters = VendInvParameter::with([
                    'ledger',
                    'InvoiceCharge'
                ])
                ->where('TnT_ID', $entry->TnT_ID)
                ->whereNull('deleted_at')
                ->orderBy('Eff_Date', 'desc')
                ->get()
                ->map(function ($param) {

                    return [
                        'VIP_Id' => $param->VIP_Id,
                        'ledger_id' => $param->Lg_Id,
                        'ledger_name' => $param->ledger->Lg_Name ?? null,

                        'invoice_charge_id' => $param->IC_Id,
                        'invoice_charge_name' => $param->InvoiceCharge->IC_Name ?? null,
                        'invoice_charge_code' => $param->InvoiceCharge->IC_Code ?? null,
                        'Exmp_Alw' => $param->Exmp_Alw ?? null,

                        'percentage' => $param->Percent,

                        'type' => $param->Add_Dedu,
                        'type_text' => $param->add_deduct_text,

                        'formula' => $param->Formula,

                        'effective_date' => $param->Eff_Date
                            ? $param->Eff_Date->format('d-m-Y')
                            : null,
                    ];
                })
                ->toArray();


            $allocatedTotal = $vendorAllocations->sum('WO_Amount');

            $remainingAmount = (float)$entry->Approved_Amount - (float)$allocatedTotal;


            return [

                'TE_Id' => $entry->TE_Id,

                'Dpt_id'   => $entry->Dpt_id,
                'Dpt_Name' => $entry->department->Dpt_Name ?? null,
                'Dpt_Desc' => $entry->department->Dpt_Desc ?? null,

                'Lg_Id'   => $entry->Lg_Id,
                'Lg_Name' => $entry->ledger->Lg_Name ?? null,

                'TnT_ID'   => $entry->TnT_ID,
                'tendertype' => $entry->tendertype,

                'Proposal_Amount' => $entry->Proposal_Amount,
                'Approved_Amount' => $entry->Approved_Amount,

                'formatted_proposal_amount' =>
                    number_format($entry->Proposal_Amount ?? 0, 2),

                'formatted_approved_amount' =>
                    number_format($entry->Approved_Amount ?? 0, 2),

                'allocated_amount' => $allocatedTotal,
                'remaining_amount' => $remainingAmount,

                'formatted_remaining_amount' =>
                    number_format($remainingAmount ?? 0, 2),

                'Tnd_Date'   => $entry->Tnd_Date,
                'Description'=> $entry->Description,


                'vendor_allocations' => $vendorAllocations->map(function ($allocation) {

                    return [
                        'WA_Id' => $allocation->WA_Id,

                        'SL_Id' => $allocation->SL_Id,

                        'vendor_details' => $allocation->subledger ? [
                            'SL_Code' => $allocation->subledger->SL_Code,
                            'SL_Name' => $allocation->subledger->SL_Name,
                            'GST_Incd' => $allocation->subledger->GST_Incd,
                        ] : null,

                        'WO_Amount' => $allocation->WO_Amount,

                        'formatted_WO_Amount' =>
                            number_format($allocation->WO_Amount ?? 0, 2),

                        'created_at' => $allocation->created_at
                            ? $allocation->created_at->format('d-m-Y H:i:s')
                            : null
                    ];

                })->toArray(),


                'vendor_invoice_parameters' => $vendorInvoiceParameters,

                'has_vendor_allocations'   => $vendorAllocations->count() > 0,
                'total_vendor_allocations' => $vendorAllocations->count(),

                'created_at' => $entry->created_at
                    ? $entry->created_at->format('d-m-Y H:i:s')
                    : null
            ];

        });

        return response()->json([
            'success' => true,
            'message' => 'Tender entries with vendor allocations fetched successfully',
            'data' => [
                'department_id' => $departmentId,
                'ledger_id'     => $ledgerId,
                'total_tender_entries' => $tenderEntries->count(),
                'tender_entries' => $formattedEntries
            ]
        ]);

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch tender entries',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}

 public function show($id)
    {
        $entry = TenderEntry::with(['department', 'ledger', 'budgetHead', 'tendertype'])->find($id);

        if (!$entry) {
            return response()->json([
                'success' => false,
                'message' => 'Tender entry not found'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $entry
        ]);
    }

public function store(Request $request)
{
    DB::beginTransaction();

    try {

        $validator = Validator::make($request->all(), [

            'Dpt_id' => 'required|exists:dept_master,Dpt_id',
            'Lg_Id' => 'required|exists:ledger_master,Lg_Id',
            'Bh_Id' => 'required|exists:budget_head,Bh_Id',
            'TnT_ID' => 'nullable|exists:tender_type,TnT_ID',
            'Proposal_Amount' => 'required|numeric|min:0',
            'Approved_Amount' => 'nullable|numeric|min:0',

            // ✅ UPDATED FIELD
            'TE_Date' => 'nullable|date',
            'TE_St_Date' => 'required|date',

            // ✅ NEW FIELDS
            'TE_Ed_Date' => 'nullable|date',
            'BG_Per'     => 'nullable|string',
            'EMD_Per'    => 'nullable|string',
            'TE_Fee'     => 'nullable|numeric|min:0',

            'Description' => 'required|string',

            'Fnc_Id' => 'nullable|exists:function_types,Fnc_Id',

            'Documents' => 'nullable|array',
            'Documents.*' => 'file',

            'Documents_description' => 'nullable|array',
            'Documents_description.*' => 'nullable|string'
        ]);

        if ($validator->fails()) {

            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        $entry = TenderEntry::create([

            'Dpt_id' => $request->Dpt_id,
            'Lg_Id' => $request->Lg_Id,
            'Bh_Id' => $request->Bh_Id,
            'TnT_ID' => $request->TnT_ID,
            'Proposal_Amount' => $request->Proposal_Amount,
            'Approved_Amount' => $request->Approved_Amount,

            // ✅ UPDATED FIELD
            'TE_Date' => $request->TE_Date,
            'TE_St_Date' => $request->TE_St_Date,

            // ✅ NEW FIELDS
            'TE_Ed_Date' => $request->TE_Ed_Date,
            'BG_Per'     => $request->BG_Per,
            'EMD_Per'    => $request->EMD_Per,
            'TE_Fee'     => $request->TE_Fee,

            'Description' => $request->Description,
            'Documents' => []

        ]);

        $newDocs = [];

        if ($request->hasFile('Documents')) {

            foreach ($request->file('Documents') as $index => $file) {

                if (!$file->isValid()) continue;

                $folderName = 'tender_documents';
                $folderPath = public_path($folderName);

                if (!File::exists($folderPath)) {
                    File::makeDirectory($folderPath, 0755, true, true);
                }

                $fileName = Str::uuid() . '.' . $file->getClientOriginalExtension();
                $file->move($folderPath, $fileName);

                $fullUrl = url($folderName . '/' . $fileName);

                $docName = 'Document_' . ($index + 1);

                $docDescription = $request->Documents_description[$index] ?? null;

                $docRecord = DocumentLibrary::create([
                    'Fnc_Id' => $request->Fnc_Id,
                    'Rec_Id' => $entry->TE_Id,
                    'Description' => $docDescription,
                    'Doc_Upload' => $fullUrl,
                    'Serial_No' => $index + 1
                ]);

                $newDocs[] = [
                    'doc_lib_id' => $docRecord->Doc_Lib,
                    'name' => $docName,
                    'description' => $docDescription,
                    'url' => $fullUrl,
                    'type' => $file->getClientOriginalExtension()
                ];
            }
        }

        if (!empty($newDocs)) {

            $entry->update([
                'Documents' => $newDocs
            ]);
        }

        DB::commit();

        return response()->json([

            'success' => true,
            'message' => 'Tender entry created successfully',
            'data' => $entry

        ]);

    } catch (\Exception $e) {

        DB::rollBack();

        return response()->json([
            'success' => false,
            'message' => 'Something went wrong. Please try again later.'
        ], 500);
    }
}

public function update(Request $request, $id)
{
    DB::beginTransaction();

    try {

        $entry = TenderEntry::find($id);

        if (!$entry) {
            return response()->json([
                'success' => false,
                'message' => 'Tender entry not found'
            ], 404);
        }

        $validator = Validator::make($request->all(), [

            'Dpt_id' => 'sometimes|nullable|exists:dept_master,Dpt_id',
            'Lg_Id' => 'sometimes|nullable|exists:ledger_master,Lg_Id',
            'Bh_Id' => 'sometimes|nullable|exists:budget_head,Bh_Id',
            'TnT_ID' => 'nullable|exists:tender_type,TnT_ID',

            'Proposal_Amount' => 'sometimes|numeric|min:0',
            'Approved_Amount' => 'nullable|numeric|min:0',

            // ✅ UPDATED FIELD
            'TE_Date' => 'sometimes|nullable|date',
            'TE_St_Date' => 'sometimes|nullable|date',

            // ✅ NEW FIELDS
            'TE_Ed_Date' => 'sometimes|nullable|date',
            'BG_Per'     => 'sometimes|nullable|string',
            'EMD_Per'    => 'sometimes|nullable|string',
            'TE_Fee'     => 'sometimes|nullable|numeric|min:0',

            'Description' => 'sometimes|nullable|string',

            // Documents
            'Documents' => 'sometimes|nullable|array',
            'Documents.*' => 'sometimes|nullable|string',

            'Documents_description' => 'sometimes|nullable|array',
            'Documents_description.*' => 'sometimes|nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        // ✅ Normal fields update
        $entry->update($request->except('Documents', 'Documents_description'));

        // ✅ Old documents
        $existingDocs = $entry->Documents ?? [];

        $newDocs = [];

        // ✅ Fnc_Id optional (NULL allowed)
        $fncId = $request->Fnc_Id ?? $entry->Fnc_Id ?? null;

        // ✅ Base64 upload
        if (!empty($request->Documents)) {

            foreach ($request->Documents as $index => $base64File) {

                if (!$base64File) continue;

                if (strpos($base64File, 'base64,') !== false) {

                    [$meta, $content] = explode(',', $base64File);

                    preg_match('/data:(.*?);base64/', $meta, $matches);
                    $extension = isset($matches[1])
                        ? explode('/', $matches[1])[1]
                        : 'png';

                    $fileName = Str::uuid() . '.' . $extension;

                    $folderName = 'tender_documents';
                    $folderPath = public_path($folderName);

                    if (!File::exists($folderPath)) {
                        File::makeDirectory($folderPath, 0755, true, true);
                    }

                    file_put_contents(
                        $folderPath . '/' . $fileName,
                        base64_decode($content)
                    );

                    $fullUrl = url($folderName . '/' . $fileName);

                    $docDescription = $request->Documents_description[$index] ?? null;

                    $serialNo = count($existingDocs) + count($newDocs) + 1;

                    $docRecord = DocumentLibrary::create([
                        'Fnc_Id' => $fncId,
                        'Rec_Id' => $entry->TE_Id,
                        'Description' => $docDescription,
                        'Doc_Upload' => $fullUrl,
                        'Serial_No' => $serialNo
                    ]);

                    $newDocs[] = [
                        'doc_lib_id' => $docRecord->Doc_Lib,
                        'name' => 'Document_' . $serialNo,
                        'description' => $docDescription,
                        'url' => $fullUrl,
                        'type' => $extension
                    ];
                }
            }
        }

        // ✅ Merge old + new
        if (!empty($newDocs)) {

            $finalDocs = array_merge($existingDocs, $newDocs);

            $entry->update([
                'Documents' => $finalDocs
            ]);
        }

        DB::commit();

        return response()->json([
            'success' => true,
            'message' => 'Tender entry updated successfully',
            'data' => $entry
        ]);

    } catch (\Exception $e) {

        DB::rollBack();

        return response()->json([
            'success' => false,
            'message' => 'Something went wrong. Please try again later.'
        ], 500);
    }
}

 public function destroy($id)
    {

        $entry = TenderEntry::find($id);

        if (!$entry) {

            return response()->json([
                'success' => false,
                'message' => 'Tender entry not found'
            ], 404);
        }

        $entry->delete();

        return response()->json([
            'success' => true,
            'message' => 'Tender entry deleted successfully'
        ]);
    }


    public function deleteDocument($doc_id)
{
    DB::beginTransaction();

    try {

        // 1. Find document
        $doc = DocumentLibrary::find($doc_id);

        if (!$doc) {
            return response()->json([
                'success' => false,
                'message' => 'Document not found'
            ], 404);
        }

        // 2. Get Tender Entry
        $entry = TenderEntry::find($doc->Rec_Id);

        // 3. Delete file from folder
        if ($doc->Doc_Upload) {

            $filePath = public_path(parse_url($doc->Doc_Upload, PHP_URL_PATH));

            if (File::exists($filePath)) {
                File::delete($filePath);
            }
        }

        // 4. Delete from DocumentLibrary table
        $doc->delete();

        // 5. Remove from TenderEntry JSON (Documents column)
        if ($entry && is_array($entry->Documents)) {

            $updatedDocs = collect($entry->Documents)
                ->filter(function ($item) use ($doc_id) {
                    return $item['doc_lib_id'] != $doc_id;
                })
                ->values()
                ->toArray();

            $entry->update([
                'Documents' => $updatedDocs
            ]);
        }

        DB::commit();

        return response()->json([
            'success' => true,
            'message' => 'Document deleted successfully'
        ]);

    } catch (\Exception $e) {

        DB::rollBack();

        return response()->json([
            'success' => false,
            'message' => 'Something went wrong. Please try again later.'
        ], 500);
    }
}

}
