<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class License extends Model
{
    protected $table = 'licenses';
    protected $fillable = [
        'license_key', 'buyer_name', 'buyer_email', 'domain',
        'is_active', 'is_banned', 'ban_reason', 'activated_at',
        'expires_at', 'downloads_count', 'last_download_at',
        'last_check_ip', 'notes', 'type'
    ];

    public static function generateKey()
    {
        do {
            $key = strtoupper(
                Str::random(4) . '-' .
                Str::random(4) . '-' .
                Str::random(4) . '-' .
                Str::random(4)
            );
        } while (self::where('license_key', $key)->exists());

        return $key;
    }

    public function isValid()
    {
        if (!$this->is_active || $this->is_banned) return false;
        if ($this->expires_at && $this->expires_at < now()) return false;
        return true;
    }

    public function logs()
    {
        return DB::table('license_logs')
            ->where('license_id', $this->id)
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public static function log($licenseId, $action, $details = '', $ip = null, $domain = null)
    {
        DB::table('license_logs')->insert([
            'license_id' => $licenseId,
            'action' => $action,
            'ip_address' => $ip ?: request()->ip(),
            'domain' => $domain,
            'details' => $details,
            'created_at' => now(),
        ]);
    }
}
