<?php

namespace App\Http\Controllers\API\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProductManagementController extends Controller
{
    public function index(Request $request)
    {
        try {
            $query = Product::with(['restaurant', 'category']);
            
            if ($request->restaurant_id) {
                $query->where('restaurant_id', $request->restaurant_id);
            }
            
            if ($request->status) {
                if ($request->status === 'available') {
                    $query->where('is_available', true);
                } elseif ($request->status === 'unavailable') {
                    $query->where('is_available', false);
                }
            }
            
            if ($request->search) {
                $query->where(function($q) use ($request) {
                    $q->where('name', 'like', '%' . $request->search . '%')
                      ->orWhere('description', 'like', '%' . $request->search . '%');
                });
            }
            
            $products = $query->latest()->paginate($request->per_page ?? 20);
            
            return response()->json([
                'success' => true,
                'data' => $products
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function store(Request $request)
    {
        try {
            $request->validate([
                'restaurant_id' => 'required|exists:restaurants,id',
                'name' => 'required|string|max:255',
                'description' => 'nullable|string',
                'price' => 'nullable|numeric|min:0',
                'discount' => 'nullable|numeric|min:0',
                'category_id' => 'required|exists:categories,id',
                'image' => 'nullable|image|max:3072'
            ]);
            
            // Check for duplicate product name in same restaurant
            $exists = Product::where('restaurant_id', $request->restaurant_id)
                ->where('name', $request->name)
                ->exists();
            
            if ($exists) {
                return response()->json([
                    'success' => false,
                    'message' => 'A product with this name already exists in this restaurant'
                ], 422);
            }
            
            $data = [
                'restaurant_id' => $request->restaurant_id,
                'name' => $request->name,
                'description' => $request->description,
                'price' => $request->price ?? 0,
                'discount' => $request->discount ?? 0,
                'category_id' => $request->category_id,
                'is_available' => true
            ];
            
            if ($request->hasFile('image')) {
                $path = $request->file('image')->store('products', 'public');
                $data['image'] = $path;
            }
            
            $product = Product::create($data);
            
            // Handle variation prices
            if ($request->variation_prices) {
                $variationPrices = json_decode($request->variation_prices, true);
                $variationDiscounts = $request->variation_discounts ? json_decode($request->variation_discounts, true) : [];
                
                if ($variationPrices) {
                    foreach ($variationPrices as $categoryVariationId => $price) {
                        if ($price > 0) {
                            $categoryVariation = \App\Models\CategoryVariation::find($categoryVariationId);
                            if ($categoryVariation) {
                                \App\Models\ProductVariation::create([
                                    'product_id' => $product->id,
                                    'category_variation_id' => $categoryVariationId,
                                    'name' => $categoryVariation->name,
                                    'price' => $price,
                                    'discount' => $variationDiscounts[$categoryVariationId] ?? 0
                                ]);
                            }
                        }
                    }
                }
            }
            
            // Handle addon prices
            if ($request->addon_prices) {
                $addonPrices = json_decode($request->addon_prices, true);
                
                if ($addonPrices) {
                    foreach ($addonPrices as $categoryAddonId => $price) {
                        if ($price > 0) {
                            $categoryAddon = \App\Models\CategoryAddon::find($categoryAddonId);
                            if ($categoryAddon) {
                                \App\Models\ProductAddon::create([
                                    'product_id' => $product->id,
                                    'category_addon_id' => $categoryAddonId,
                                    'name' => $categoryAddon->name,
                                    'price' => $price
                                ]);
                            }
                        }
                    }
                }
            }
            
            return response()->json([
                'success' => true,
                'message' => 'Product created successfully',
                'data' => $product
            ]);
        } catch (\Exception $e) {
            \Log::error('Product creation error: ' . $e->getMessage());
            \Log::error('Stack trace: ' . $e->getTraceAsString());
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function show($id)
    {
        try {
            $product = Product::with(['restaurant', 'category', 'variations', 'addons'])->findOrFail($id);
            
            return response()->json([
                'success' => true,
                'data' => $product
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Product not found'
            ], 404);
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $product = Product::findOrFail($id);
            
            // Check for duplicate product name in same restaurant (excluding current product)
            if ($request->filled('name') && $request->filled('restaurant_id')) {
                $exists = Product::where('restaurant_id', $request->restaurant_id)
                    ->where('name', $request->name)
                    ->where('id', '!=', $id)
                    ->exists();
                
                if ($exists) {
                    return response()->json([
                        'success' => false,
                        'message' => 'A product with this name already exists in this restaurant'
                    ], 422);
                }
            }
            
            $data = [];
            
            if ($request->filled('restaurant_id')) $data['restaurant_id'] = $request->restaurant_id;
            if ($request->filled('name')) $data['name'] = $request->name;
            if ($request->filled('description')) $data['description'] = $request->description;
            if ($request->filled('price')) $data['price'] = $request->price;
            if ($request->filled('discount')) $data['discount'] = $request->discount;
            if ($request->filled('category_id')) $data['category_id'] = $request->category_id;
            
            if ($request->hasFile('image')) {
                if ($product->image) {
                    Storage::disk('public')->delete($product->image);
                }
                $data['image'] = $request->file('image')->store('products', 'public');
            }
            
            $product->update($data);
            
            // Handle variation prices update
            if ($request->variation_prices) {
                $variationPrices = json_decode($request->variation_prices, true);
                $variationDiscounts = $request->variation_discounts ? json_decode($request->variation_discounts, true) : [];
                
                if ($variationPrices) {
                    // Delete existing variations
                    $product->variations()->delete();
                    
                    // Create new variations
                    foreach ($variationPrices as $categoryVariationId => $price) {
                        if ($price > 0) {
                            $categoryVariation = \App\Models\CategoryVariation::find($categoryVariationId);
                            if ($categoryVariation) {
                                \App\Models\ProductVariation::create([
                                    'product_id' => $product->id,
                                    'category_variation_id' => $categoryVariationId,
                                    'name' => $categoryVariation->name,
                                    'price' => $price,
                                    'discount' => $variationDiscounts[$categoryVariationId] ?? 0
                                ]);
                            }
                        }
                    }
                }
            }
            
            // Handle addon prices update
            if ($request->addon_prices) {
                $addonPrices = json_decode($request->addon_prices, true);
                
                if ($addonPrices) {
                    // Delete existing addons
                    $product->addons()->delete();
                    
                    // Create new addons
                    foreach ($addonPrices as $categoryAddonId => $price) {
                        if ($price > 0) {
                            $categoryAddon = \App\Models\CategoryAddon::find($categoryAddonId);
                            if ($categoryAddon) {
                                \App\Models\ProductAddon::create([
                                    'product_id' => $product->id,
                                    'category_addon_id' => $categoryAddonId,
                                    'name' => $categoryAddon->name,
                                    'price' => $price
                                ]);
                            }
                        }
                    }
                }
            }
            
            return response()->json([
                'success' => true,
                'message' => 'Product updated successfully',
                'data' => $product->fresh()
            ]);
        } catch (\Exception $e) {
            \Log::error('Product update error: ' . $e->getMessage());
            \Log::error('Stack trace: ' . $e->getTraceAsString());
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $product = Product::findOrFail($id);
            
            if ($product->image) {
                Storage::disk('public')->delete($product->image);
            }
            
            $product->delete();
            
            return response()->json([
                'success' => true,
                'message' => 'Product deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function verify($id)
    {
        try {
            $product = Product::findOrFail($id);
            $product->update(['verification_status' => 'verified']);
            
            return response()->json([
                'success' => true,
                'message' => 'Product verified successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function reject(Request $request, $id)
    {
        try {
            $request->validate(['reason' => 'nullable|string']);
            
            $product = Product::findOrFail($id);
            $product->update([
                'verification_status' => 'rejected',
                'rejection_reason' => $request->reason
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Product rejected successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function toggleAvailability($id)
    {
        try {
            $product = Product::findOrFail($id);
            $product->update(['is_available' => !$product->is_available]);
            
            return response()->json([
                'success' => true,
                'message' => 'Product availability updated successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function toggleFeatured($id)
    {
        try {
            $product = Product::findOrFail($id);
            $product->update(['is_featured' => !$product->is_featured]);
            
            return response()->json([
                'success' => true,
                'message' => 'Product featured status updated successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function getDashboardStats()
    {
        try {
            $stats = [
                'total_products' => Product::count(),
                'pending_verification' => 0,
                'verified_products' => Product::count()
            ];
            
            return response()->json([
                'success' => true,
                'data' => $stats
            ]);
        } catch (\Exception $e) {
            \Log::error('Dashboard stats error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function exportProducts(Request $request)
    {
        try {
            $query = Product::with(['restaurant', 'category']);
            
            if ($request->restaurant_id) {
                $query->where('restaurant_id', $request->restaurant_id);
            }
            
            if ($request->status) {
                $query->where('verification_status', $request->status);
            }
            
            $products = $query->get();
            
            $filename = 'products_' . date('Y-m-d_His') . '.xls';
            
            $headers = [
                'Content-Type' => 'application/vnd.ms-excel',
                'Content-Disposition' => 'attachment; filename="' . $filename . '"',
                'Cache-Control' => 'max-age=0',
            ];
            
            $callback = function() use ($products) {
                echo "<html><head><meta charset='utf-8'></head><body><table border='1'>";
                echo "<tr style='background-color: #ff6b35; color: white; font-weight: bold;'>";
                echo "<th>ID</th><th>Name</th><th>Restaurant</th><th>Category</th><th>Price</th><th>Status</th><th>Verification</th><th>Created</th>";
                echo "</tr>";
                
                foreach ($products as $product) {
                    echo "<tr>";
                    echo "<td>" . $product->id . "</td>";
                    echo "<td>" . htmlspecialchars($product->name) . "</td>";
                    echo "<td>" . htmlspecialchars($product->restaurant->name ?? 'N/A') . "</td>";
                    echo "<td>" . htmlspecialchars($product->category->name ?? 'N/A') . "</td>";
                    echo "<td>Rs. " . number_format($product->price, 2) . "</td>";
                    echo "<td>" . ($product->is_available ? 'Available' : 'Unavailable') . "</td>";
                    echo "<td>" . ucfirst($product->verification_status ?? 'pending') . "</td>";
                    echo "<td>" . $product->created_at->format('Y-m-d H:i:s') . "</td>";
                    echo "</tr>";
                }
                
                echo "</table></body></html>";
            };
            
            return response()->stream($callback, 200, $headers);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function getRestaurants()
    {
        try {
            $restaurants = \App\Models\Restaurant::select('id', 'name')->get();
            
            return response()->json([
                'success' => true,
                'data' => $restaurants
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function getCategories()
    {
        try {
            $categories = Category::select('id', 'name')->get();
            
            return response()->json([
                'success' => true,
                'data' => $categories
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
    
    public function downloadTemplate(Request $request)
    {
        try {
            $filename = 'product_import_template_' . date('Y-m-d') . '.xls';
            
            $headers = [
                'Content-Type' => 'application/vnd.ms-excel',
                'Content-Disposition' => 'attachment; filename="' . $filename . '"',
                'Cache-Control' => 'max-age=0',
            ];
            
            $callback = function() {
                echo "<html><head><meta charset='utf-8'></head><body><table border='1'>";
                echo "<tr style='background-color: #ff6b35; color: white; font-weight: bold;'>";
                echo "<th>Restaurant ID</th><th>Category ID</th><th>Product Name</th><th>Description</th><th>Base Price</th><th>Discount</th>";
                echo "<th>Variation Name</th><th>Variation Price</th><th>Variation Discount</th>";
                echo "<th>Addon Name</th><th>Addon Price</th>";
                echo "</tr>";
                echo "<tr>";
                echo "<td>1</td><td>1</td><td>Chicken Pizza</td><td>Delicious pizza</td><td>1500</td><td>100</td>";
                echo "<td>Large</td><td>2000</td><td>150</td>";
                echo "<td>Extra Cheese</td><td>200</td>";
                echo "</tr>";
                echo "<tr>";
                echo "<td>1</td><td>1</td><td>Chicken Pizza</td><td></td><td></td><td></td>";
                echo "<td>Medium</td><td>1500</td><td>100</td>";
                echo "<td>Extra Toppings</td><td>150</td>";
                echo "</tr>";
                echo "</table></body></html>";
            };
            
            return response()->stream($callback, 200, $headers);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
    
    public function importProducts(Request $request)
    {
        try {
            $request->validate([
                'file' => 'required|file|mimes:xlsx,xls,csv'
            ]);
            
            $file = $request->file('file');
            $extension = $file->getClientOriginalExtension();
            
            // Read file content
            $content = file_get_contents($file->getRealPath());
            
            // Parse Excel/CSV
            $rows = [];
            if ($extension === 'csv') {
                $lines = explode("\n", $content);
                foreach ($lines as $line) {
                    $rows[] = str_getcsv($line);
                }
            } else {
                // Simple HTML table parser for .xls files
                preg_match_all('/<tr[^>]*>(.*?)<\/tr>/is', $content, $matches);
                foreach ($matches[1] as $row) {
                    preg_match_all('/<td[^>]*>(.*?)<\/td>/is', $row, $cells);
                    if (!empty($cells[1])) {
                        $rows[] = array_map('strip_tags', $cells[1]);
                    }
                }
            }
            
            if (count($rows) < 2) {
                return response()->json([
                    'success' => false,
                    'message' => 'File is empty or invalid'
                ], 400);
            }
            
            // Skip header row
            array_shift($rows);
            
            $imported = 0;
            $errors = [];
            $currentProduct = null;
            
            foreach ($rows as $index => $row) {
                try {
                    $restaurantId = trim($row[0] ?? '');
                    $categoryId = trim($row[1] ?? '');
                    $productName = trim($row[2] ?? '');
                    $description = trim($row[3] ?? '');
                    $basePrice = trim($row[4] ?? '');
                    $discount = trim($row[5] ?? '');
                    $variationName = trim($row[6] ?? '');
                    $variationPrice = trim($row[7] ?? '');
                    $variationDiscount = trim($row[8] ?? '');
                    $addonName = trim($row[9] ?? '');
                    $addonPrice = trim($row[10] ?? '');
                    
                    // Create or update product
                    if ($productName && $restaurantId && $categoryId) {
                        $currentProduct = Product::updateOrCreate(
                            [
                                'restaurant_id' => $restaurantId,
                                'name' => $productName
                            ],
                            [
                                'category_id' => $categoryId,
                                'description' => $description,
                                'price' => $basePrice ?: 0,
                                'discount' => $discount ?: 0,
                                'is_available' => true
                            ]
                        );
                        $imported++;
                    }
                    
                    // Add variation
                    if ($currentProduct && $variationName && $variationPrice) {
                        \App\Models\ProductVariation::updateOrCreate(
                            [
                                'product_id' => $currentProduct->id,
                                'name' => $variationName
                            ],
                            [
                                'price' => $variationPrice,
                                'discount' => $variationDiscount ?: 0
                            ]
                        );
                    }
                    
                    // Add addon
                    if ($currentProduct && $addonName && $addonPrice) {
                        \App\Models\ProductAddon::updateOrCreate(
                            [
                                'product_id' => $currentProduct->id,
                                'name' => $addonName
                            ],
                            [
                                'price' => $addonPrice
                            ]
                        );
                    }
                } catch (\Exception $e) {
                    $errors[] = "Row " . ($index + 2) . ": " . $e->getMessage();
                }
            }
            
            return response()->json([
                'success' => true,
                'message' => "Imported {$imported} products successfully",
                'errors' => $errors
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
}