<?php

namespace App\Services;

use App\Models\Wage;
use App\Models\User;
use App\Models\Appointment;
use Carbon\Carbon;

class WageService
{
    /**
     * Calculate wage for a therapist in a given period
     */
    public function calculateWage(int $therapistId, string $periodStart, string $periodEnd): array
    {
        $therapist = User::find($therapistId);
        
        $completedAppointments = Appointment::where('user_id', $therapistId)
            ->where('status', 'completed')
            ->whereBetween('appointment_date', [$periodStart, $periodEnd . ' 23:59:59'])
            ->get();

        $sessionsCount = $completedAppointments->count();
        $hoursWorked = $completedAppointments->sum('duration_minutes') / 60;

        $baseAmount = 0;
        
        if ($therapist->session_rate) {
            $baseAmount = $sessionsCount * $therapist->session_rate;
        } elseif ($therapist->hourly_rate) {
            $baseAmount = $hoursWorked * $therapist->hourly_rate;
        }

        return [
            'therapist_id' => $therapistId,
            'period_start' => $periodStart,
            'period_end' => $periodEnd,
            'sessions_count' => $sessionsCount,
            'hours_worked' => round($hoursWorked, 2),
            'base_amount' => round($baseAmount, 2),
            'bonus' => 0,
            'deductions' => 0,
            'total_amount' => round($baseAmount, 2),
        ];
    }

    /**
     * Create wage record
     */
    public function createWage(array $data, int $createdBy): Wage
    {
        $wage = Wage::create(array_merge($data, [
            'created_by' => $createdBy,
        ]));

        // Auto-create ledger entry
        $ledgerService = new LedgerService();
        $ledgerService->recordWage($wage);

        return $wage;
    }

    /**
     * Get therapist performance metrics
     */
    public function getPerformanceMetrics(int $therapistId, string $periodStart, string $periodEnd): array
    {
        $wage = $this->calculateWage($therapistId, $periodStart, $periodEnd);
        $therapist = User::find($therapistId);

        $targetSessions = $therapist->target_sessions_per_month ?? 0;
        $sessionsAchieved = $targetSessions > 0 ? ($wage['sessions_count'] / $targetSessions) * 100 : 0;

        return [
            'sessions_count' => $wage['sessions_count'],
            'hours_worked' => $wage['hours_worked'],
            'target_sessions' => $targetSessions,
            'sessions_achieved_percentage' => round($sessionsAchieved, 2),
            'base_amount' => $wage['base_amount'],
        ];
    }
}
