<?php

namespace App\Http\Controllers\Dashboard;

use Carbon\Carbon;
use App\Models\Sale\Sale;
use App\Models\Client\Client;
use App\Models\Product\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\InventoryMovement;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $start_date = $request->start_date ? Carbon::parse($request->start_date)->startOfDay() : Carbon::now()->startOfMonth();
        $end_date = $request->end_date ? Carbon::parse($request->end_date)->endOfDay() : Carbon::now()->endOfDay();

        // KPIs
        $total_sales = Sale::whereBetween('created_at', [$start_date, $end_date])->whereNull('deleted_at')->sum('total');
        $sales_count = Sale::whereBetween('created_at', [$start_date, $end_date])->whereNull('deleted_at')->count();
        $total_clients = Client::where('state', 1)->count();
        $total_debt = Sale::whereBetween('created_at', [$start_date, $end_date])->whereNull('deleted_at')->sum('debt');
        
        $inventory_entries = InventoryMovement::where('tipo', 'ENTRADA')
            ->whereBetween('created_at', [$start_date, $end_date])
            ->count();
        $inventory_exits = InventoryMovement::where('tipo', 'SALIDA')
            ->whereBetween('created_at', [$start_date, $end_date])
            ->count();

        // Top 5 Products (Sold by quantity)
        $top_products = DB::table('sale_details')
            ->join('products', 'sale_details.product_id', '=', 'products.id')
            ->select('products.title', DB::raw('SUM(sale_details.quantity) as total_sold'))
            ->whereBetween('sale_details.created_at', [$start_date, $end_date])
            ->groupBy('products.id', 'products.title')
            ->orderByDesc('total_sold')
            ->limit(5)
            ->get();

        // Top 5 Clients (by revenue)
        $top_clients = DB::table('sales')
            ->join('clients', 'sales.client_id', '=', 'clients.id')
            ->select('clients.full_name', DB::raw('SUM(sales.total) as total_spent'))
            ->whereBetween('sales.created_at', [$start_date, $end_date])
            ->whereNull('sales.deleted_at')
            ->groupBy('clients.id', 'clients.full_name')
            ->orderByDesc('total_spent')
            ->limit(5)
            ->get();

        // Payment Methods distribution
        $payment_methods = DB::table('sale_payments')
            ->select('method_payment', DB::raw('SUM(amount) as total'))
            ->whereBetween('created_at', [$start_date, $end_date])
            ->groupBy('method_payment')
            ->get();

        // Monthly Sales (Last 12 months)
        $monthly_sales = DB::table('sales')
            ->select(DB::raw('MONTH(created_at) as month'), DB::raw('SUM(total) as total'))
            ->where('created_at', '>=', Carbon::now()->subMonths(12))
            ->whereNull('deleted_at')
            ->groupBy('month')
            ->orderBy('month')
            ->get();

        // Recent Inventory Movements
        $recent_movements = InventoryMovement::with(['user', 'supplier', 'details'])
            ->orderByDesc('created_at')
            ->limit(5)
            ->get()->map(function($m) {
                // Calcular total valorado del movimiento
                $total_valorado = $m->details->sum(function($d) {
                    return $d->cantidad * $d->precioUnitario;
                });

                return [
                    'id' => $m->id,
                    'tipo' => $m->tipo,
                    'total' => round($total_valorado, 2),
                    'observacion' => $m->observacion ?: '---',
                    'created_at' => $m->created_at->format('Y-m-d H:i'),
                    'user_name' => $m->user ? $m->user->name : 'N/A',
                    'supplier_name' => $m->supplier ? $m->supplier->razonSocial : 'N/A'
                ];
            });

        // Low Stock Products
        $low_stock_products = Product::all()->filter(function($product) {
            return $product->stock_actual < 5;
        })->values()->take(5)->map(function($p) {
            return [
                'id' => $p->id,
                'title' => $p->title,
                'stock' => $p->stock_actual
            ];
        });

        return response()->json([
            'kpis' => [
                'total_sales' => round($total_sales, 2),
                'sales_count' => $sales_count,
                'total_clients' => $total_clients,
                'total_debt' => round($total_debt, 2),
                'inventory_entries' => $inventory_entries,
                'inventory_exits' => $inventory_exits,
            ],
            'top_products' => $top_products,
            'top_clients' => $top_clients,
            'payment_methods' => $payment_methods,
            'monthly_sales' => $monthly_sales,
            'recent_movements' => $recent_movements,
            'low_stock_products' => $low_stock_products
        ]);
    }

    public function notifications()
    {
        $recent_movements = InventoryMovement::with(['user', 'supplier'])
            ->orderByDesc('created_at')
            ->limit(5)
            ->get()->map(function($m) {
                return [
                    'id' => $m->id,
                    'tipo' => $m->tipo,
                    'observacion' => $m->observacion ?: 'Movimiento sin observaciones',
                    'created_at' => $m->created_at->diffForHumans(),
                    'user_name' => $m->user ? $m->user->name : 'Sistema'
                ];
            });

        return response()->json([
            'recent_movements' => $recent_movements
        ]);
    }
}
