<?php

namespace App\Models;

use CodeIgniter\Model;

class BadgePrintLogModel extends Model
{
    protected $table = 'badge_print_logs';
    protected $primaryKey = 'id';
    protected $useTimestamps = false;
    protected $returnType = 'array';
    protected $allowedFields = [
        'user_id',
        'printed_by',
        'school_year',
        'printed_at',
        'role',
        'class_section_name',
        'copies',
    ];

    /**
     * Insert a batch of print logs. Swallows errors if table is missing.
     *
     * @param int[]       $userIds
     * @param int|null    $printedBy
     * @param string|null $schoolYear
     * @param array       $roleMap        userId => role label
     * @param array       $classMap       userId => class name
     * @param int         $copies         copies per user (defaults to 1)
     * @return int rows inserted (best-effort)
     */
    public function logPrints(array $userIds, ?int $printedBy, ?string $schoolYear, array $roleMap = [], array $classMap = [], int $copies = 1): int
    {
        $now = utc_now();
        $rows = [];

        foreach ($userIds as $uid) {
            $uid = (int) $uid;
            if ($uid <= 0) continue;
            $rows[] = [
                'user_id'            => $uid,
                'printed_by'         => $printedBy,
                'school_year'        => $schoolYear,
                'printed_at'         => $now,
                'role'               => (string)($roleMap[$uid] ?? ''),
                'class_section_name' => (string)($classMap[$uid] ?? ''),
                'copies'             => max(1, (int)$copies),
            ];
        }

        if (empty($rows)) return 0;

        try {
            return $this->insertBatch($rows) ?? count($rows);
        } catch (\Throwable $e) {
            // If table does not exist or other DB error, avoid breaking PDF generation
            log_message('error', 'BadgePrintLogModel::logPrints failed: ' . $e->getMessage());
            return 0;
        }
    }

    /**
     * Return counts and last printed info for given user IDs.
     *
     * @param int[]       $userIds
     * @param string|null $schoolYear Optional filter by school year
     * @return array userId => [count, last_printed_at, last_printed_by]
     */
    public function getStatus(array $userIds, ?string $schoolYear = null): array
    {
        $userIds = array_values(array_unique(array_map('intval', array_filter($userIds))));
        if (empty($userIds)) return [];

        try {
            $builder = $this->db->table($this->table . ' l')
                ->select('l.user_id, COUNT(*) AS prints, MAX(l.printed_at) AS last_printed_at, MAX(l.printed_by) AS last_printed_by')
                ->whereIn('l.user_id', $userIds)
                ->groupBy('l.user_id');

            if (!empty($schoolYear)) {
                $builder->where('l.school_year', $schoolYear);
            }

            $rows = $builder->get()->getResultArray();
        } catch (\Throwable $e) {
            log_message('error', 'BadgePrintLogModel::getStatus failed: ' . $e->getMessage());
            return [];
        }

        $out = [];
        foreach ($rows as $r) {
            $out[(int)$r['user_id']] = [
                'count'            => (int)($r['prints'] ?? 0),
                'last_printed_at'  => (string)($r['last_printed_at'] ?? ''),
                'last_printed_by'  => isset($r['last_printed_by']) ? (int)$r['last_printed_by'] : null,
            ];
        }
        return $out;
    }
}

