<?php

namespace App\Models;

use CodeIgniter\Model;

class LicenseKeyModel extends Model
{
    protected $table = 'license_keys';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'license_code', 'organization_name', 'contact_email', 'contact_phone',
        'status', 'max_seats', 'used_seats', 'valid_from', 'valid_until', 
        'notes', 'enable_login_screen', 'enable_camera_detection', 
        'enable_person_detection', 'lms_probe_origin', 'screenshot_needed',
        'sap_web_url', 'created_by', 'created_at', 'updated_at'
    ];
    protected $useTimestamps = false;

    public function generateUniqueCode()
    {
        do {
            $code = strtoupper(bin2hex(random_bytes(8)));
        } while ($this->where('license_code', $code)->first());
        
        return $code;
    }

    public function isValidLicense($code, $macId = null)
    {
        $license = $this->where('license_code', $code)->first();
        if (!$license) return false;
        
        if ($license['status'] !== 'active') return false;
        
        $today = date('Y-m-d');
        if ($license['valid_from'] && $today < $license['valid_from']) return false;
        if ($license['valid_until'] && $today > $license['valid_until']) return false;
        
        if ($license['max_seats'] != -1 && $license['used_seats'] >= $license['max_seats']) {
            if ($macId) {
                $db = \Config\Database::connect();
                $existing = $db->table('system_usage')
                    ->where('license_id', $license['id'])
                    ->where('mac_id', $macId)
                    ->get()
                    ->getRowArray();
                if (!$existing) {
                    return false;
                }
            } else {
                return false;
            }
        }
        
        return $license;
    }

    public function getSystemUsage($licenseId)
    {
        $db = \Config\Database::connect();
        return $db->table('system_usage')
            ->where('license_id', $licenseId)
            ->orderBy('created_at', 'DESC')
            ->get()
            ->getResultArray();
    }
}
