<?php

use Illuminate\Support\Facades\Route;

// Customer site routes
Route::group(['prefix' => 'restaurant'], function () {
    Route::get('/my-loyalty/{hash}', function ($hash) {
        $restaurant = \App\Models\Restaurant::with('currency')->where('hash', $hash)->firstOrFail();
        
        // Check if module is enabled
        if (!function_exists('module_enabled') || !module_enabled('Loyalty')) {
            abort(404);
        }
        
        // Check if Loyalty module is in restaurant's package
        if (function_exists('restaurant_modules')) {
            $restaurantModules = restaurant_modules($restaurant);
            if (!in_array('Loyalty', $restaurantModules)) {
                abort(404);
            }
        }
        
        // Check if loyalty is enabled (but don't abort if both points/stamps are disabled)
        // The component and view will handle showing only enabled features
        $loyaltySettings = \Modules\Loyalty\Entities\LoyaltySetting::getForRestaurant($restaurant->id);
        if (!$loyaltySettings || !$loyaltySettings->isEnabled()) {
            abort(404);
        }
        
        // Get branch
        $shopBranch = null;
        if (request()->filled('branch')) {
            $branchParam = request('branch');
            $shopBranch = \App\Models\Branch::withoutGlobalScopes()
                ->where('unique_hash', $branchParam)
                ->orWhere('id', $branchParam)
                ->first();
        }
        if (!$shopBranch) {
            $shopBranch = $restaurant->branches->first();
        }
        
        // Redirect if subdomain is enabled
        if (function_exists('module_enabled') && module_enabled('Subdomain') && $restaurant->sub_domain) {
            $subdomainUrl = 'https://' . $restaurant->sub_domain . '/my-loyalty' . (request()->has('branch') ? '?branch=' . request('branch') : '');
            return redirect($subdomainUrl);
        }
        
        return view('loyalty::shop.customer-loyalty-account', compact('restaurant', 'shopBranch'));
    })->name('loyalty.customer.account');
});
