<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\TreasuryEntry;
use App\Models\TreasuryExit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TreasuryDashboard extends Controller
{
    public function index(Request $request) {
        $this->authorize('view dashboard');

        $year = $request->input('year', date('Y')); // Default to current year if not provided

        // Get total entries and exits for the year
        $totalEntries = TreasuryEntry::where("is_valid", true)->whereYear('date', $year)->sum('amount');
        $totalExits = TreasuryExit::where("is_valid", true)->whereYear('date', $year)->sum('amount');
        $totalGap = $totalEntries - $totalExits;

        // Get cumulative solde de départ from the start (all previous years' entries and exits)
        $startingBalance = TreasuryEntry::where("is_valid", true)->whereYear('date', '<', $year)->sum('amount') - TreasuryExit::where("is_valid", true)->whereYear('date', '<', $year)->sum('amount');

        // Get category-wise data for pie charts (entries and exits grouped by category)
        $categoryEntries = TreasuryEntry::select(DB::raw('category_id, SUM(amount) as total_amount'))
            ->where('is_valid', true)
            ->whereYear('date', $year)
            ->groupBy('category_id')
            ->with('category:id,title')
            ->get()
            ->map(function ($item) {
                return [
                    'category' => $item->category->title,
                    'total_amount' => $item->total_amount
                ];
            });

        $categoryExits = TreasuryExit::select(DB::raw('category_id, SUM(amount) as total_amount'))
            ->where('is_valid', true)
            ->whereYear('date', $year)
            ->groupBy('category_id')
            ->with('category:id,title')
            ->get()
            ->map(function ($item) {
                return [
                    'category' => $item->category->title,
                    'total_amount' => $item->total_amount
                ];
            });

        // Get monthly data for bar chart
        $monthlyData = [];
        foreach (range(1, 12) as $month) {
            $monthlyEntries = TreasuryEntry::where("is_valid", true)->whereYear('date', $year)->whereMonth('date', $month)->sum('amount');
            $monthlyExits = TreasuryExit::where("is_valid", true)->whereYear('date', $year)->whereMonth('date', $month)->sum('amount');
            $monthlyGap = $monthlyEntries - $monthlyExits;

            $monthlyData[] = [
                'month' => $month,
                'entries' => $monthlyEntries,
                'exits' => $monthlyExits,
                'gap' => $monthlyGap
            ];
        }

        $yearsEntries = TreasuryEntry::selectRaw('YEAR(date) as year')
                            ->distinct();
        $yearsExits = TreasuryExit::selectRaw('YEAR(date) as year')
                            ->distinct();

        $years = $yearsEntries->union($yearsExits)
            ->orderBy('year', 'asc')
            ->get();

        $currentYear = date('Y');

        return  response()->json([
            'years' => count($years) <= 0 ? [$currentYear] : $years,
            'total_entries' => $totalEntries,
            'total_exits' => $totalExits,
            'total_gap' => $totalGap,
            'startingBalance' => $startingBalance,
            'monthly_data' => $monthlyData,
            'category_entries' => $categoryEntries,
            'category_exits' => $categoryExits
        ]);
    }
}
