<?php

namespace App\Http\Controllers\Api\Reports;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Expense;
use Carbon\Carbon;

class ExpenseReportController extends Controller
{
    public function expense_detail_report(Request $request){

        $endDate = $request->input('end_date') ?: Carbon::today()->format('Y-m-d');
        $startDate = $request->input('start_date') ?: Carbon::today()->startOfMonth()->format('Y-m-d') ;

        $expense=Expense::with('expense_head:id,expense_name','expense_account:id,account_name',
                'paid_through:id,account_name','customer:id,display_name,customer_pin','vendor:id,display_name',
                'expense_account:id,account_name')
            // ->where('organisation_id',$user['active_organisation'])
            ->where('rolledback',0)
            ->whereBetween('transaction_date',[$startDate,$endDate])
            ->get();

        $total_expense=Expense::where('rolledback',0)
                    ->whereBetween('transaction_date',[$startDate,$endDate])
                    ->sum('amount');

        $total_tax=Expense::where('rolledback',0)
                    ->whereBetween('transaction_date',[$startDate,$endDate])
                    ->sum('tax_amount');
                        
        $response=[
            'message'=>'Expense Report Fetched Successfully',
            'start_date'=>$startDate,
            'end_date'=>$endDate,
            'success'=>true,
            'total_expense'=>$total_expense,
            'expense'=>$expense,
            'total_tax'=>$total_tax
        ];

        return response()->json($response);
    }

    public function expense_summary_report(Request $request)
    {
        $endDate = $request->input('end_date') ?: Carbon::today()->format('Y-m-d');
        $startDate = $request->input('start_date') ?: Carbon::today()->startOfYear()->format('Y-m-d');

        // Fetch expenses grouped by expense head + month
        $expenses = Expense::selectRaw('
                acc_id,
                MONTH(transaction_date) as month,
                SUM(amount) as total
            ')
            ->where('rolledback', 0)
            ->whereBetween('transaction_date', [$startDate, $endDate])
            ->groupBy('acc_id', 'month')
            ->with('expense_account:id,account_name,account_code')
            ->get();

        // Reshape into pivot-style array
        $report = [];
        foreach ($expenses as $exp) {
            $head = $exp->expense_account->account_name ?? 'Not Defined';
            $head_code = $exp->expense_account->account_code ?? 'Not Defined';

            // Use account name as key
            if (!isset($report[$head])) {
                $report[$head] = [
                    'account_code' => $head_code,
                    'months' => array_fill(1, 12, 0), // Jan to Dec
                ];
            }

            // Assign monthly total
            $report[$head]['months'][$exp->month] = $exp->total;
        }

        // Build final response
        $final = [];
        foreach ($report as $head => $data) {
            $final[] = [
                'account_code' => $data['account_code'],
                'head_of_account' => $head,
                'months' => $data['months'],
                'total' => array_sum($data['months']),
            ];
        }

        return response()->json([
            'message' => 'Expense Summary Report Fetched Successfully',
            'success' => true,
            'start_date' => $startDate,
            'end_date' => $endDate,
            'data' => $final
        ]);
    }


}
