<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Services\ChartBasicServices;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Traits\GetCompanyInfo;

class ChartController extends Controller
{
    use GetCompanyInfo;

    protected $ChartBasicServices;

    public function __construct(ChartBasicServices $ChartBasicServices)
    {
        $this->ChartBasicServices = $ChartBasicServices;
    }

    public function getChartMemberschipsForMoutn(Request $request)
    {
        $companyId = $this->resolveCompanyId($request);
        $data = $this->ChartBasicServices->getChartMemberschipsForMoutn($companyId);
        return response()->json($data);
    }
    public function getTodayAttendanceRate(Request $request, $mesAnterior = null)
    {
        $companyId = $this->resolveCompanyId($request);
        $data = $this->ChartBasicServices->getTodayAttendanceRate($mesAnterior, $companyId);
        return response()->json($data);
    }
    public function getTopAttendees(Request $request, $mesAnterior = null)
    {
        $companyId = $this->resolveCompanyId($request);
        $data = $this->ChartBasicServices->getTopAttendees($mesAnterior, $companyId);
        return response()->json($data);
    }

    public function getDaysForMembership(Request $request)
    {
        $companyId = $this->resolveCompanyId($request);
        $startDate = $request->query('start_date');
        $endDate = $request->query('end_date');
        $data = $this->ChartBasicServices->getDaysForMembership($startDate, $endDate, $companyId);
        return response()->json($data);
    }

    private function resolveCompanyId(Request $request): int
    {
        $userId = (int) Auth::id();
        $companyInfo = $request->attributes->get('companyInfo') ?? $this->getCompanyInfo($userId);

        return (int) ($companyInfo?->id ?? 0);
    }
}
