<?php

namespace App\Models;

use CodeIgniter\Model;

class AdminLicenseCacheModel extends Model
{
    protected $table = 'admin_license_cache';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    protected $allowedFields = [
        'admin_id',
        'license_code',
        'license_data',
        'signature',
        'signed_at',
        'synced_at',
    ];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    public function getByAdminId(int $adminId): ?array
    {
        return $this->where('admin_id', $adminId)->first();
    }

    public function getByLicenseCode(string $licenseCode): ?array
    {
        return $this->where('license_code', $licenseCode)->first();
    }

    public function updateOrCreate(int $adminId, string $licenseCode, array $licenseData, string $signature, string $signedAt): bool
    {
        $existing = $this->getByAdminId($adminId);
        
        $data = [
            'admin_id' => $adminId,
            'license_code' => $licenseCode,
            'license_data' => json_encode($licenseData),
            'signature' => $signature,
            'signed_at' => $signedAt,
            'synced_at' => date('Y-m-d H:i:s'),
        ];

        if ($existing) {
            return $this->update($existing['id'], $data);
        }

        return $this->insert($data) !== false;
    }

    public function getLicenseData(int $adminId): ?array
    {
        $cache = $this->getByAdminId($adminId);
        
        if (!$cache) {
            return null;
        }

        return json_decode($cache['license_data'], true);
    }
}
