<?php

namespace App\Http\Controllers\web\home;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Models\Cart;
use App\Models\Category;
use App\Models\Product;
use App\Models\SlideshowBanner;
use App\Models\Subscriber;
use App\Models\Visitor;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

class homeController extends Controller
{
    public function index(){
        try {
            // Common data for all users (Shared with layouts, fetched from cache)
            $categories = Cache::remember('layout_categories', 86400, function () {
                return Category::where('status', 1)->get();
            });
            
            // Optimization: Fetch and cache active product IDs first (10 minutes cache)
            $allProductIds = Cache::remember('active_product_ids', 600, function () {
                return Product::where('status', 1)
                    ->whereHas('productcolor')
                    ->pluck('id')
                    ->toArray();
            });
                
            $products = collect();
            if (!empty($allProductIds)) {
                $randomKeys = array_rand($allProductIds, min(12, count($allProductIds)));
                $randomIds = is_array($randomKeys) ? array_map(fn($k) => $allProductIds[$k], $randomKeys) : [$allProductIds[$randomKeys]];
                // Fetch products by selected IDs and shuffle them in-memory
                $products = Product::whereIn('id', $randomIds)->get()->shuffle();
            }

            // Featured products (NotNull cutted_price) (10 minutes cache)
            $featuredIds = Cache::remember('featured_product_ids', 600, function () {
                return Product::where('status', 1)
                    ->whereHas('productcolor')
                    ->whereNotNull('cutted_price')
                    ->pluck('id')
                    ->toArray();
            });
                
            $featured = collect();
            if (!empty($featuredIds)) {
                $randomKeysFeatured = array_rand($featuredIds, min(4, count($featuredIds)));
                $randomFeaturedIds = is_array($randomKeysFeatured) ? array_map(fn($k) => $featuredIds[$k], $randomKeysFeatured) : [$featuredIds[$randomKeysFeatured]];
                // Fetch featured products by selected IDs and shuffle them in-memory
                $featured = Product::whereIn('id', $randomFeaturedIds)->get()->shuffle();
            }

            $productCount = $products->count();

            // Fetch Banner and SlideshowBanner from cache to prevent database queries
            $banner = Cache::remember('home_banner', 86400, function () {
                return Banner::find(1);
            });
            $heroSlides = Cache::remember('home_hero_slides', 86400, function () {
                return SlideshowBanner::where('status', 1)->orderBy('order', 'asc')->get();
            });

            // Fetch wishlist product IDs if the user is authenticated to avoid N+1 queries in the loop
            $wishlistProductIds = [];
            $cart_product = collect();
            $totalPrice = 0;

            if (auth()->check()) {
                $user = auth()->user();
                if ($user && $user->id) {
                    $wishlistProductIds = \App\Models\Wishlist::where('user_id', $user->id)->pluck('product_id')->toArray();
                    $cart_product = Cart::where('userid', $user->id)->take(2)->get();
                    $totalPrice = $cart_product->sum('product_price');
                }
            }

            return view('web.home.index', compact(
                'categories', 
                'products', 
                'productCount', 
                'featured', 
                'banner', 
                'heroSlides', 
                'wishlistProductIds', 
                'cart_product', 
                'totalPrice'
            ));

        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
            
            // Abort with 500 error instead of redirecting to the same route, preventing infinite loops.
            abort(500, 'An unexpected error occurred on the homepage. Our team has been notified.');
        }
    }

    public function coming_soon(){
        return view('web.home.comingsoon');
    }

    public function subscriber_add(Request $request){
    // Validate the request to ensure email is present
    $request->validate([
        'subscriber_email' => 'required|email'
    ]);

    // Check if the email already exists in the database
      try {
         $existingSubscriber = Subscriber::where('email', $request->subscriber_email)->first();

    if ($existingSubscriber) {
        // Email already exists, redirect with a message
        return redirect()->back()->with('warning', 'This email is already subscribed.');
    }

    // Email does not exist, create a new subscriber
    $subscriber = new Subscriber();
    $subscriber->email = $request->subscriber_email;
    $subscriber->status = 1;
    $subscriber->save();

    // Redirect with a success message
    return redirect()->back()->with('success', 'You are subscribed successfully');
      } catch (\Throwable $th) {
        DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
           ]);
        return redirect()->route('american.plastic.web');
      }
    }



}
