<?php

namespace App\Http\Controllers;

use App\Models\Supplier;
use App\Models\SaleItem;
use App\Models\CapitalInjection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class InvestorReportController extends Controller
{
    /**
     * Dashboard for the logged-in investor.
     */
    public function index()
    {
        $user = auth()->user();
        $this->authorize('viewReports', [Supplier::class]);
        $isAdmin = $user->hasRole('Admin');

        // Get suppliers linked to this user (or all if admin)
        $suppliersQuery = Supplier::with(['capitalInjections', 'products.saleItems', 'capitalSettlements']);
        
        if ($user->hasRole('Inversor')) {
            $suppliersQuery->where('user_id', $user->id);
        }

        $suppliers = $suppliersQuery->get();

        $reports = $suppliers->map(function ($supplier) {
            // 1. Total Injected (Principal)
            $totalInjected = $supplier->capitalInjections->sum('amount');

            // 2. Total Recovered (Reimbursement at Cost)
            $totalRecovered = 0;
            $totalProfit = 0;
            $totalRevenue = 0;

            foreach ($supplier->products as $product) {
                foreach ($product->saleItems as $item) {
                    $totalRecovered += ($item->quantity * $product->purchase_price);
                    $totalRevenue += ($item->quantity * $item->price);
                }
            }

            $totalProfit = $totalRevenue - $totalRecovered;
            
            // 3. Settlements Logic
            $totalSettledAndConfirmed = $supplier->capitalSettlements()
                ->where('status', 'confirmed')
                ->sum('amount');
            
            $pendingSettlements = $supplier->capitalSettlements()
                ->where('status', 'pending')
                ->get();

            // 4. Metrics
            $readyToPay = max(0, $totalRecovered - $totalSettledAndConfirmed);
            $pendingPrincipal = max(0, $totalInjected - $totalRecovered);

            // 5. Current Stock Value
            $stockValue = $supplier->products->sum(function($p) {
                return $p->stock * $p->purchase_price;
            });

            return [
                'supplier_id' => $supplier->id,
                'supplier_name' => $supplier->name,
                'investor_name' => $supplier->investor_name ?? $supplier->user->name ?? 'N/A',
                'total_injected' => $totalInjected,
                'total_recovered' => $totalRecovered,
                'total_paid' => $totalSettledAndConfirmed,
                'ready_to_pay' => $readyToPay,
                'pending_principal' => $pendingPrincipal,
                'total_profit' => $totalProfit,
                'stock_value' => $stockValue,
                'injections' => $supplier->capitalInjections()->latest('injection_date')->get(),
                'pending_settlements' => $pendingSettlements,
                'settlement_history' => $supplier->capitalSettlements()->where('status', 'confirmed')->latest('payment_date')->take(5)->get()
            ];
        });

        return view('investors.dashboard', compact('reports', 'isAdmin'));
    }

    /**
     * Store a new capital injection.
     */
    public function storeInjection(Request $request)
    {
        $request->validate([
            'supplier_id' => 'required|exists:suppliers,id',
            'amount' => 'required|numeric|min:0.01',
            'injection_date' => 'required|date',
            'notes' => 'nullable|string'
        ]);

        // Security check
        $supplier = Supplier::findOrFail($request->supplier_id);
        $this->authorize('viewReports', $supplier);

        CapitalInjection::create($request->all());

        return back()->with('success', 'Inyección de capital registrada correctamente.');
    }

    /**
     * Create a settlement (Admin only).
     */
    public function storeSettlement(Request $request)
    {
        $request->validate([
            'supplier_id' => 'required|exists:suppliers,id',
            'amount' => 'required|numeric|min:0.01',
            'payment_date' => 'required|date',
            'notes' => 'nullable|string'
        ]);

        $this->authorize('manageSettlements', Supplier::class);

        \App\Models\CapitalSettlement::create([
            'supplier_id' => $request->supplier_id,
            'amount' => $request->amount,
            'payment_date' => $request->payment_date,
            'notes' => $request->notes,
            'status' => 'pending'
        ]);

        return back()->with('success', 'Liquidación de pago registrada. El inversor debe confirmar la recepción.');
    }

    /**
     * Confirm a settlement (Investor only or Admin).
     */
    public function confirmSettlement(\App\Models\CapitalSettlement $settlement)
    {
        $user = auth()->user();

        // Security check: only the investor assigned to the supplier can confirm
        $this->authorize('confirmSettlement', [$settlement]);

        $settlement->update([
            'status' => 'confirmed',
            'confirmed_at' => now()
        ]);

        return back()->with('success', 'Has confirmado la recepción del pago de S/ ' . number_format($settlement->amount, 2));
    }
}
