<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Booking;
use App\Models\Room;
use App\Models\Customer;
use App\Models\RoomType;
use App\Models\BookingCustomer;
use App\Models\Transaction;
use App\Models\Receipt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use App\Models\User; // Added this import for users
use Illuminate\Support\Facades\Hash; // Added this import for Hash

class BookingController extends Controller
{
    public function __construct()
    {
        // Temporarily comment out permission middleware for debugging
        // $this->middleware('permission:view-bookings')->only(['index', 'show', 'roomBoard']);
        // $this->middleware('permission:create-bookings')->only(['create', 'store']);
        // $this->middleware('permission:edit-bookings')->only(['edit', 'update', 'checkIn', 'checkOut']);
        // $this->middleware('permission:delete-bookings')->only(['destroy']);
    }

    public function index(Request $request)
    {
        $query = Booking::with(['room.roomType', 'bookingCustomers']);

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->whereHas('bookingCustomers', function($q) use ($search) {
                $q->where('first_name', 'like', "%{$search}%")
                  ->orWhere('last_name', 'like', "%{$search}%")
                  ->orWhere('document_number', 'like', "%{$search}%");
            })->orWhereHas('room', function($q) use ($search) {
                $q->where('room_no', 'like', "%{$search}%");
            });
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('booking_status', $request->status);
        }

        // Filter by date range
        if ($request->filled('date_from')) {
            $query->where('check_in', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->where('check_out', '<=', $request->date_to);
        }

        $bookings = $query->orderBy('created_at', 'desc')->paginate(10);

        return view('backend.bookings.index', compact('bookings'));
    }

    public function roomBoard()
    {
        // Get all rooms organized by floor with their current bookings
        $rooms = Room::with(['roomType', 'bookings' => function($query) {
            $query->whereIn('booking_status', ['Checked In', 'Confirmed'])
                  ->orderBy('created_at', 'desc');
        }])
        ->where('deleteStatus', false)
        ->orderBy('floor')
        ->orderBy('room_no')
        ->get()
        ->groupBy('floor');

        // Debug information
        Log::info('Room Board - Total rooms: ' . $rooms->flatten()->count());
        Log::info('Room Board - Floors: ' . $rooms->keys()->implode(', '));

        return view('backend.bookings.room-board', compact('rooms'));
    }

    public function create()
    {
        $availableRooms = Room::with('roomType')
            ->where('deleteStatus', false)
            ->where('room_status', 'Available')
            ->where('status', false)
            ->get();

        $roomTypes = RoomType::all();

        // Get all users (employees) for customer selection
        $users = User::where('status', 'Customer')->get();

        $cashiers = User::where(function($query) {
            $query->where('status', '!=', 'Customer')
                ->orWhereNull('status');
        })->orderBy('name')->get();

        // Latest customer data for the authenticated user to prefill
        $authLatestCustomer = BookingCustomer::where('user_id', Auth::id())
            ->orderBy('created_at', 'desc')
            ->first();

        return view('backend.bookings.create', compact('availableRooms', 'roomTypes', 'users', 'cashiers', 'authLatestCustomer'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'room_id' => 'required|exists:rooms,room_id',
            'cashier_id' => 'required|exists:users,id',
            'number_of_customers' => 'required|integer|min:1|max:5',
            'price_per_night' => 'required|numeric|min:0',
            'number_of_nights' => 'required|integer|min:1',
            'check_in' => 'required|date|after_or_equal:today',
            'check_out' => 'required|date|after:check_in',
            'observations' => 'nullable|string|max:500',
            'customers' => 'required|array|min:1',
            'customers.*.user_id' => 'nullable|exists:users,id',
            'customers.*.first_name' => 'required|string|max:100',
            'customers.*.last_name' => 'required|string|max:100',
            'customers.*.document_number' => 'nullable|string|max:50',
            'customers.*.document_type' => 'required|string|max:20',
            'customers.*.nationality' => 'nullable|string|max:50',
            'customers.*.origin_city' => 'nullable|string|max:100',
            'customers.*.phone' => 'nullable|string|max:20',
            'customers.*.email' => 'nullable|email|max:100',
            'card_type' => 'nullable|string|max:50',
            'payment_transaction_id' => 'nullable|required_unless:card_type,Cash,CustomerBalance|string|max:100',
        ]);

        Log::info('Validation passed successfully');

        DB::beginTransaction();
        try {
            // Calculate total price (only based on nights and price, not customer count)
            $totalPrice = $request->price_per_night * $request->number_of_nights;

            // Since payment is made before booking, set advance payment to total price
            $advancePayment = $totalPrice;
            $dueAmount = 0; // No due amount since full payment is made

            Log::info('Calculated values:', [
                'totalPrice' => $totalPrice,
                'advancePayment' => $advancePayment,
                'dueAmount' => $dueAmount
            ]);

            // Process customers and get primary user id
            $customerUserIds = [];
            $primaryUserId = null;

            foreach ($request->customers as $index => $customerData) {
                $customerUserId = null;

                // Check if user_id is provided directly
                if (!empty($customerData['user_id'])) {
                    $customerUserId = $customerData['user_id'];
                } else {
                    // Check if user exists with same email and phone
                    $existingUser = null;

                    if (!empty($customerData['email']) || !empty($customerData['phone'])) {
                        $query = User::query();

                        if (!empty($customerData['email'])) {
                            $query->where('email', $customerData['email']);
                        }

                        if (!empty($customerData['document_number'])) {
                            $query->where('document_number', $customerData['document_number']);
                        }

                        $existingUser = $query->first();
                    }

                    if ($existingUser) {
                        // Use existing user
                        $customerUserId = $existingUser->id;
                        Log::info('Using existing user:', ['user_id' => $customerUserId, 'email' => $customerData['email'], 'document_number' => $customerData['document_number']]);
                    } else {
                        // Create new user
                        $fullName = $customerData['first_name'] . ' ' . $customerData['last_name'];
                        $email = $customerData['email'] ?? null;
                        $phone = $customerData['phone'] ?? null;
                        $documentNumber = $customerData['document_number'] ?? null;

                        // Generate unique username
                        $baseUsername = strtolower(str_replace(' ', '', $customerData['first_name'] . $customerData['last_name']));
                        $username = $baseUsername;
                        $counter = 1;

                        while (User::where('username', $username)->exists()) {
                            $username = $baseUsername . $counter;
                            $counter++;
                        }

                        $newUser = User::create([
                            'name' => $fullName,
                            'username' => $username,
                            'email' => $email,
                            'phone' => $phone,
                            'document_number' => $documentNumber,
                            'status' => 'Customer',
                            'password' => Hash::make('12345678'),
                        ]);

                        $customerUserId = $newUser->id;
                        Log::info('Created new user:', ['user_id' => $customerUserId, 'username' => $username, 'name' => $fullName]);
                    }
                }

                $customerUserIds[] = $customerUserId;

                // Set primary user id (first customer or current auth user)
                if ($index === 0) {
                    $primaryUserId = $customerUserId;
                }
            }

            // If no primary user found, use current auth user
            if (!$primaryUserId) {
                $primaryUserId = Auth::id();
            }

            if ($request->card_type === 'CustomerBalance') {
                $user = User::find($primaryUserId);
                if ($user->advance_balance >= $totalPrice) {
                    // Sufficient balance, deduct amount
                    $user->advance_balance -= $totalPrice;
                    $user->save();
                } else {
                    // Insufficient balance, return back with error
                    return back()->withErrors([
                        'balance' => 'Customer does not have sufficient balance to complete this payment.'
                    ])->withInput();
//                    return back()->with('error', 'Customer does not have sufficient balance to complete this payment.')->withInput();
                }
            }

            Log::info('Primary user ID determined:', ['primary_user_id' => $primaryUserId]);

            // Create booking
            $booking = Booking::create([
                'room_id' => $request->room_id,
                'user_id' => $primaryUserId,
                'cashier_id' => $request->cashier_id,
                'number_of_customers' => $request->number_of_customers,
                'price_per_night' => $request->price_per_night,
                'number_of_nights' => $request->number_of_nights,
                'check_in' => $request->check_in,
                'check_out' => $request->check_out,
                'total_price' => $totalPrice,
                'advance_payment' => $advancePayment,
                'due_amount' => $dueAmount,
                'remaining_price' => $dueAmount,
                'observations' => $request->observations,
                'booking_status' => 'Checked In',
                'checked_in_at' => now(),
                'payment_status' => true, // Always paid since payment is made before booking
            ]);

            Log::info('Booking created successfully:', ['booking_id' => $booking->booking_id]);

            // Create booking customers
            foreach ($request->customers as $index => $customerData) {
                BookingCustomer::create([
                    'booking_id' => $booking->booking_id,
                    'user_id' => $customerUserIds[$index], // Use the processed user_id
                    'document_number' => $customerData['document_number'] ?? null,
                    'document_type' => $customerData['document_type'],
                    'first_name' => $customerData['first_name'],
                    'last_name' => $customerData['last_name'],
                    'nationality' => $customerData['nationality'] ?? 'Not Specified',
                    'origin_city' => $customerData['origin_city'] ?? 'Not Specified',
                    'phone' => $customerData['phone'] ?? null,
                    'email' => $customerData['email'] ?? null,
                ]);
            }

            Log::info('Booking customers created successfully');

            // Create transaction with user_id
            Transaction::create([
                'booking_id' => $booking->booking_id,
                'user_id' => $primaryUserId,
                'cashier_id' => $request->cashier_id,
                'card_type' => $request->card_type ?? 'Cash',
                'payment_transaction_id' => ($request->card_type === 'Cash' || $request->card_type === 'CustomerBalance' || empty($request->card_type)) ? null : $request->payment_transaction_id,
                'amount' => $totalPrice,
                'payment_date' => now(),
            ]);
            Log::info('Transaction created successfully');

            // Update room status when booking is checked in
            Room::where('room_id', $request->room_id)->update([
                'room_status' => 'Occupied',
                'status' => true,
            ]);

            Log::info('Room status updated - booking is checked in');

            // Create receipt
            $receipt = Receipt::create([
                'booking_id' => $booking->booking_id,
                'receipt_number' => Receipt::generateReceiptNumber(),
                'total_amount' => $totalPrice,
                'advance_payment' => $advancePayment,
                'due_amount' => $dueAmount,
                'payment_method' => $request->filled('card_type') ? $request->card_type : 'Cash',
                'card_type' => $request->card_type,
                'transaction_id' => $request->payment_transaction_id,
                'notes' => $request->observations,
                'status' => 'Paid', // Always paid since payment is made before booking
            ]);

            Log::info('Receipt created successfully:', ['receipt_id' => $receipt->receipt_id]);

            DB::commit();

            return redirect()->route('receipts.show', $receipt)->with('success', 'Booking created successfully! Guest is now checked in.');
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Error creating booking: ' . $e->getMessage(), [
                'request_data' => $request->all(),
                'trace' => $e->getTraceAsString()
            ]);
            return back()->with('error', 'Error creating booking: ' . $e->getMessage())->withInput();
        }
    }

    public function show(Booking $booking)
    {
        $booking->load(['room.roomType', 'bookingCustomers']);
        return view('backend.bookings.show', compact('booking'));
    }

    public function edit(Booking $booking)
    {
        // Check if checkout date has passed
        if (now()->format('Y-m-d') > $booking->check_out) {
            return redirect()->route('bookings.show', $booking)->with('error', 'Cannot edit booking after checkout date has passed.');
        }

        $booking->load(['room.roomType', 'bookingCustomers', 'transactions', 'receipt']);
        $availableRooms = Room::with('roomType')
            ->where('deleteStatus', false)
            ->where('room_status', 'Available')
            ->where('status', false)
            ->orWhere('room_id', $booking->room_id)
            ->get();

        $roomTypes = RoomType::all();

        $cashiers = User::where(function($query) {
            $query->where('status', '!=', 'Customer')
                ->orWhereNull('status');
        })->orderBy('name')->get();

        // Get all users (employees) for customer selection
        $users = User::all();

        return view('backend.bookings.edit', compact('booking', 'availableRooms', 'roomTypes', 'users', 'cashiers'));
    }

    public function update(Request $request, Booking $booking)
    {
        // Log the incoming request data for debugging
        Log::info('Booking update request data:', $request->all());
        Log::info('Request method: ' . $request->method());
        Log::info('Request URL: ' . $request->url());
        Log::info('Request headers: ' . json_encode($request->headers->all()));

        // Check if checkout date has passed
        if (now()->format('Y-m-d') > $booking->check_out) {
            return redirect()->route('bookings.show', $booking)->with('error', 'Cannot update booking after checkout date has passed.');
        }

        $request->validate([
            'room_id' => 'required|exists:rooms,room_id',
            'number_of_customers' => 'required|integer|min:1|max:5',
            'price_per_night' => 'required|numeric|min:0',
            'number_of_nights' => 'required|integer|min:1',
            'check_in' => 'required|date',
            'check_out' => 'required|date|after:check_in',
            'observations' => 'nullable|string|max:500',
            'customers' => 'required|array|min:1',
            'customers.*.user_id' => 'nullable|exists:users,id',
            'customers.*.first_name' => 'required|string|max:100',
            'customers.*.last_name' => 'required|string|max:100',
            'customers.*.document_number' => 'nullable|string|max:50',
            'customers.*.document_type' => 'required|string|max:20',
            'customers.*.nationality' => 'nullable|string|max:50',
            'customers.*.origin_city' => 'nullable|string|max:100',
            'customers.*.phone' => 'nullable|string|max:20',
            'customers.*.email' => 'nullable|email|max:100',
            'card_type' => 'nullable|string|max:50',
            'payment_transaction_id' => 'nullable|required_unless:card_type,Cash,CustomerBalance|string|max:100',
        ]);

        Log::info('Validation passed successfully');

        DB::beginTransaction();
        try {
            // Calculate total price (only based on nights and price, not customer count)
            $totalPrice = $request->price_per_night * $request->number_of_nights;

            // Since payment is made before booking, set advance payment to total price
            $advancePayment = $totalPrice;
            $dueAmount = 0; // No due amount since full payment is made

            Log::info('Calculated values:', [
                'totalPrice' => $totalPrice,
                'advancePayment' => $advancePayment,
                'dueAmount' => $dueAmount
            ]);

            // Process customers and get primary user id
            $customerUserIds = [];
            $primaryUserId = null;

            foreach ($request->customers as $index => $customerData) {
                $customerUserId = null;

                // Check if user_id is provided directly
                if (!empty($customerData['user_id'])) {
                    $customerUserId = $customerData['user_id'];
                } else {
                    // Check if user exists with same email and phone
                    $existingUser = null;

                    if (!empty($customerData['email']) || !empty($customerData['phone'])) {
                        $query = User::query();

                        if (!empty($customerData['email'])) {
                            $query->where('email', $customerData['email']);
                        }

                        if (!empty($customerData['document_number'])) {
                            $query->where('document_number', $customerData['document_number']);
                        }

                        $existingUser = $query->first();
                    }

                    if ($existingUser) {
                        // Use existing user
                        $customerUserId = $existingUser->id;
                        Log::info('Using existing user:', ['user_id' => $customerUserId, 'email' => $customerData['email'], 'document_number' => $customerData['document_number']]);
                    } else {
                        // Create new user
                        $fullName = $customerData['first_name'] . ' ' . $customerData['last_name'];
                        $email = $customerData['email'] ?? null;
                        $phone = $customerData['phone'] ?? null;
                        $documentNumber = $customerData['document_number'] ?? null;

                        // Generate unique username
                        $baseUsername = strtolower(str_replace(' ', '', $customerData['first_name'] . $customerData['last_name']));
                        $username = $baseUsername;
                        $counter = 1;

                        while (User::where('username', $username)->exists()) {
                            $username = $baseUsername . $counter;
                            $counter++;
                        }

                        $newUser = User::create([
                            'name' => $fullName,
                            'username' => $username,
                            'email' => $email,
                            'phone' => $phone,
                            'document_number' => $documentNumber,
                            'status' => 'Customer',
                            'password' => Hash::make('12345678'),
                        ]);

                        $customerUserId = $newUser->id;
                        Log::info('Created new user:', ['user_id' => $customerUserId, 'username' => $username, 'name' => $fullName]);
                    }
                }

                $customerUserIds[] = $customerUserId;

                // Set primary user id (first customer or current auth user)
                if ($index === 0) {
                    $primaryUserId = $customerUserId;
                }
            }

            // If no primary user found, use current auth user
            if (!$primaryUserId) {
                $primaryUserId = Auth::id();
            }

            Log::info('Primary user ID determined:', ['primary_user_id' => $primaryUserId]);

            // Store original room ID before updating
            $originalRoomId = $booking->room_id;

            // Update booking
            $booking->update([
                'room_id' => $request->room_id,
                'user_id' => $primaryUserId,
                'number_of_customers' => $request->number_of_customers,
                'price_per_night' => $request->price_per_night,
                'number_of_nights' => $request->number_of_nights,
                'check_in' => $request->check_in,
                'check_out' => $request->check_out,
                'total_price' => $totalPrice,
                'advance_payment' => $advancePayment,
                'due_amount' => $dueAmount,
                'remaining_price' => $dueAmount,
                'observations' => $request->observations,
                'payment_status' => true, // Always paid since payment is made before booking
            ]);

            Log::info('Booking updated successfully:', ['booking_id' => $booking->booking_id]);

            // Delete existing booking customers
            $booking->bookingCustomers()->delete();

            // Create new booking customers
            foreach ($request->customers as $index => $customerData) {
                BookingCustomer::create([
                    'booking_id' => $booking->booking_id,
                    'user_id' => $customerUserIds[$index], // Use the processed user_id
                    'document_number' => $customerData['document_number'] ?? null,
                    'document_type' => $customerData['document_type'],
                    'first_name' => $customerData['first_name'],
                    'last_name' => $customerData['last_name'],
                    'nationality' => $customerData['nationality'] ?? 'Not Specified',
                    'origin_city' => $customerData['origin_city'] ?? 'Not Specified',
                    'phone' => $customerData['phone'] ?? null,
                    'email' => $customerData['email'] ?? null,
                ]);
            }

            Log::info('Booking customers updated successfully');

            // Update transaction if it exists, or create new one
            $transaction = $booking->transactions()->first();
            if ($transaction) {
                $transaction->update([
                    'user_id' => $primaryUserId,
                    'card_type' => $request->card_type ?? 'Cash',
                    'payment_transaction_id' => ($request->card_type === 'Cash' || empty($request->card_type)) ? null : $request->payment_transaction_id,
                    'amount' => $totalPrice,
                    'payment_date' => now(),
                ]);
            } else {
                // Create new transaction if none exists
                Transaction::create([
                    'booking_id' => $booking->booking_id,
                    'user_id' => $primaryUserId,
                    'card_type' => $request->card_type ?? 'Cash',
                    'payment_transaction_id' => ($request->card_type === 'Cash' || empty($request->card_type)) ? null : $request->payment_transaction_id,
                    'amount' => $totalPrice,
                    'payment_date' => now(),
                ]);
            }
            Log::info('Transaction updated/created successfully');

            // Update room status if room changed
            if ($originalRoomId != $request->room_id) {
                Log::info('Room changed, updating room statuses:', [
                    'old_room_id' => $originalRoomId,
                    'new_room_id' => $request->room_id
                ]);

                // Set old room back to available
                Room::where('room_id', $originalRoomId)->update([
                    'room_status' => 'Available',
                    'status' => false,
                ]);

                // Set new room to occupied
                Room::where('room_id', $request->room_id)->update([
                    'room_status' => 'Occupied',
                    'status' => true,
                ]);

                Log::info('Room statuses updated successfully');
            } else {
                Log::info('No room change detected');
            }

            Log::info('Room status updated if needed');

            // Update receipt if it exists
            $receipt = $booking->receipt;
            if ($receipt) {
                $receipt->update([
                    'total_amount' => $totalPrice,
                    'advance_payment' => $advancePayment,
                    'due_amount' => $dueAmount,
                    'payment_method' => $request->filled('card_type') ? $request->card_type : 'Cash',
                    'card_type' => $request->card_type,
                    'transaction_id' => $request->payment_transaction_id,
                    'notes' => $request->observations,
                    'status' => 'Paid', // Always paid since payment is made before booking
                ]);
            } else {
                // Create new receipt if none exists
                $receipt = Receipt::create([
                    'booking_id' => $booking->booking_id,
                    'receipt_number' => Receipt::generateReceiptNumber(),
                    'total_amount' => $totalPrice,
                    'advance_payment' => $advancePayment,
                    'due_amount' => $dueAmount,
                    'payment_method' => $request->filled('card_type') ? $request->card_type : 'Cash',
                    'card_type' => $request->card_type,
                    'transaction_id' => $request->payment_transaction_id,
                    'notes' => $request->observations,
                    'status' => 'Paid', // Always paid since payment is made before booking
                ]);
            }

            Log::info('Receipt updated/created successfully:', ['receipt_id' => $receipt->receipt_id]);

            DB::commit();

            return redirect()->route('bookings.show', $booking)->with('success', 'Booking updated successfully! Guest information has been modified.');
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Error updating booking: ' . $e->getMessage(), [
                'request_data' => $request->all(),
                'booking_id' => $booking->booking_id,
                'trace' => $e->getTraceAsString()
            ]);
            return back()->with('error', 'Error updating booking: ' . $e->getMessage())->withInput();
        }
    }

    public function destroy(Booking $booking)
    {
        DB::beginTransaction();
        try {
            // Update room status back to available
            Room::where('room_id', $booking->room_id)->update([
                'room_status' => 'Available',
                'status' => false,
            ]);

            // Delete booking customers
            $booking->bookingCustomers()->delete();

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

            DB::commit();

            return redirect()->route('bookings.index')->with('success', 'Booking deleted successfully!');
        } catch (\Exception $e) {
            DB::rollback();
            return back()->with('error', 'Error deleting booking: ' . $e->getMessage());
        }
    }

    public function checkIn(Booking $booking)
    {
        if ($booking->booking_status !== 'Confirmed') {
            return back()->with('error', 'Only confirmed bookings can be checked in.');
        }

        DB::beginTransaction();
        try {
            $booking->update([
                'booking_status' => 'Checked In',
                'checked_in_at' => now(),
            ]);

            // Update room status
            Room::where('room_id', $booking->room_id)->update([
                'room_status' => 'Occupied',
                'check_in_status' => true,
            ]);

            DB::commit();

            return back()->with('success', 'Guest checked in successfully!');
        } catch (\Exception $e) {
            DB::rollback();
            return back()->with('error', 'Error checking in: ' . $e->getMessage());
        }
    }

    public function checkOut(Booking $booking)
    {
        if ($booking->booking_status !== 'Checked In') {
            return back()->with('error', 'Only checked-in bookings can be checked out.');
        }

        DB::beginTransaction();
        try {
            $booking->update([
                'booking_status' => 'Checked Out',
                'checked_out_at' => now(),
            ]);

            // Update room status
            Room::where('room_id', $booking->room_id)->update([
                'room_status' => 'Available',
                'status' => false,
                'check_in_status' => false,
            ]);

            DB::commit();

            return back()->with('success', 'Guest checked out successfully!');
        } catch (\Exception $e) {
            DB::rollback();
            return back()->with('error', 'Error checking out: ' . $e->getMessage());
        }
    }

    public function getRoomPrice(Request $request)
    {
        $room = Room::find($request->room_id);
        if ($room) {
            return response()->json([
                'price' => $room->price_per_night ?? $room->roomType->price,
                'room_type' => $room->roomType->room_type,
                'capacity' => $room->capacity,
            ]);
        }
        return response()->json(['error' => 'Room not found'], 404);
    }

    public function getLatestBookingCustomer(Request $request)
    {
        $userId = $request->query('user_id') ?: Auth::id();
        $latest = BookingCustomer::where('user_id', $userId)
            ->orderBy('created_at', 'desc')
            ->first();

        if (!$latest) {
            return response()->json(['data' => null]);
        }

        return response()->json([
            'data' => [
                'user_id' => $latest->user_id,
                'document_number' => $latest->document_number,
                'document_type' => $latest->document_type,
                'first_name' => $latest->first_name,
                'last_name' => $latest->last_name,
                'nationality' => $latest->nationality,
                'origin_city' => $latest->origin_city,
                'phone' => $latest->phone,
                'email' => $latest->email,
            ]
        ]);
    }


}
