<?php

namespace App\Http\Controllers\Admin;

use App\Constants\Status;
use App\Http\Controllers\Controller;
use App\Models\Contribution;
use App\Models\Investment;
use Carbon\Carbon;
use Illuminate\Http\Request;

class InvestReportController extends Controller {
    public function dashboard() {
        $pageTitle                                = 'Investment Report';
        $contributions                            = Contribution::paid()->get();
        $investments['total_investment_count']    = Investment::count();
        $investments['total_close_requests']      = Investment::active()->where('close_request', Status::YES)->count();
        $investments['total_contribution_amount'] = $contributions->sum(function ($contribution) {
            return $contribution->amount + $contribution->penalty_amount;
        });
        $investments['completed_investment'] = Investment::completed()->count();
        return view('admin.investment.report', compact('pageTitle', 'investments'));
    }

    public function investmentReport(Request $request) {
        $diffInDays = Carbon::parse($request->start_date)->diffInDays(Carbon::parse($request->end_date));

        $groupBy = $diffInDays > 30 ? 'months' : 'days';
        $format  = $diffInDays > 30 ? '%M-%Y' : '%d-%M-%Y';

        if ($groupBy == 'days') {
            $dates = $this->getAllDates($request->start_date, $request->end_date);
        } else {
            $dates = $this->getAllMonths($request->start_date, $request->end_date);
        }

        $investments = Investment::whereDate('start_date', '>=', $request->start_date)
            ->whereDate('start_date', '<=', $request->end_date)
            ->selectRaw('COUNT(id) AS quantity')
            ->selectRaw("DATE_FORMAT(start_date, '{$format}') as created_on")
            ->groupBy('created_on')
            ->get();

        $data = [];

        foreach ($dates as $date) {
            $data[] = [
                'created_on' => $date,
                'investment' => $investments->where('created_on', $date)->first()?->quantity ?? 0,
            ];
        }

        $data = collect($data);

        $report['created_on'] = $data->pluck('created_on');
        $report['data']       = [
            [
                'name' => 'Investments',
                'data' => $data->pluck('investment'),
            ],
        ];

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

    public function contributionChart(Request $request) {
        $startDate = Carbon::parse($request->start_date)->startOfDay();
        $endDate   = Carbon::parse($request->end_date)->endOfDay();

        $contributions = Contribution::paid()
            ->whereBetween('contributed_date', [$startDate, $endDate])
            ->selectRaw('DATE(contributed_date) as date, SUM(amount) + SUM(penalty_amount) as total_amount')
            ->groupBy('date')
            ->orderBy('date', 'asc')
            ->get();

        return response()->json([
            'data'       => [
                [
                    'name' => 'Contribution Amount',
                    'data' => $contributions->pluck('total_amount')->toArray(),
                ],
            ],
            'created_on' => $contributions->pluck('date')->toArray(),
        ]);
    }

    private function getAllDates($startDate, $endDate) {
        $dates       = [];
        $currentDate = new \DateTime($startDate);
        $endDate     = new \DateTime($endDate);

        while ($currentDate <= $endDate) {
            $dates[] = $currentDate->format('d-F-Y');
            $currentDate->modify('+1 day');
        }

        return $dates;
    }

    private function getAllMonths($startDate, $endDate) {
        if ($endDate > now()) {
            $endDate = now()->format('Y-m-d');
        }

        $startDate = new \DateTime($startDate);
        $endDate   = new \DateTime($endDate);

        $months = [];

        while ($startDate <= $endDate) {
            $months[] = $startDate->format('F-Y');
            $startDate->modify('+1 month');
        }

        return $months;
    }
}
