<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Riwayat IP per klik — anti-click-fraud (RPD §15.1, BR-08).
 *
 * @property int $id
 * @property string $ip
 * @property int $ad_id
 * @property string|null $browser
 * @property string $tanggal
 *
 * @method static Builder|self alreadyClicked(int $adId, string $ip, string $tanggal)
 */
class IpHistory extends Model
{
    protected $fillable = ['ip', 'ad_id', 'browser', 'tanggal'];

    protected function casts(): array
    {
        return [
            'tanggal' => 'date',
        ];
    }

    public function ad(): BelongsTo
    {
        return $this->belongsTo(Ad::class);
    }

    /**
     * Scope: cek apakah IP sudah pernah klik iklan ini pada tanggal tertentu (BR-08).
     */
    public function scopeAlreadyClicked(Builder $query, int $adId, string $ip, string $tanggal): Builder
    {
        return $query
            ->where('ad_id', $adId)
            ->where('ip', $ip)
            ->whereDate('tanggal', $tanggal);
    }
}
