<?php

namespace App\Modules\Gamification;

use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\ValidationModel;
use App\Models\User;
use App\Modules\Bookings\Task;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PointsTransaction extends ValidationModel
{
    use SoftDeletes;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'points_transactions';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['identifier', 'user_id', 'action', 'amount', 'task_id', 'description', 'created_by'];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [
        'identifier' => ['required'],
        'user_id'    => ['required'],
    ];

    /**
     * Defines a relationship that links to the user.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Defines a relationship that links to the task.
     */
    public function task(): BelongsTo
    {
        return $this->belongsTo(Task::class, 'task_id');
    }

    /**
     * Define a custom range selection based on the created_at column.
     */
    public function scopeCreatedRange($query, ?string $start_date = null, ?string $end_date = null)
    {
        if ($start_date && $end_date) {
            $start_date = is_numeric($start_date) ? 
                now()->setTimestamp($start_date) : 
                now()->parse($start_date);
            $end_date = is_numeric($end_date) ? 
                now()->setTimestamp($end_date) : 
                now()->parse($end_date);

            return $query->whereBetween('created_at', [$start_date, $end_date]);
        }

        return $query->whereBetween('created_at', [
            now()->startOfMonth(),
            now()->endOfMonth()
        ]);
    }
}
