<?php

namespace App\Models;

use CodeIgniter\Model;

class LateSlipLogModel extends Model
{
    protected $table = 'late_slip_logs';
    protected $primaryKey = 'id';
    protected $useTimestamps = false; // we control printed_at explicitly
    protected $returnType = 'array';
    protected $allowedFields = [
        'school_year',
        'semester',
        'student_name',
        'slip_date',
        'time_in',
        'grade',
        'reason',
        'admin_name',
        'printed_by',
        'printed_at',
    ];

    /**
     * Best-effort insert of a single late slip print log.
     * Swallows DB errors to avoid blocking printing.
     *
     * @param array $data expects keys: school_year, student_name, slip_date (Y-m-d), time_in (H:i:s), grade, reason, admin_name
     * @param int|null $printedBy user id of the admin performing the print
     * @return bool success (best-effort)
     */
    public function logSlip(array $data, ?int $printedBy): bool
    {
        $row = [
            'school_year'  => (string)($data['school_year'] ?? ''),
            'semester'     => (string)($data['semester']    ?? ''),
            'student_name' => (string)($data['student_name'] ?? ''),
            'slip_date'    => $data['slip_date'] ?? null,
            'time_in'      => $data['time_in'] ?? null,
            'grade'        => (string)($data['grade'] ?? ''),
            'reason'       => (string)($data['reason'] ?? ''),
            'admin_name'   => (string)($data['admin_name'] ?? ''),
            'printed_by'   => $printedBy,
            'printed_at'   => utc_now(),
        ];

        try {
            return (bool) $this->insert($row);
        } catch (\Throwable $e) {
            log_message('error', 'LateSlipLogModel::logSlip failed: ' . $e->getMessage());
            return false;
        }
    }
}
