<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\MonthlyCompanyFinancial;
use App\Models\CompanyFinancialLog;
use Illuminate\Http\Request;
use Carbon\Carbon;

class MonthlyFinancialController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $company = Company::find($user->company_id);
        if (!$company) return response()->json(['message' => 'No company found'], 403);

        $months = [];
        for ($i = 5; $i >= 0; $i--) {
            $month = Carbon::now()->subMonths($i);
            $ym = $month->format('Y-m');
            $mfin = MonthlyCompanyFinancial::recalculateMonth($company->id, $ym);
            $months[] = [
                'year_month' => $ym,
                'month_name' => $month->format('F Y'),
                'revenue' => (float) $mfin->revenue,
                'expenses' => (float) $mfin->expenses,
                'net_profit' => (float) $mfin->net_profit,
            ];
        }
        return response()->json(['company_id' => $company->id, 'months' => $months]);
    }

    public function recalculate(Request $request)
    {
        $user = $request->user();
        $company = Company::find($user->company_id);
        if (!$company) return response()->json(['message' => 'No company found'], 403);

        $validated = $request->validate([
            'year_month' => 'required|string|regex:/^\d{4}-\d{2}$/',
        ]);

        $ym = $validated['year_month'];
        $mfin = MonthlyCompanyFinancial::recalculateMonth($company->id, $ym);

        return response()->json([
            'message' => 'Recalculated from invoices and expenses',
            'month' => [
                'year_month' => $ym,
                'revenue' => (float) $mfin->revenue,
                'expenses' => (float) $mfin->expenses,
                'net_profit' => (float) $mfin->net_profit,
            ]
        ]);
    }
}
