<?php

namespace App\Http\Controllers\v1\Tenancy\Loyalty;

use App\Http\Controllers\Controller;
use App\Models\Tenancy\Loyalty;
use App\Models\Tenancy\VisitPayment;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;

class GetLoyaltyProgress extends Controller
{
    public function __invoke(): Response
    {
        $loyaltyData = Loyalty::status()
            ->active()
            ->get()
            ->sortBy(function ($order) {
                return array_search($order['name'], Loyalty::STATUS_LOYALTIES);
            })->values()->all();
        $data = [
            'total_paid' => 0,
            'total_visits' => 0,
        ];
        if ($user = Auth::guard('sanctum')->user()) {
            if ($loyaltyData[0]->amount_to_activate) {
                $visitHistoryIds = $user->visitHistories()
                    ->where('date', '>', $loyaltyData[0]->date_start)
                    ->pluck('visit_id')
                    ->toArray();
                $visitIds = $user->visits()
                    ->where('date', '>', $loyaltyData[0]->date_start)
                    ->where('visits.status', '<>', 'default')
                    ->pluck('visits.id')
                    ->toArray();

                $allVisitIds = array_merge($visitHistoryIds, $visitIds);

                $visitHistoryPayments = VisitPayment::whereIn('visit_id', $allVisitIds)->sum('paid');
                $data['total_paid'] += $visitHistoryPayments;
            } else {
                $data['total_visits'] = $user->visitHistories()
                    ->where('date', '>', $loyaltyData[0]->date_start)
                    ->count('visits_history.id');
            }
        }

        return $this->ok([
            'statuses' => $loyaltyData,
            'totals' => $data,
        ]);
    }
}
