<?php

namespace App\Http\Controllers;

use App\Models\PriceHistory;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PriceHistoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        try {
            $query = PriceHistory::with(['product', 'user']);

            // Filter by product
            if ($request->has('product_id')) {
                $query->where('product_id', $request->product_id);
            }

            // Filter by price type
            if ($request->has('price_type')) {
                $query->where('price_type', $request->price_type);
            }

            // Filter by date range
            if ($request->has('start_date')) {
                $query->whereDate('created_at', '>=', $request->start_date);
            }

            if ($request->has('end_date')) {
                $query->whereDate('created_at', '<=', $request->end_date);
            }

            // Sorting
            $query->latest();

            $priceHistories = $query->paginate(20)->withQueryString();

            // Get products for filter
            $products = Product::whereHas('priceHistories')
                ->orderBy('name')
                ->get(['id', 'name', 'sku']);

            // Statistics
            $stats = [
                'total_changes' => PriceHistory::count(),
                'last_30_days' => PriceHistory::where('created_at', '>=', now()->subDays(30))->count(),
                'avg_price_change' => PriceHistory::avg(DB::raw('ABS(new_price - old_price)')),
                'most_changed_product' => PriceHistory::select('product_id')
                    ->selectRaw('COUNT(*) as changes')
                    ->groupBy('product_id')
                    ->orderByDesc('changes')
                    ->first(),
            ];

            return view('price-histories.index', compact('priceHistories', 'stats', 'products'));
            
        } catch (\Exception $e) {
            Log::error('PriceHistory index error: ' . $e->getMessage());
            return redirect()->route('dashboard')
                ->with('error', 'Failed to load price history. Please try again.');
        }
    }

    /**
     * Show price trends for a specific product.
     */
    public function trends(Request $request, Product $product)
    {
        try {
            // Get price history for this product
            $priceHistories = PriceHistory::where('product_id', $product->id)
                ->with('user')
                ->orderBy('created_at', 'desc')
                ->paginate(20);

            // Get price statistics
            $priceStats = [
                'current_price' => $product->sale_price,
                'current_cost' => $product->cost_price,
                'first_recorded_price' => PriceHistory::where('product_id', $product->id)
                    ->where('price_type', 'sale_price')
                    ->orderBy('created_at')
                    ->first()?->new_price ?? $product->sale_price,
                'highest_price' => PriceHistory::where('product_id', $product->id)
                    ->where('price_type', 'sale_price')
                    ->max('new_price') ?? $product->sale_price,
                'lowest_price' => PriceHistory::where('product_id', $product->id)
                    ->where('price_type', 'sale_price')
                    ->min('new_price') ?? $product->sale_price,
                'total_changes' => $priceHistories->total(),
                'last_change' => $priceHistories->first()?->created_at,
            ];

            // Get price change frequency
            $changeFrequency = PriceHistory::where('product_id', $product->id)
                ->selectRaw('price_type, COUNT(*) as count')
                ->groupBy('price_type')
                ->get();

            return view('price-histories.trends', compact('product', 'priceHistories', 'priceStats', 'changeFrequency'));
            
        } catch (\Exception $e) {
            Log::error('Price trends error: ' . $e->getMessage());
            return redirect()->route('products.show', $product)
                ->with('error', 'Failed to load price trends.');
        }
    }

    /**
     * Compare prices between products.
     */
    public function compare(Request $request)
    {
        try {
            $productIds = $request->input('product_ids', []);
            
            if (empty($productIds)) {
                $products = Product::whereHas('priceHistories')
                    ->orderBy('name')
                    ->limit(5)
                    ->get();
                $productIds = $products->pluck('id')->toArray();
            }

            $products = Product::whereIn('id', $productIds)
                ->with(['priceHistories' => function($query) {
                    $query->where('price_type', 'sale_price')
                          ->orderBy('created_at', 'desc')
                          ->limit(10);
                }])
                ->get();

            // Get all products for selection
            $allProducts = Product::whereHas('priceHistories')
                ->orderBy('name')
                ->get(['id', 'name', 'sku']);

            return view('price-histories.compare', compact('products', 'allProducts'));
            
        } catch (\Exception $e) {
            Log::error('Price compare error: ' . $e->getMessage());
            return redirect()->route('price-histories.index')
                ->with('error', 'Failed to load price comparison.');
        }
    }

    /**
     * Export price history.
     */
    public function export(Request $request)
    {
        try {
            $query = PriceHistory::with(['product', 'user']);

            // Apply filters
            if ($request->has('product_id')) {
                $query->where('product_id', $request->product_id);
            }

            if ($request->has('start_date')) {
                $query->whereDate('created_at', '>=', $request->start_date);
            }

            if ($request->has('end_date')) {
                $query->whereDate('created_at', '<=', $request->end_date);
            }

            $priceHistories = $query->get();

            $fileName = 'price-history-' . date('Y-m-d') . '.csv';
            $headers = [
                'Content-Type' => 'text/csv',
                'Content-Disposition' => "attachment; filename=$fileName",
            ];

            $callback = function() use ($priceHistories) {
                $file = fopen('php://output', 'w');
                
                // Add BOM for UTF-8
                fwrite($file, "\xEF\xBB\xBF");
                
                // Headers
                fputcsv($file, [
                    'Date', 'Product', 'SKU', 'Price Type', 'Old Price', 'New Price',
                    'Change Amount', 'Change %', 'Changed By', 'Reason', 'Notes'
                ]);
                
                // Data
                foreach ($priceHistories as $history) {
                    $changeAmount = $history->new_price - $history->old_price;
                    $changePercent = $history->old_price > 0 ? 
                        ($changeAmount / $history->old_price) * 100 : 0;
                    
                    fputcsv($file, [
                        $history->created_at->format('Y-m-d H:i:s'),
                        $history->product->name ?? '',
                        $history->product->sku ?? '',
                        ucfirst(str_replace('_', ' ', $history->price_type)),
                        $history->old_price,
                        $history->new_price,
                        $changeAmount,
                        round($changePercent, 2) . '%',
                        $history->user->name ?? 'System',
                        $history->change_reason ?? '',
                        $history->notes ?? '',
                    ]);
                }
                
                fclose($file);
            };

            return response()->stream($callback, 200, $headers);
            
        } catch (\Exception $e) {
            Log::error('Price history export error: ' . $e->getMessage());
            return redirect()->route('price-histories.index')
                ->with('error', 'Failed to export price history.');
        }
    }

    /**
     * Get price analytics dashboard.
     */
    public function analytics()
    {
        try {
            // Recent price changes
            $recentChanges = PriceHistory::with(['product', 'user'])
                ->latest()
                ->limit(10)
                ->get();

            // Price change statistics
            $stats = [
                'total_changes_today' => PriceHistory::whereDate('created_at', today())->count(),
                'total_changes_week' => PriceHistory::where('created_at', '>=', now()->subWeek())->count(),
                'total_changes_month' => PriceHistory::where('created_at', '>=', now()->subMonth())->count(),
                'avg_daily_changes' => PriceHistory::where('created_at', '>=', now()->subMonth())
                    ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
                    ->groupBy('date')
                    ->avg('count'),
                'most_active_products' => PriceHistory::select('product_id')
                    ->selectRaw('COUNT(*) as changes')
                    ->where('created_at', '>=', now()->subMonth())
                    ->groupBy('product_id')
                    ->orderByDesc('changes')
                    ->limit(5)
                    ->with('product')
                    ->get(),
                'largest_increase' => PriceHistory::select('*')
                    ->addSelect(DB::raw('(new_price - old_price) as increase'))
                    ->where('new_price', '>', 'old_price')
                    ->orderByDesc('increase')
                    ->with('product')
                    ->first(),
                'largest_decrease' => PriceHistory::select('*')
                    ->addSelect(DB::raw('(old_price - new_price) as decrease'))
                    ->where('new_price', '<', 'old_price')
                    ->orderByDesc('decrease')
                    ->with('product')
                    ->first(),
            ];

            // Price change trends
            $trends = PriceHistory::selectRaw('
                DATE(created_at) as date,
                price_type,
                COUNT(*) as changes,
                AVG(new_price - old_price) as avg_change
            ')
                ->where('created_at', '>=', now()->subMonth())
                ->groupBy('date', 'price_type')
                ->orderBy('date')
                ->get();

            return view('price-histories.analytics', compact('recentChanges', 'stats', 'trends'));
            
        } catch (\Exception $e) {
            Log::error('Price analytics error: ' . $e->getMessage());
            return redirect()->route('dashboard')
                ->with('error', 'Failed to load price analytics.');
        }
    }
}