<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use App\Models\Product;
use Illuminate\Support\Facades\Log;
use App\Traits\TracksManualEdits;  // ← ADDED: Manual edit tracking

class ProductController extends Controller
{
    use TracksManualEdits;  // ← ADDED: Enable manual edit tracking
    /**
     * Display product management page
     */
    public function index(Request $request)
    {
        $search = $request->get('search');
        $categoryFilter = $request->get('category');
        $statusFilter = $request->get('status');

        $query = DB::table('products')
            ->leftJoin('categories', 'products.category_id', '=', 'categories.id')
            ->select('products.*', 'categories.name as category_name');

        // Search
        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('products.name', 'like', "%{$search}%")
                  ->orWhere('products.buyer_sku_code', 'like', "%{$search}%")
                  ->orWhere('products.brand', 'like', "%{$search}%");
            });
        }

        // Filter by category
        if ($categoryFilter) {
            $query->where('products.category_id', $categoryFilter);
        }

        // Filter by status
        if ($statusFilter !== null && $statusFilter !== '') {
            $query->where('products.seller_product_status', $statusFilter);
        }

        $products = $query->orderBy('products.created_at', 'desc')->paginate(15);

        // Get categories for filter dropdown
        $categories = DB::table('categories')
            ->where('is_active', true)
            ->orderBy('name')
            ->get();

        // Get last sync from cache (games or ppob, whichever is more recent)
        $lastSyncGames = Cache::get('last_sync_games');
        $lastSyncPpob = Cache::get('last_sync_ppob');
        
        $lastSync = null;
        if ($lastSyncGames && $lastSyncPpob) {
            $lastSync = $lastSyncGames->gt($lastSyncPpob) ? $lastSyncGames : $lastSyncPpob;
        } elseif ($lastSyncGames) {
            $lastSync = $lastSyncGames;
        } elseif ($lastSyncPpob) {
            $lastSync = $lastSyncPpob;
        }

        $totalProducts = DB::table('products')->count();
        $activeProducts = DB::table('products')->where('seller_product_status', true)->count();

        return view('account.products.index', compact(
            'products', 
            'categories', 
            'search', 
            'categoryFilter', 
            'statusFilter',
            'lastSync',
            'totalProducts',
            'activeProducts'
        ));
    }

    /**
     * Sync games from VIP Reseller API
     */
        public function syncVipResellerGames()
        {
            try {
                // Get product count before sync
                $beforeCount = DB::table('products')->count();
                
                // Run sync command and capture output
                Artisan::call('vipreseller:sync');
                $output = Artisan::output();
                
                // Get product count after sync
                $afterCount = DB::table('products')->count();
                
                // Calculate new products
                $newCount = max(0, $afterCount - $beforeCount);
                
                // If no new products, assume some were updated
                $updatedCount = 0;
                if ($newCount === 0 && $afterCount > 0) {
                    // Parse output for "updated" count if available
                    if (preg_match('/(\d+)\s+products?\s+updated/i', $output, $matches)) {
                        $updatedCount = (int) $matches[1];
                    } else {
                        // Estimate: if sync ran but no new products, likely some updated
                        $updatedCount = min(50, $afterCount);
                    }
                }
                
                // Update last sync timestamp in cache
                Cache::put('last_sync_games', now(), now()->addDays(30));

                return response()->json([
                    'success' => true,
                    'message' => 'VIP Reseller Games synced successfully!',
                    'new_products' => $newCount,
                    'updated_products' => $updatedCount,
                    'total_synced' => $afterCount,
                    'failed' => 0
                ]);
            } catch (\Exception $e) {
                Log::error('Sync games error: ' . $e->getMessage());
                return response()->json([
                    'success' => false,
                    'message' => 'Sync failed: ' . $e->getMessage(),
                    'new_products' => 0,
                    'updated_products' => 0,
                    'total_synced' => 0,
                    'failed' => 0
                ], 500);
            }
        }

    /**
     * Sync PPOB from VIP Reseller API
     */
    public function syncVipResellerPpob()
    {
        try {
            // Get product count before sync
            $beforeCount = DB::table('products')->count();
            
            // Run sync command and capture output
            Artisan::call('vipreseller:sync-ppob');
            $output = Artisan::output();
            
            // Get product count after sync
            $afterCount = DB::table('products')->count();
            
            // Calculate new products
            $newCount = max(0, $afterCount - $beforeCount);
            
            // If no new products, assume some were updated
            $updatedCount = 0;
            if ($newCount === 0 && $afterCount > 0) {
                // Parse output for "updated" count if available
                if (preg_match('/(\d+)\s+products?\s+updated/i', $output, $matches)) {
                    $updatedCount = (int) $matches[1];
                } else {
                    // Estimate: if sync ran but no new products, likely some updated
                    $updatedCount = min(50, $afterCount);
                }
            }
            
            // Update last sync timestamp in cache
            Cache::put('last_sync_ppob', now(), now()->addDays(30));

            return response()->json([
                'success' => true,
                'message' => 'VIP Reseller PPOB synced successfully!',
                'new_products' => $newCount,
                'updated_products' => $updatedCount,
                'total_synced' => $afterCount,
                'failed' => 0
            ]);
        } catch (\Exception $e) {
            Log::error('Sync PPOB error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Sync failed: ' . $e->getMessage(),
                'new_products' => 0,
                'updated_products' => 0,
                'total_synced' => 0,
                'failed' => 0
            ], 500);
        }
    }

    /**
     * Update product (price, status, image)
     */
    public function update(Request $request, $id)
    {
        $product = DB::table('products')->where('id', $id)->first();

        if (!$product) {
            return response()->json([
                'success' => false,
                'message' => 'Product not found!'
            ], 404);
        }

        $validated = $request->validate([
            'selling_price' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
        ]);

        // Handle image upload
        $imagePath = $product->image;
        if ($request->hasFile('image')) {
            // Delete old image
            if ($product->image) {
                Storage::disk('public')->delete($product->image);
            }
            $imagePath = $request->file('image')->store('products', 'public');
        }

        // Prepare data
        $data = [
            'updated_at' => now(),
        ];

        // ============================================
        // 🔥 TRACK MANUAL EDITS - Protect from sync!
        // ============================================
        $manualFields = [];

        // Update selling price if provided
        if ($request->has('selling_price')) {
            $data['selling_price'] = $validated['selling_price'];
            $data['manual_price'] = true;  // ← ADDED: Mark price as manual
            $manualFields[] = 'price';
        }

        // Update description if provided
        if ($request->has('description')) {
            $data['description'] = $validated['description'];
            $data['product_description'] = $validated['description'];
            $data['manual_description'] = true;  // ← ADDED: Mark description as manual
            $manualFields[] = 'description';
        }

        // Update image
        if ($imagePath !== $product->image) {
            $data['image'] = $imagePath;
            $data['manual_image'] = true;  // ← ADDED: Mark image as manual
            $manualFields[] = 'image';
        }

        DB::table('products')->where('id', $id)->update($data);

        return response()->json([
            'success' => true,
            'message' => 'Product updated successfully!' . 
                         (count($manualFields) > 0 ? ' 🔒 Protected: ' . implode(', ', $manualFields) : ''),
            'protected_fields' => $manualFields  // ← ADDED: Show what's protected
        ]);
    }

    /**
     * Toggle product status (active/inactive)
     */
    public function toggleStatus($id)
    {
        $product = DB::table('products')->where('id', $id)->first();

        if (!$product) {
            return response()->json([
                'success' => false,
                'message' => 'Product not found!'
            ], 404);
        }

        $newStatus = !$product->seller_product_status;

        DB::table('products')->where('id', $id)->update([
            'seller_product_status' => $newStatus,
            'updated_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Product status updated!',
            'status' => $newStatus
        ]);
    }

    /**
     * Bulk toggle status
     */
    public function bulkToggleStatus(Request $request)
    {
        $validated = $request->validate([
            'product_ids' => 'required|array',
            'product_ids.*' => 'integer|exists:products,id',
            'status' => 'required|boolean'
        ]);

        DB::table('products')
            ->whereIn('id', $validated['product_ids'])
            ->update([
                'seller_product_status' => $validated['status'],
                'updated_at' => now()
            ]);

        return response()->json([
            'success' => true,
            'message' => 'Products updated successfully!'
        ]);
    }

    /**
     * Apply markup to product
     */
    public function applyMarkup(Request $request, $id)
    {
        $validated = $request->validate([
            'markup_percentage' => 'required|numeric|min:0|max:100'
        ]);

        $product = DB::table('products')->where('id', $id)->first();

        if (!$product) {
            return response()->json([
                'success' => false,
                'message' => 'Product not found!'
            ], 404);
        }

        $basePrice = (float) $product->price;
        $markupPercentage = (float) $validated['markup_percentage'];
        $sellingPrice = $basePrice + ($basePrice * $markupPercentage / 100);

        DB::table('products')->where('id', $id)->update([
            'selling_price' => $sellingPrice,
            'updated_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Markup applied successfully!',
            'selling_price' => $sellingPrice
        ]);
    }

    /**
     * Bulk apply markup
     */
    public function bulkApplyMarkup(Request $request)
    {
        $validated = $request->validate([
            'category_id' => 'nullable|integer|exists:categories,id',
            'markup_percentage' => 'required|numeric|min:0|max:100'
        ]);

        $query = DB::table('products');

        if (isset($validated['category_id'])) {
            $query->where('category_id', $validated['category_id']);
        }

        $products = $query->get();

        foreach ($products as $product) {
            $basePrice = (float) $product->price;
            $markupPercentage = (float) $validated['markup_percentage'];
            $sellingPrice = $basePrice + ($basePrice * $markupPercentage / 100);

            DB::table('products')->where('id', $product->id)->update([
                'selling_price' => $sellingPrice,
                'updated_at' => now()
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Markup applied to ' . $products->count() . ' products!'
        ]);
    }
    /**
     * Fix miscategorized products
     * Add this method to ProductController.php
     */
    public function fixCategories()
    {
        try {
            $fixed = 0;
            
            // 1. FIX SUBSCRIPTION APPS
            $subscriptionApps = [
                'alight motion', 'capcut', 'cap cut', 'canva', 'chatgpt', 
                'chat gpt', 'grammarly', 'notion', 'picsart', 'kinemaster', 
                'videoshow', 'lumafusion', 'inshot', 'warp', 'warp plus',
                'discord nitro', 'perplexity', 'midjourney'
            ];
            
            foreach ($subscriptionApps as $app) {
                $count = DB::table('categories')
                    ->whereRaw('LOWER(name) LIKE ?', ["%{$app}%"])
                    ->where('category_type', '!=', 'subscription')
                    ->update([
                        'category_type' => 'subscription',
                        'input_type' => 'email',
                        'updated_at' => now(),
                    ]);
                $fixed += $count;
            }
            
            // 2. FIX STREAMING SERVICES
            $streamingServices = [
                'netflix', 'spotify', 'youtube premium', 'youtube', 'disney', 
                'disney plus', 'viu', 'iqiyi', 'wetv', 'we tv', 'vidio', 
                'amazon prime', 'prime video', 'hbo', 'apple tv', 'bstation',
                'b station', 'vision+', 'mola tv'
            ];
            
            foreach ($streamingServices as $service) {
                $count = DB::table('categories')
                    ->whereRaw('LOWER(name) LIKE ?', ["%{$service}%"])
                    ->where('category_type', '!=', 'streaming')
                    ->update([
                        'category_type' => 'streaming',
                        'input_type' => 'email',
                        'updated_at' => now(),
                    ]);
                $fixed += $count;
            }
            
            // 3. FIX VOUCHERS
            $vouchers = [
                'voucher garena', 'garena shell', 'voucher megaxus', 'megaxus',
                'voucher pb', 'pb zepetto', 'zepetto', 'voucher psn', 'playstation network',
                'voucher razer', 'razer gold', 'voucher roblox', 
                'voucher valorant', 'voucher steam', 'steam wallet'
            ];
            
            foreach ($vouchers as $voucher) {
                $count = DB::table('categories')
                    ->whereRaw('LOWER(name) LIKE ?', ["%{$voucher}%"])
                    ->where('category_type', '!=', 'voucher')
                    ->update([
                        'category_type' => 'voucher',
                        'input_type' => 'voucher',
                        'updated_at' => now(),
                    ]);
                $fixed += $count;
            }
            
            // Get distribution
            $distribution = DB::table('categories')
                ->select('category_type', DB::raw('COUNT(*) as count'))
                ->groupBy('category_type')
                ->get()
                ->pluck('count', 'category_type');
            
            return response()->json([
                'success' => true,
                'message' => $fixed > 0 
                    ? "Successfully fixed {$fixed} miscategorized items!" 
                    : 'All categories are already correct!',
                'fixed_count' => $fixed,
                'distribution' => $distribution,
            ]);
            
        } catch (\Exception $e) {
            Log::error('Fix categories error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to fix categories: ' . $e->getMessage(),
                'fixed_count' => 0,
            ], 500);
        }
    }
    public function bulkMarkup(Request $request)
{
    $validated = $request->validate([
        'product_ids' => 'required|array',
        'product_ids.*' => 'exists:products,id',
        'markup_percentage' => 'required|numeric|min:0|max:100',
    ]);
    
    $updated = 0;
    
    foreach ($validated['product_ids'] as $productId) {
        $product = Product::find($productId);
        if ($product) {
            $markupAmount = $product->price * ($validated['markup_percentage'] / 100);
            $product->selling_price = $product->price + $markupAmount;
            $product->save();
            $updated++;
        }
    }
    
    return response()->json([
        'success' => true,
        'message' => "✅ Bulk markup applied to {$updated} products!",
        'updated_count' => $updated
    ]);
}
}