<?php

namespace App\Models;

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

class Ad extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'advertiser_id',
        'position',
        'format',
        'content',
        'target',
        'target_data',
        'start_at',
        'end_at',
        'impressions_limit',
        'clicks_limit',
        'impressions_count',
        'clicks_count',
        'status',
    ];

    protected $casts = [
        'target_data' => 'array',
        'start_at' => 'datetime',
        'end_at' => 'datetime',
    ];

    public function advertiser()
    {
        return $this->belongsTo(User::class, 'advertiser_id');
    }

    public function isActive(): bool
    {
        if ($this->status !== 'active') {
            return false;
        }

        $now = now();
        if ($this->start_at && $now < $this->start_at) {
            return false;
        }
        if ($this->end_at && $now > $this->end_at) {
            return false;
        }
        if ($this->impressions_limit && $this->impressions_count >= $this->impressions_limit) {
            return false;
        }
        if ($this->clicks_limit && $this->clicks_count >= $this->clicks_limit) {
            return false;
        }

        return true;
    }
}

