<?php

namespace App\Models;

use CodeIgniter\Model;

/**
 * QRCodeModel — manages qr_codes table.
 */
class QRCodeModel extends Model
{
    protected $table       = 'qr_codes';
    protected $primaryKey  = 'id';
    protected $useTimestamps = true;
    protected $createdField  = 'generated_at';
    protected $updatedField  = 'updated_at';
    protected $returnType  = 'array';

    protected $allowedFields = [
        'profile_id', 'file_path', 'qr_url',
        'has_logo', 'logo_path', 'foreground', 'background',
    ];

    /**
     * Get QR record by profile ID.
     */
    public function getByProfile(int $profileId): ?array
    {
        return $this->where('profile_id', $profileId)->first();
    }

    /**
     * Upsert — insert or update QR record for a profile.
     */
    public function upsert(int $profileId, array $data): bool
    {
        $existing = $this->getByProfile($profileId);
        $data['profile_id'] = $profileId;

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

        return (bool) $this->insert($data);
    }

    /**
     * Total QR codes generated.
     */
    public function getTotalCount(): int
    {
        return $this->countAll();
    }

    /**
     * QR codes list with profile info.
     */
    public function getListWithProfiles(): array
    {
        return $this->select('qr_codes.*, profiles.name AS profile_name, profiles.slug')
                    ->join('profiles', 'profiles.id = qr_codes.profile_id')
                    ->orderBy('qr_codes.generated_at', 'DESC')
                    ->findAll();
    }
}
