<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class FlashSaleController extends Controller
{
    public function show(Request $request)
    {
        $isActive = Setting::where('key', 'flash_sale_active')->value('value') === '1';
        $startAt = Setting::where('key', 'flash_sale_start_at')->value('value');
        $endAt = Setting::where('key', 'flash_sale_end_at')->value('value');

        $products = Product::where('is_active', true)
            ->where('is_flash_sale', true)
            ->with('category')
            ->withAvg('reviews', 'rating')
            ->withCount('reviews')
            ->latest()
            ->take(8)
            ->get()
            ->map(function ($product) {
                $currentPrice = $product->discount_price > 0 ? $product->discount_price : $product->price;
                $oldPrice = $product->discount_price > 0 ? $product->price : null;

                return [
                    'id' => (string) $product->id,
                    'name' => $product->name,
                    'description' => strip_tags((string) $product->description),
                    'price' => (float) $currentPrice,
                    'oldPrice' => $oldPrice ? (float) $oldPrice : null,
                    'imageUrl' => $product->image_url ?? (Str::startsWith($product->image, ['http://', 'https://'])
                        ? $product->image
                        : route('public.media', ['path' => $product->image])),
                    'unit' => $product->unit,
                    'reviews_avg_rating' => $product->reviews_avg_rating !== null ? (float) $product->reviews_avg_rating : null,
                    'reviews_count' => (int) ($product->reviews_count ?? 0),
                    'rating' => $product->reviews_avg_rating !== null ? (float) $product->reviews_avg_rating : 0,
                    'isPopular' => (bool) $product->is_featured,
                    'categoryId' => (string) $product->category_id,
                ];
            });

        $hasProducts = $products->count() > 0;
        $rawFlag = Setting::where('key', 'flash_sale_active')->value('value');
        $effectiveActive = $rawFlag === '1' || ($rawFlag === null && $hasProducts);

        return response()->json([
            'status' => 'success',
            'data' => [
                'is_active' => $effectiveActive,
                'start_at' => $startAt,
                'end_at' => $endAt,
                'products' => $products,
            ],
        ]);
    }
}
