<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{
    /**
     * Homepage with search & smart pagination
     */
public function index(Request $request)
{
    $tab = $request->get('tab', 'all');
    $search = $request->get('search', '');
    
    $sliders = DB::table('sliders')
        ->orderBy('sort_order', 'asc')
        ->orderBy('created_at', 'desc')
        ->get();
    
    // POPULAR GAMES
    $popularGames = DB::table('categories')
        ->where('categories.is_active', true)
        ->where('categories.is_popular', true)
        ->where('categories.category_type', 'game')
        ->leftJoin('products', function($join) {
            $join->on('categories.id', '=', 'products.category_id')
                ->where('products.seller_product_status', true);
        })
        ->select('categories.*', DB::raw('COUNT(DISTINCT products.id) as product_count'))
        ->groupBy('categories.id', 'categories.name', 'categories.manual_name', 'categories.slug', 
                  'categories.brand_code', 'categories.brand', 'categories.category_type', 
                  'categories.icon', 'categories.description', 'categories.manual_description', 
                  'categories.api_filter', 'categories.input_type', 'categories.image', 
                  'categories.manual_image', 'categories.banner', 'categories.sort_order', 
                  'categories.is_active', 'categories.is_popular', 'categories.popularity_score',
                  'categories.created_at', 'categories.updated_at')
        ->orderBy('categories.sort_order', 'asc')
        ->limit(6)
        ->get();
    
    // POPULAR VOUCHERS
    $popularVouchers = DB::table('categories')
        ->where('categories.is_active', true)
        ->where('categories.is_popular', true)
        ->where('categories.category_type', 'voucher')
        ->leftJoin('products', function($join) {
            $join->on('categories.id', '=', 'products.category_id')
                ->where('products.seller_product_status', true);
        })
        ->select('categories.*', DB::raw('COUNT(DISTINCT products.id) as product_count'))
        ->groupBy('categories.id', 'categories.name', 'categories.manual_name', 'categories.slug', 
                  'categories.brand_code', 'categories.brand', 'categories.category_type', 
                  'categories.icon', 'categories.description', 'categories.manual_description', 
                  'categories.api_filter', 'categories.input_type', 'categories.image', 
                  'categories.manual_image', 'categories.banner', 'categories.sort_order', 
                  'categories.is_active', 'categories.is_popular', 'categories.popularity_score',
                  'categories.created_at', 'categories.updated_at')
        ->orderBy('categories.sort_order', 'asc')
        ->limit(6)
        ->get();
    
    $query = DB::table('categories')
        ->where('categories.is_active', true)
        ->orderBy('categories.sort_order', 'asc')
        ->orderBy('categories.created_at', 'desc');
    
    if (!empty($search)) {
        $query->where(function($q) use ($search) {
            $q->where('categories.name', 'like', "%{$search}%")
              ->orWhere('categories.description', 'like', "%{$search}%");
        });
    }
    
    if ($tab !== 'all') {
        $query->where('categories.category_type', $tab);
    }
    
    $query->leftJoin('products', function($join) {
        $join->on('categories.id', '=', 'products.category_id')
            ->where('products.seller_product_status', true);
    })
    ->select('categories.*', DB::raw('COUNT(DISTINCT products.id) as product_count'))
    ->groupBy('categories.id', 'categories.name', 'categories.manual_name', 'categories.slug', 
              'categories.brand_code', 'categories.brand', 'categories.category_type', 
              'categories.icon', 'categories.description', 'categories.manual_description', 
              'categories.api_filter', 'categories.input_type', 'categories.image', 
              'categories.manual_image', 'categories.banner', 'categories.sort_order', 
              'categories.is_active', 'categories.is_popular', 'categories.popularity_score',
              'categories.created_at', 'categories.updated_at');
    
    // ✅ SIMPLIFIED PAGINATION LOGIC
    if (!empty($search)) {
        // SEARCH MODE: Show all results (no pagination)
        $allCategories = $query->get();
        $perPage = $allCategories->count() > 0 ? $allCategories->count() : 1;
        $categories = new \Illuminate\Pagination\LengthAwarePaginator(
            $allCategories,
            $allCategories->count(),
            $perPage,
            1,
            ['path' => $request->url(), 'query' => $request->query()]
        );
    } else {
        // ✅ PAGINATE ALL TABS (all, game, voucher)
        $categories = $query->paginate(25)->withQueryString();
    }
    
    if ($request->ajax()) {
        $html = '';
        foreach ($categories as $category) {
            $image = $category->image 
                ? '<img src="'.asset('storage/' . $category->image).'" alt="'.$category->name.'" class="w-full h-full object-cover group-hover:scale-110 transition duration-500">'
                : '<div class="w-full h-full bg-gradient-to-br from-cyan-500/20 to-purple-500/20 flex items-center justify-center"><i class="fas fa-gamepad text-6xl text-cyan-400/50"></i></div>';
                
            $type = $category->category_type ?? 'game';
            $desc = $category->description ?? 'Top up cepat & murah';
            $count = $category->product_count ?? 0;

            $html .= '
            <div class="bg-gray-900 rounded-2xl border border-gray-800 hover:border-cyan-500 transition overflow-hidden group card-hover fade-in-up">
                <a href="/'.$type.'/'.$category->slug.'">
                    <div class="aspect-square relative overflow-hidden">
                        '.$image.'
                        <div class="absolute inset-0 bg-gradient-to-t from-gray-900 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition duration-300"></div>
                    </div>
                    <div class="p-4">
                        <h3 class="font-bold text-white mb-1 line-clamp-1 group-hover:text-cyan-400 transition">'.$category->name.'</h3>
                        <p class="text-sm text-gray-400 line-clamp-2">'.$desc.'</p>
                        <div class="mt-2 flex items-center justify-between text-xs text-gray-500">
                            <span><i class="fas fa-tag text-cyan-400 mr-1"></i>'.$count.' Produk</span>
                            <span><i class="fas fa-bolt text-green-400 mr-1"></i>Instan</span>
                        </div>
                    </div>
                </a>
            </div>';
        }
        return response()->json([
            'html' => $html,
            'hasMore' => $categories->hasMorePages()
        ]);
    }

    return view('store', compact('categories', 'sliders', 'popularGames', 'popularVouchers'));
}

    /**
     * Products by category/game
     */
 public function productsByCategory($type, $slug)
{
    $category = DB::table('categories')
        ->where('slug', $slug)
        ->where('is_active', true)
        ->first();

    if (!$category) abort(404);

    $products = DB::table('products')
        ->where('category_id', $category->id)
        ->where('seller_product_status', true)
        ->orderBy('selling_price')
        ->get();

    // Get reviews
    $reviews = collect();
    $averageRating = 0;
    $totalReviews = 0;
    
    if ($products->isNotEmpty()) {
        $productIds = $products->pluck('id')->toArray();
        
        $reviews = DB::table('reviews')
            ->whereIn('product_id', $productIds)
            ->where('status', 'approved')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();
        
        $averageRating = round(DB::table('reviews')
            ->whereIn('product_id', $productIds)
            ->where('status', 'approved')
            ->avg('rating') ?? 0, 1);
        
        $totalReviews = DB::table('reviews')
            ->whereIn('product_id', $productIds)
            ->where('status', 'approved')
            ->count();
    }

    // ⭐⭐⭐ USE NEW getConfig() WITH DROPDOWN SUPPORT!
    $config = $this->getConfig($category);
    
    // Special case: PLN
    if ($slug === 'pln') {
        $config['id_label'] = 'Nomor Meter / ID Pelanggan';
        $config['id_placeholder'] = 'Masukkan 11-12 digit nomor meter';
        $config['id_icon'] = 'fa-bolt';
    }

    // ⭐ VIEW = 'products' (BUKAN 'products.show')
    return view('products', compact('category', 'products', 'config', 'reviews', 'averageRating', 'totalReviews'));
}

private function getConfig($category)
{
    $slug = strtolower($category->slug);
    
    // ============================================
    // TYPE A: User ID Only (Numeric)
    // ============================================
    
    // Free Fire
    if (in_array($slug, ['free-fire', 'ff', 'freefire'])) {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 1234567890',
            'id_icon' => 'fa-id-card',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // PUBG Mobile
    if (in_array($slug, ['pubg-mobile', 'pubg'])) {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 5123456789',
            'id_icon' => 'fa-id-card',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // Call of Duty Mobile
    if (in_array($slug, ['cod-mobile', 'call-of-duty-mobile', 'codm'])) {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 6512345678',
            'id_icon' => 'fa-id-card',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // Arena of Valor
    if (in_array($slug, ['arena-of-valor', 'aov'])) {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 1234567890',
            'id_icon' => 'fa-id-card',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // Lords Mobile
    if (in_array($slug, ['lords-mobile'])) {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 123456789',
            'id_icon' => 'fa-id-card',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // ============================================
    // TYPE B: User ID + Zone ID (Numeric + Numeric)
    // ============================================
    
    // Mobile Legends
    if (in_array($slug, ['mobile-legends', 'ml', 'mlbb', 'mobile-legends-a', 'mobile-legends-b'])) {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 12345678',
            'id_icon' => 'fa-id-card',
            'show_zone' => true,
            'zone_type' => 'text',
            'zone_label' => 'Zone ID',
            'zone_placeholder' => 'Contoh: 2605',
            'zone_icon' => 'fa-map-marker-alt',
            'is_voucher' => false,
        ];
    }
    
    // Marvel Super War
    if (in_array($slug, ['marvel-super-war', 'msw'])) {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 1234567890',
            'id_icon' => 'fa-id-card',
            'show_zone' => true,
            'zone_type' => 'text',
            'zone_label' => 'Zone ID',
            'zone_placeholder' => 'Contoh: 3001',
            'zone_icon' => 'fa-map-marker-alt',
            'is_voucher' => false,
        ];
    }
    // Magic Chess GO GO
    if (in_array($slug, ['magic-chess', 'magic-chess-go-go', 'mcgg'])) {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 12345678',
            'id_icon' => 'fa-id-card',
            'show_zone' => true,
            'zone_type' => 'text',
            'zone_label' => 'Server ID',
            'zone_placeholder' => 'Contoh: 2001',
            'zone_icon' => 'fa-server',
            'is_voucher' => false,
        ];
    }
    
    // ============================================
    // TYPE C: UID + Server (Numeric + Dropdown)
    // ============================================
    
    // Genshin Impact
    if (in_array($slug, ['genshin-impact', 'genshin'])) {
        return [
            'id_label' => 'UID (User ID)',
            'id_placeholder' => 'Contoh: 800000000',
            'id_icon' => 'fa-id-card',
            'show_zone' => true,
            'zone_type' => 'dropdown',
            'zone_label' => 'Server',
            'zone_placeholder' => 'Pilih Server',
            'zone_icon' => 'fa-server',
            'zone_options' => [
                'os_asia' => 'Asia',
                'os_usa' => 'America',
                'os_euro' => 'Europe',
                'os_cht' => 'TW, HK, MO'
            ],
            'is_voucher' => false,
        ];
    }
    
    // Honkai Star Rail
    if (in_array($slug, ['honkai-star-rail', 'hsr'])) {
        return [
            'id_label' => 'UID (User ID)',
            'id_placeholder' => 'Contoh: 600000000',
            'id_icon' => 'fa-id-card',
            'show_zone' => true,
            'zone_type' => 'dropdown',
            'zone_label' => 'Server',
            'zone_placeholder' => 'Pilih Server',
            'zone_icon' => 'fa-server',
            'zone_options' => [
                'prod_official_asia' => 'Asia',
                'prod_official_usa' => 'America',
                'prod_official_euro' => 'Europe',
                'prod_official_cht' => 'TW, HK, MO'
            ],
            'is_voucher' => false,
        ];
    }
    
    // Ragnarok M
    if (in_array($slug, ['ragnarok-m', 'ragnarok-eternal-love'])) {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 12345678',
            'id_icon' => 'fa-id-card',
            'show_zone' => true,
            'zone_type' => 'dropdown',
            'zone_label' => 'Server',
            'zone_placeholder' => 'Pilih Server',
            'zone_icon' => 'fa-server',
            'zone_options' => [
                'eternal_love' => 'Eternal Love (SEA)',
                'memory_faith' => 'Memory of Faith (China)',
                'new_generation' => 'New Generation (Global)'
            ],
            'is_voucher' => false,
        ];
    }
    
    // Dragons Raja
    if (in_array($slug, ['dragons-raja'])) {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 123456789',
            'id_icon' => 'fa-id-card',
            'show_zone' => true,
            'zone_type' => 'dropdown',
            'zone_label' => 'Server',
            'zone_placeholder' => 'Pilih Server',
            'zone_icon' => 'fa-server',
            'zone_options' => [
                'celestial' => 'Celestial',
                'nidavellir' => 'Nidavellir',
                'asgard' => 'Asgard'
            ],
            'is_voucher' => false,
        ];
    }
    
    // ============================================
    // TYPE D: Username/Riot ID (Text)
    // ============================================
    
    // League of Legends Wild Rift
    if (in_array($slug, ['lol-wild-rift', 'wild-rift', 'lolwr'])) {
        return [
            'id_label' => 'Riot ID',
            'id_placeholder' => 'Contoh: PlayerName#1234',
            'id_icon' => 'fa-user',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // Valorant
    if (in_array($slug, ['valorant'])) {
        return [
            'id_label' => 'Riot ID',
            'id_placeholder' => 'Contoh: PlayerName#1234',
            'id_icon' => 'fa-user',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // Roblox
    if (in_array($slug, ['roblox'])) {
        return [
            'id_label' => 'Username',
            'id_placeholder' => 'Contoh: PlayerName123',
            'id_icon' => 'fa-user',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // Point Blank
    if (in_array($slug, ['point-blank', 'pb'])) {
        return [
            'id_label' => 'Username',
            'id_placeholder' => 'Contoh: PlayerName',
            'id_icon' => 'fa-user',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // ============================================
    // TYPE E: Player Tag (Text with #)
    // ============================================
    
    // Clash of Clans
    if (in_array($slug, ['clash-of-clans', 'coc'])) {
        return [
            'id_label' => 'Player Tag',
            'id_placeholder' => 'Contoh: #ABC123XYZ',
            'id_icon' => 'fa-hashtag',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // Clash Royale
    if (in_array($slug, ['clash-royale'])) {
        return [
            'id_label' => 'Player Tag',
            'id_placeholder' => 'Contoh: #123ABC456',
            'id_icon' => 'fa-hashtag',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // Brawl Stars
    if (in_array($slug, ['brawl-stars'])) {
        return [
            'id_label' => 'Player Tag',
            'id_placeholder' => 'Contoh: #12ABC34',
            'id_icon' => 'fa-hashtag',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // ============================================
    // TYPE F: Character Name + Server (Text + Dropdown)
    // ============================================
    
    // Ragnarok Origin
    if (in_array($slug, ['ragnarok-origin'])) {
        return [
            'id_label' => 'Character Name',
            'id_placeholder' => 'Contoh: MyCharacter',
            'id_icon' => 'fa-user',
            'show_zone' => true,
            'zone_type' => 'dropdown',
            'zone_label' => 'Server',
            'zone_placeholder' => 'Pilih Server',
            'zone_icon' => 'fa-server',
            'zone_options' => [
                'valhalla' => 'Valhalla',
                'midgard' => 'Midgard',
                'asgard' => 'Asgard'
            ],
            'is_voucher' => false,
        ];
    }
    
 // ============================================
    // VOUCHERS
    // ============================================
    
    if ($category->category_type === 'voucher') {
        return [
            'id_label' => 'Nomor HP / Email',
            'id_placeholder' => 'Masukkan Nomor HP atau Email',
            'id_icon' => 'fa-envelope',
            'show_zone' => false, // <--- WAJIB ADA INI BIAR GAK ERROR
            'is_voucher' => true,
        ];
    }
    
    // ============================================
    // FALLBACK: Use old getInputConfig()
    // ============================================
    
    return [
    'id_label' => 'User ID',
    'id_placeholder' => 'Masukkan User ID',
    'id_icon' => 'fa-id-card',
    'show_zone' => false,
    'is_voucher' => false,
];
}

    /**
     * Track order page
     */
    public function trackOrder(Request $request)
    {
        $orderId = $request->input('order_id');
        
        if (!$orderId) {
            return redirect('/')->with('error', 'Order ID tidak ditemukan');
        }
        
        // Get transaction by invoice_number
        $transaction = DB::table('transactions')
            ->leftJoin('products', 'transactions.product_id', '=', 'products.id')
            ->leftJoin('categories', 'products.category_id', '=', 'categories.id')
            ->where('transactions.invoice_number', $orderId)
            ->select(
                'transactions.*',
                'products.name as product_name',
                'products.sku as product_sku',
                'categories.name as category_name'
            )
            ->first();
        
        if (!$transaction) {
            return view('track-order', [
                'found' => false,
                'order_id' => $orderId
            ]);
        }
        
        return view('track-order', [
            'found' => true,
            'transaction' => $transaction
        ]);
    }

    /**
     * User dashboard
     */
    public function dashboard()
    {
        $user = Auth::user();

        // Get user transactions
        $transactions = DB::table('transactions')
            ->leftJoin('products', 'transactions.product_id', '=', 'products.id')
            ->leftJoin('categories', 'products.category_id', '=', 'categories.id')
            ->where('transactions.customer_email', $user->email)
            ->select('transactions.*', 'products.name as product_name', 'categories.name as category_name')
            ->orderBy('transactions.created_at', 'desc')
            ->paginate(10);

        // Get user stats
        $stats = DB::table('transactions')
            ->where('customer_email', $user->email)
            ->selectRaw('
                COUNT(*) as total_transactions,
                SUM(CASE WHEN status = "success" THEN 1 ELSE 0 END) as success_count,
                SUM(CASE WHEN status = "pending" THEN 1 ELSE 0 END) as pending_count,
                SUM(CASE WHEN status = "success" THEN total_amount ELSE 0 END) as total_spent
            ')
            ->first();

        return view('account.dashboard', compact('transactions', 'stats'));
    }

    /**
     * Search categories and products (Legacy - Optional)
     */
    public function search(Request $request)
    {
        $query = $request->input('q', '');
        
        if (strlen($query) < 2) {
            return redirect('/')->with('info', 'Masukkan minimal 2 karakter untuk pencarian');
        }

        // Get sliders for consistent UI
        $sliders = DB::table('sliders')
            ->orderBy('sort_order', 'asc')
            ->orderBy('created_at', 'desc')
            ->get();

        // Search in categories with product count
        $categories = DB::table('categories')
            ->where('categories.is_active', true)
            ->where(function($q) use ($query) {
                $q->where('categories.name', 'like', "%{$query}%")
                  ->orWhere('categories.description', 'like', "%{$query}%");
            })
            ->leftJoin('products', function($join) {
                $join->on('categories.id', '=', 'products.category_id')
                    ->where('products.seller_product_status', true);
            })
            ->select('categories.*', DB::raw('COUNT(DISTINCT products.id) as product_count'))
            ->groupBy('categories.id', 'categories.name', 'categories.slug', 'categories.brand_code', 
                      'categories.category_type', 'categories.input_type', 'categories.description', 
                      'categories.api_filter', 'categories.is_active', 'categories.sort_order', 
                      'categories.image', 'categories.created_at', 'categories.updated_at')
            ->get();

        $totalResults = $categories->count();

        return view('search', compact('categories', 'sliders', 'query', 'totalResults'));
    }
/**
 * API: Realtime search categories (AJAX)
 */
/**
 * API: Realtime search categories (AJAX)
 */
public function apiSearchCategories(Request $request)
{
    try {
        $search = $request->get('q', '');
        $tab = $request->get('tab', 'all');
        
        // Minimal 2 karakter
        if (strlen($search) < 2) {
            return response()->json([
                'categories' => [], 
                'total' => 0,
                'search_term' => $search
            ]);
        }
        
        // Trim & clean search query
        $search = trim($search);
        
        // Build query dengan TABLE PREFIX ✅
        $query = DB::table('categories')
            ->where('categories.is_active', true);  // ✅ Add prefix!
        
        // Search filter
        $query->where(function($q) use ($search) {
            $q->where('categories.name', 'LIKE', '%' . $search . '%')  // ✅ Add prefix!
              ->orWhere('categories.description', 'LIKE', '%' . $search . '%');  // ✅ Add prefix!
        });
        
        // Tab filter
        if ($tab !== 'all') {
            $query->where('categories.category_type', $tab);  // ✅ Add prefix!
        }
        
        // Add product count
        $query->leftJoin('products', function($join) {
            $join->on('categories.id', '=', 'products.category_id')
                ->where('products.seller_product_status', true);
        })
        ->select('categories.*', DB::raw('COUNT(DISTINCT products.id) as product_count'))
        ->groupBy(
            'categories.id', 
            'categories.name', 
            'categories.slug', 
            'categories.brand_code', 
            'categories.category_type', 
            'categories.input_type', 
            'categories.description', 
            'categories.api_filter', 
            'categories.is_active', 
            'categories.sort_order', 
            'categories.image', 
            'categories.created_at', 
            'categories.updated_at'
        )
        ->orderBy('categories.sort_order', 'asc')
        ->limit(20);
        
        $categories = $query->get();
        
        return response()->json([
            'categories' => $categories,
            'total' => $categories->count(),
            'search_term' => $search
        ]);
        
    } catch (\Exception $e) {
        // Log error
        \Log::error('API Search Error: ' . $e->getMessage());
        
        // Return error as JSON
        return response()->json([
            'error' => 'Search failed',
            'message' => $e->getMessage(),
            'categories' => [],
            'total' => 0
        ], 500);
    }
}
}

