HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux ip-10-0-8-47 6.8.0-1021-aws #23~22.04.1-Ubuntu SMP Tue Dec 10 16:31:58 UTC 2024 aarch64
User: ubuntu (1000)
PHP: 8.1.2-1ubuntu2.22
Disabled: NONE
Upload Files
File: /var/www/javago-portal-updates/app/Http/Controllers/API/CafeAuthController.php
<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Helpers\Aws;
use App\Models\Cafe;
use App\Models\CafeTiming;
use App\Models\Addon;
use App\Models\AddonSize;
use App\Models\CafeMenu;
use App\Models\CafeMenuItem;
use App\Models\CafeMenuItemSize;
use App\Models\CafeFilter;
use App\Models\CafeManagement;
use App\Models\CafeClickCollectTiming;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Models\CafeSubscription;
use App\Models\PromoCodes;
use Illuminate\Support\Str;

class CafeAuthController extends Controller
{


    //Is email Exists
    public function isEmailExists(Request $request)
    {
        try {
            // Validate the incoming request
            $validator = Validator::make($request->all(), [
                'email' => 'required|email',
            ]);

            // Handle validation errors
            if ($validator->fails()) {
                // Throw a ValidationException if validation fails
                throw new ValidationException($validator);
            }

            $cafe = Cafe::where('email', $request->email)->first();
            if ($cafe) {
                return response()->json([
                    'status' => 'Error',
                    'message' => 'Email Already Exists!',
                ], 403);
            } else {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Email Not Found! You can Proceed ahead.',
                ], 200);
            }

        } catch (ValidationException $validationException) {
            // Handle validation exception and return custom response
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle other exceptions
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while checking email existance.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    //Register
    public function register(Request $request)
    {
        try {
            // Validate the incoming request
            $validator = Validator::make($request->all(), [
                'email' => 'required|email',
                'password' => 'required|min:8',
            ]);

            // Handle validation errors
            if ($validator->fails()) {
                // Throw a ValidationException if validation fails
                throw new ValidationException($validator);
            }

            $cafe = Cafe::where('email', $request->email)->first();
            if ($cafe) {
                return response()->json([
                    'status' => 'Error',
                    'message' => 'Account Already Exists with this email!',
                ], 403);
            } else {

                DB::beginTransaction();
                // Create only email & password fields
                $create = [
                    'email' => $request->email,
                    'password' => bcrypt($request->password), // Secure password
                    'cafe_type' => 0,
                    'signup_completed' => 1,
                    'is_active' => 1,
                    'approved' => 1,
                    'created_at' => Carbon::now()->timestamp,
                    'updated_at' => Carbon::now()->timestamp,
                ];

                // Insert and get the ID
                $cafeId = Cafe::insertGetId($create);

                // Fetch the newly created user
                $cafe = Cafe::find($cafeId);

                // Assign role to the cafe owner (if using Spatie roles)
                $cafe->assignRole('cafe_admin');

                $cafeTime = [
                    'cafe_id' => $cafeId,
                    'open_time' => config('constants.cafe_timing.open_time'),
                    'close_time' => config('constants.cafe_timing.close_time'),
                    'is_active' => config('constants.cafe_timing.is_active'),
                    'created_at' => Carbon::now()->timestamp,
                    'updated_at' => Carbon::now()->timestamp,
                ];
                $cafeTiming = [];
                for ($i = 0; $i < 7; $i++) {
                    $cafeTime['day'] = $i;
                    array_push($cafeTiming, $cafeTime);
                }
                CafeTiming::insert($cafeTiming);

                // add cafe menu
                $cafeMenus = [
                    // [
                    //     'menu_name' => 'Drinks',
                    //     'cafe_id' => $cafeId,
                    //     'created_at' => Carbon::now()->timestamp,
                    //     'updated_at' => Carbon::now()->timestamp,
                    // ],
                    // [
                    //     'menu_name' => 'Pastries',
                    //     'cafe_id' => $cafeId,
                    //     'created_at' => Carbon::now()->timestamp,
                    //     'updated_at' => Carbon::now()->timestamp,
                    // ],
                    [
                        'menu_name' => 'Hot Drinks',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Tea',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Bakery',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Sandwiches',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Iced drinks',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Smoothies',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Bagles',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Salads',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Wraps',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Snacks',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Bottled Drinks',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Breakfast Options',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Bubble Tea',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Cakes',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Coffee',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Hot Chocolate',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Soft Drinks',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Brunch',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Breakfast',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Lunch',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Main Meals',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Desserts',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Soup',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Milkshakes',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Kids Menu',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Seasonal',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Vegan Options',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Matcha',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Juice',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Coffee Beans and Other Retail',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Other',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Unique',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'menu_name' => 'Bundles',
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                ];
                CafeMenu::insert($cafeMenus);

                // add addons
                $addons = [
                    [
                        'addon_name' => "Milk",
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'addon_name' => "Sugar",
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'addon_name' => "Syrup",
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'addon_name' => "Other",
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'addon_name' => "Added Taste",
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'addon_name' => "Add on",
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                    [
                        'addon_name' => "Bubble Tea Add on",
                        'cafe_id' => $cafeId,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ],
                ];
                Addon::insert($addons);

                // add addon sizes
                $addonSizes = [];
                $addon = Addon::where('cafe_id', $cafeId)->get();
                foreach ($addon as $key => $value) {
                    switch ($value->addon_name) {
                        case 'Milk':
                            $addonSize = [
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'No milk',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Whole milk',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Semi skimmed milk',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Oat milk',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Soya milk',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Almond milk',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Skimmed milk',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Coconut milk',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                            ];
                            array_push($addonSizes, $addonSize);
                            break;

                        case 'Sugar':
                            $addonSize = [
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'White sugar',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Brown sugar',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Sweetener',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                            ];
                            array_push($addonSizes, $addonSize);
                            break;

                        case 'Syrup':
                            $addonSize = [
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Vanilla',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Hazelnut',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Caramel',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Salted caramel',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Mint',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Almond',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Mocha/Chocolate',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Coconut',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Cinnamon',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Toffee Nut',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Macadamia Nut',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Raspberry',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Strawberry',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Blueberry',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Cherry',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Peach',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Mango',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Passionfruit',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Pomegranate',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Orange',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Pumpkin Spice',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Peppermint',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Gingerbread',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Maple',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Irish Cream',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Amaretto',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Butter Pecan',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Sugar-Free Vanilla',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Sugar-Free Caramel',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Sugar-Free Hazelnut',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Pistachio',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Walnut',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Peanut Butter',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Matcha',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                            ];
                            array_push($addonSizes, $addonSize);
                            break;

                        case 'Other':
                            $addonSize = [
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Decaf',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Extra shot',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Espresso',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                            ];
                            array_push($addonSizes, $addonSize);
                            break;
                        case 'Added Taste':
                            $addonSize = [
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Ginger',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Mint',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Honey',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                            ];
                            array_push($addonSizes, $addonSize);
                            break;
                        case 'Add on':
                            $addonSize = [
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Marshmallow',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Whipped cream',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                            ];
                            array_push($addonSizes, $addonSize);
                            break;
                        case 'Bubble Tea Add on':
                            $addonSize = [
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Blueberry popping ball',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Lychee popping ball',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Mango popping ball',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Passionfruit popping ball',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Strawberry popping ball',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Green Apple popping ball',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Black pearls',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Mango jelly',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Lychee jelly',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Coconut jelly',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Rainbow jelly',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Coffee jelly',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Grass jelly',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Extra popping bubble',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Extra tapioca',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Jelly',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Make it fizzy',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'No ice',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Extra boba',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Taro powder',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Crystal boba',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Honey boba',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                                [
                                    'addon_id' => $value->id,
                                    'cafe_id' => $cafeId,
                                    'addon_size_name' => 'Aloe vera chunks',
                                    'addon_size_price' => 0,
                                    'created_at' => Carbon::now()->timestamp,
                                    'updated_at' => Carbon::now()->timestamp,
                                ],
                            ];
                            array_push($addonSizes, $addonSize);
                            break;
                        default:
                            break;
                    }
                }
                for ($i = 0; $i < sizeof($addonSizes); $i++) {
                    AddonSize::insert($addonSizes[$i]);
                }
                DB::commit();
                $token = $cafe->createToken('CafeAppToken')->plainTextToken;
                return response()->json([
                    'status' => 'Success',
                    'message' => 'Account Created Successfully!',
                    'token' => $token,
                ], 200);
            }


        } catch (ValidationException $validationException) {
            // Handle validation exception and return custom response
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle other exceptions
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while Registeration.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function getCafeInformationSuggestions(Request $request)
    {
        try {
            $cafe = Cafe::find($request->user->id);
            if (!$cafe) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cafe not found.',
                ], 404);
            }
            $cafeFilters = CafeFilter::all();
            $cafeTimings = CafeTiming::where('cafe_id', $cafe->id)->get();
            return response()->json([
                'status' => 'success',
                'cafeFilters' => $cafeFilters,
                'cafeTimings' => $cafeTimings,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while fetching cafe information.',
                'error' => $e->getMessage(),
            ], 500);
        }

    }

    //Add cafe Information
    public function updateCafeInformation(Request $request)
    {
        try {
            // Validate the incoming request
            $validator = Validator::make($request->all(), [
                'name' => 'required',
                'phone' => 'required',
                'address' => 'required',
                'postcode' => 'required',
                'latitude' => 'required',
                'longitude' => 'required',
                'categories' => 'required',
                'bio' => 'required',
                'image' => 'nullable',
                'coffee_origin' => 'nullable',
                'coffee_roast' => 'nullable',
                'coffee_origin_country' => 'nullable',
                'speciallity_coffee' => 'nullable|integer',
            ]);

            // Handle validation errors
            if ($validator->fails()) {
                // Throw a ValidationException if validation fails
                throw new ValidationException($validator);
            }

            // Find the cafe
            $cafe = Cafe::find($request->user->id);

            // Update the cafe information
            $cafe->cafe_name = $request->name;
            $cafe->phone = $request->phone;
            $cafe->city = $request->city ?? null;
            $cafe->address = $request->address;
            $cafe->postcode = $request->postcode;
            $cafe->latitude = $request->latitude ?? 0;
            $cafe->longitude = $request->longitude ?? 0;
            $cafe->cafe_filter = $request->categories;
            $cafe->bio = $request->bio;
            if (isset($request->image) && is_file($request->image)) {
                $cafe->banner_image = Aws::uploadImageS3Bucket('images/cafe', $request->image, '');
            }
            $cafe->profile_completed = 1;
            $cafe->save();

            // Update or create CafeManagement information
            $cafeManagement = CafeManagement::updateOrCreate(
                ['cafe_id' => $cafe->id], // Match by cafe_id
                [
                    'coffee_origin' => $request->coffee_origin,
                    'coffee_roast' => $request->coffee_roast,
                    'coffee_origin_country' => $request->coffee_origin_country,
                    'speciallity_coffee' => $request->speciallity_coffee,
                ]
            );
            $cafe->cafe_management = $cafeManagement;
            return response()->json([
                'status' => 'success',
                'message' => 'Cafe information updated successfully!',
                'cafe' => $cafe,
            ], 200);

        } catch (ValidationException $validationException) {
            // Handle validation exception and return custom response
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle other exceptions
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while updating cafe information.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    //update Cafe Hours
    public function updateCafeHours(Request $request)
    {
        try {
            DB::beginTransaction();
            $cafe = Cafe::find($request->user->id);
            $cafeTimings = $request->cafe;
            CafeTiming::where('cafe_id', $cafe->id)->chunk(100, function ($cafeTimingsBatch) use ($cafeTimings) {
                foreach ($cafeTimingsBatch as $cafeTiming) {
                    // Find the corresponding day in the request data
                    $day = $cafeTiming->day;

                    if (isset($cafeTimings[$day])) {
                        // Prepare the data for the update
                        $cafe_time = [
                            'open_time' => $cafeTimings[$day]['open_time'],
                            'close_time' => $cafeTimings[$day]['close_time'],
                            'is_active' => isset($cafeTimings[$day]['is_active']) ? $cafeTimings[$day]['is_active'] : 0,
                            'updated_at' => Carbon::now()->timestamp,
                        ];

                        // Update the cafe timing for the specific day
                        $cafeTiming->update($cafe_time);
                    }
                }
            });
            DB::commit();
            return response()->json([
                'status' => 'success',
                'message' => 'Cafe hours updated successfully!',
            ], 200);

        } catch (ValidationException $validationException) {
            // Handle validation exception and return custom response
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle other exceptions
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while updating cafe hours.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    //update Click and collect
    public function updateClickCollect(Request $request)
    {
        try {
            // Validate the incoming request
            $validator = Validator::make($request->all(), [
                'click_and_collect' => 'required|integer',
                'max_orders_click_collect' => 'nullable|required_if:click_and_collect,1',
            ]);

            // Handle validation errors
            if ($validator->fails()) {
                // Throw a ValidationException if validation fails
                throw new ValidationException($validator);
            }

            // Find the cafe
            $cafe = Cafe::find($request->user->id);
            $cafeManagement = CafeManagement::updateOrCreate(
                ['cafe_id' => $cafe->id], // Match by cafe_id
                [
                    'click_and_collect' => $request->click_and_collect,
                    'max_orders_click_collect' => $request->max_orders_click_collect,
                ]
            );

            return response()->json([
                'status' => 'success',
                'message' => 'Cafe click and collect updated successfully!',
            ], 200);

        } catch (ValidationException $validationException) {
            // Handle validation exception and return custom response
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle other exceptions
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while updating cafe click and collect.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }


    //update Cafe click and Collect hours
    public function updateClickCollectHours(Request $request)
    {
        try {
            DB::beginTransaction();

            $cafe = Cafe::find($request->user->id);
            $cafeTimings = $request->cafe;

            // Iterate through the request timings and handle chunked updates or creation
            CafeClickCollectTiming::where('cafe_id', $cafe->id)->chunk(100, function ($cafeTimingsBatch) use ($cafeTimings, $cafe) {
                foreach ($cafeTimingsBatch as $cafeTiming) {
                    // Find the corresponding day in the request data
                    $day = $cafeTiming->day;

                    if (isset($cafeTimings[$day])) {
                        // Prepare the data for the update
                        $cafe_time = [
                            'start_time' => $cafeTimings[$day]['open_time'],
                            'end_time' => $cafeTimings[$day]['close_time'],
                            'is_active' => isset($cafeTimings[$day]['is_active']) ? $cafeTimings[$day]['is_active'] : 0,
                            'updated_at' => Carbon::now()->timestamp,
                        ];

                        // Update the cafe click and collect timing for the specific day
                        $cafeTiming->update($cafe_time);
                    }
                }
            });

            // Now handle the case where there are cafe timings in the request that do not exist yet
            foreach ($cafeTimings as $day => $timing) {
                $existingCafeTiming = CafeClickCollectTiming::where('cafe_id', $cafe->id)->where('day', $day)->first();

                // If no record exists for this day, create a new one
                if (!$existingCafeTiming) {
                    CafeClickCollectTiming::create([
                        'cafe_id' => $cafe->id,
                        'day' => $day,
                        'start_time' => $timing['open_time'],
                        'end_time' => $timing['close_time'],
                        'is_active' => isset($timing['is_active']) ? $timing['is_active'] : 0,
                        'created_at' => Carbon::now()->timestamp,
                        'updated_at' => Carbon::now()->timestamp,
                    ]);
                }
            }

            DB::commit();

            return response()->json([
                'status' => 'success',
                'message' => 'Cafe click and collect hours updated successfully!',
            ], 200);

        } catch (ValidationException $validationException) {
            // Handle validation exception and return custom response
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle other exceptions
            DB::rollBack(); // Rollback transaction if an error occurs
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while updating cafe click and collect hours.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }


    //login
    public function cafeLogin(Request $request)
    {
        try {
            // Validate the incoming request
            $validator = Validator::make($request->all(), [
                'email' => 'required|email',
                'password' => 'required|min:8',
            ]);

            // Handle validation errors
            if ($validator->fails()) {
                // Throw a ValidationException if validation fails
                throw new ValidationException($validator);
            }

            // Check if the user exists in the database
            $user = Cafe::where('email', $request->email)->first();

            if (!$user) {
                return response()->json(['message' => 'Invalid credentials.'], 401);
            }

            // Attempt to authenticate the user
            if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
                // Authentication passed, create a token
                $token = $user->createToken('CafeAppToken')->plainTextToken;

                return response()->json([
                    'status' => 'success',
                    'message' => 'Login successful.',
                    'token' => $token,
                ], 200);
            } else {
                return response()->json(['message' => 'Invalid credentials.'], 401);
            }
        } catch (ValidationException $validationException) {
            // Handle validation exception and return custom response
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle other exceptions
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while logging in.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function cafeProfile(Request $request)
    {
        try {
            if ($request->user) {
                // Check if the user exists in the database
                $user = Cafe::where('id', $request->user->id)->with('timing')->with('cafeManagement')->with('CafeClickCollectTiming')->get();
                $cafeSubscription = CafeSubscription::where('cafe_id', $request->user->id)->first();

                $user[0]->subscriptionstatus = $cafeSubscription ? 1 : 0;
                return response()->json([
                    'status' => 'success',
                    'message' => 'Profile fetched successfully!',
                    'user' => $user,
                ], 200);
            } else {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Profile Not found!',
                    'user' => null,
                ], 404);
            }



        } catch (ValidationException $validationException) {
            // Handle validation exception and return custom response
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle other exceptions
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while gtting Profile.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    //link stripe Account
    public function linkStripeAccount(Request $request)
    {
        try {
            // Validate the incoming request
            $validator = Validator::make($request->all(), [
                'account_id' => 'required',
            ]);

            // Handle validation errors
            if ($validator->fails()) {
                // Throw a ValidationException if validation fails
                throw new ValidationException($validator);
            }
            $cafe = Cafe::find($request->user->id);
            $cafe->stripe_account_id = $request->account_id;
            $cafe->stripe_onboarding_completed = 1;
            $cafe->save();
            return response()->json([
                'status' => 'success',
                'message' => 'Stripe Account linked successfully!',
                'cafe' => $cafe,
            ], 200);

        } catch (ValidationException $validationException) {
            // Handle validation exception and return custom response
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle other exceptions
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while linking Stripe Account.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    //update publishing status
    public function updatePublishingStatus(Request $request)
    {
        try {
            $cafe = Cafe::find($request->user->id);
            $cafe->is_published = 1;
            $cafe->save();
            return response()->json([
                'status' => 'success',
                'message' => 'Cafe Published successfully!',
                'cafe' => $cafe,
            ], 200);

        } catch (ValidationException $validationException) {
            // Handle validation exception and return custom response
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle other exceptions
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while publishing Cafe.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
    public function updatePassword(Request $request)
    {
        try {
            // Validate the incoming request
            $validator = Validator::make($request->all(), [
                'current_password' => 'required|min:8',
                'new_password' => 'required|min:8', // Ensure new_password_confirmation is included
            ]);

            // Handle validation errors
            if ($validator->fails()) {
                throw new ValidationException($validator);
            }

            $cafe = Cafe::find($request->user->id);

            // Check if the cafe exists
            if (!$cafe) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cafe not found!',
                ], 404);
            }

            // Compare current password with stored hash
            if (!Hash::check($request->current_password, $cafe->password)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Current password is incorrect.',
                ], 400);
            }

            // Hash the new password and update it
            $cafe->password = bcrypt($request->new_password);
            $cafe->save();

            return response()->json([
                'status' => 'success',
                'message' => 'Password updated successfully!',
                'cafe' => $cafe,
            ], 200);

        } catch (ValidationException $validationException) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while updating the password.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function myCafePosition(Request $request)
    {
        try {
            $cafe = Cafe::find($request->user->id);
            if (!$cafe) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cafe not found.',
                ], 404);
            }

            // Assuming you have a method to calculate the rank based on cafe data
            $position = Cafe::where('id', '<', $cafe->id)->count() + 1;

            return response()->json([
                'status' => 'success',
                'message' => 'Cafe position fetched successfully!',
                'position' => $position,
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while fetching cafe rank.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function updateFcmToken(Request $request)
    {
        try {
            // Validate the incoming request
            $validator = Validator::make($request->all(), [
                'fcm_token' => 'required',
            ]);

            // Handle validation errors
            if ($validator->fails()) {
                throw new ValidationException($validator);
            }

            $cafe = Cafe::find($request->user->id);

            // Check if the cafe exists
            if (!$cafe) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cafe not found!',
                ], 404);
            }

            $cafe->fcm_token = $request->fcm_token;
            $cafe->save();

            return response()->json([
                'status' => 'success',
                'message' => 'FCM token updated successfully!',
                'cafe' => $cafe,
            ], 200);

        } catch (ValidationException $validationException) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while updating the fcm token.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function getCafeSubscription(Request $request)
    {
        try {
            $cafe = Cafe::find($request->user->id);
            if (!$cafe) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cafe not found.',
                ], 404);
            }

            $subscription = $cafe->cafeSubscription;

            return response()->json([
                'status' => 'success',
                'message' => 'Cafe subscription fetched successfully!',
                'subscription' => $subscription,
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while fetching cafe subscription.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function updateCafeSubscription(Request $request)
    {
        try {
            // Validate the incoming request
            $validator = Validator::make($request->all(), [
                'subscription_type' => 'required|string',
                'plan_name' => 'required|string',
                'transaction_id' => 'required|string',
            ]);

            // Handle validation errors
            if ($validator->fails()) {
                throw new ValidationException($validator);
            }

            $cafe = Cafe::find($request->user->id);
            if (!$cafe) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cafe not found.',
                ], 404);
            }

            $subscription = CafeSubscription::updateOrCreate(
                ['cafe_id' => $cafe->id],
                [
                    'subscription_type' => $request->subscription_type,
                    'plan_name' => $request->plan_name,
                    'transaction_id' => $request->transaction_id,
                    'expiration_date' => $request->expiration_date ? Carbon::parse($request->expiration_date) : null,
                ]
            );

            return response()->json([
                'status' => 'success',
                'message' => 'Cafe subscription updated successfully!',
                'subscription' => $subscription,
            ], 200);

        } catch (ValidationException $validationException) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        }
    }


    public function getPromoCodeDetail(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'promo_code' => 'required|string',
            ]);

            if ($validator->fails()) {
                throw new ValidationException($validator);
            }

            $promo = PromoCodes::where('code', $request->promo_code)
                //->where('is_active', true)
                ->first();

            //if (!$promo) {
            //  return response()->json([
            //    'status' => 'error',
            //  'message' => 'Invalid or expired promo code.',
            // ], 404);
            //}

            $freeMonths = $promo->free_months ?? 0;
            $discount = $promo->discount_percent ?? "0";
            $fixed_price = $promo->fixed_price ?? 0;

            return response()->json([
                'status' => 'success',
                'message' => 'Promo code details fetched.',
                'promo' => [
                    'code' => $promo->code,
                    'free_months' => $freeMonths,
                    'discount' => $discount,
                    'fixed_price' => $fixed_price,
                    'type' => $promo->type,
                    'is_active' => $promo->is_active,
                    'price' => $promo->price ?? null,
                    'description' => match ($promo->type) {
                        'year_free_then_monthly' => "1 year free, then �{$promo->price}/mo",
                        'month_free_then_discount' => "1st month free, then {$discount}% off for 12 months",
                        default => "Promo code benefits available.",
                    },
                ]
            ]);

        } catch (ValidationException $validationException) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Something went wrong.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }



    public function applyPromoCode(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'promo_code' => 'required|string',
            ]);

            if ($validator->fails()) {
                throw new ValidationException($validator);
            }

            $cafe = Cafe::find($request->user->id);

            if (!$cafe) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cafe not found.',
                ], 404);
            }

            $promo = PromoCodes::where('code', $request->promo_code)
                ->where('is_active', true)
                ->first();

            if (!$promo) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Invalid or expired promo code.',
                ], 422);
            }

            $freeMonths = $promo->free_months ?? 0;
            $expirationDate = Carbon::now()->addMonths($freeMonths);

            $planName = $freeMonths == 12 ? 'Yearly' : 'Monthly';
            $subscriptionType = 'Promo'; // can also be 'Paid' if you want to keep same values
            $transactionId = 'PROMO-' . strtoupper(Str::random(10));

            // Save or update subscription
            $subscription = CafeSubscription::updateOrCreate(
                ['cafe_id' => $cafe->id],
                [
                    'subscription_type' => $subscriptionType,
                    'plan_name' => $planName,
                    'transaction_id' => $transactionId,
                    'expiration_date' => $expirationDate,
                    'promo_code' => $promo->code,
                    'promo_code_applied_at' => Carbon::now(),
                ]
            );

            // Optional: mark promo code as used
            $promo->is_active = 0;
            $promo->save();

            return response()->json([
                'status' => 'success',
                'message' => 'Promo code applied and subscription updated.',
                'subscription' => $subscription,
                'promo' => [
                    'code' => $promo->code,
                    'free_months' => $freeMonths,
                    'discount' => $promo->discount ?? 0,
                    'type' => $promo->type,
                    'description' => match ($promo->type) {
                        'year_free_then_monthly' => "1 year free, then �{$promo->price}/mo",
                        'month_free_then_discount' => "1st month free, then {$promo->discount}% off for 12 months",
                        default => "Promo code applied."
                    },
                ],
            ]);

        } catch (ValidationException $validationException) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed.',
                'errors' => $validationException->errors(),
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Something went wrong.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }


}