<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class UserActionCount extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'action_type',
        'daily_count',
        'monthly_count',
        'count_date'
    ];

    protected $casts = [
        'count_date' => 'date',
    ];

    /**
     * Get the user that owns the action count.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Check if user has reached daily limit for an action.
     *
     * @param int $userId
     * @param string $actionType
     * @param int $limit
     * @return bool
     */
    public static function hasReachedDailyLimit($userId, $actionType, $limit)
    {
        if ($limit === 0) {
            return false; // 0 means unlimited
        }

        $today = now()->toDateString();
        
        $count = self::where('user_id', $userId)
            ->where('action_type', $actionType)
            ->where('count_date', $today)
            ->first();

        return $count && $count->daily_count >= $limit;
    }

    /**
     * Check if user has reached monthly limit for an action.
     *
     * @param int $userId
     * @param string $actionType
     * @param int $limit
     * @return bool
     */
    public static function hasReachedMonthlyLimit($userId, $actionType, $limit)
    {
        if ($limit === 0) {
            return false; // 0 means unlimited
        }

        $currentMonth = now()->startOfMonth()->toDateString();
        $endOfMonth = now()->endOfMonth()->toDateString();
        
        $totalCount = self::where('user_id', $userId)
            ->where('action_type', $actionType)
            ->whereBetween('count_date', [$currentMonth, $endOfMonth])
            ->sum('daily_count');

        return $totalCount >= $limit;
    }

    /**
     * Increment the action count for a user.
     *
     * @param int $userId
     * @param string $actionType
     * @return UserActionCount
     */
    public static function incrementCount($userId, $actionType)
    {
        $today = now()->toDateString();
        
        $actionCount = self::firstOrNew([
            'user_id' => $userId,
            'action_type' => $actionType,
            'count_date' => $today,
        ]);

        if (!$actionCount->exists) {
            $actionCount->daily_count = 0;
            $actionCount->monthly_count = 0;
        }

        $actionCount->daily_count += 1;
        $actionCount->monthly_count += 1;
        $actionCount->save();

        return $actionCount;
    }
} 