<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;

class LateSlipLog extends BaseModel
{
    protected $table = 'late_slip_logs';

    // CI: useTimestamps = false (printed_at is controlled explicitly)
    public $timestamps = false;

    protected $fillable = [
        'school_year',
        'semester',
        'student_name',
        'slip_date',
        'time_in',
        'grade',
        'reason',
        'admin_name',
        'printed_by',
        'printed_at',
    ];

    protected $casts = [
        'printed_by' => 'integer',
        'slip_date'  => 'date',     // slip_date is Y-m-d
        'printed_at' => 'datetime',
        // time_in is often stored as TIME or string; keep as string unless you store as DATETIME
        'time_in'    => 'string',
    ];

    /**
     * Best-effort insert of a single late slip print log.
     * Swallows DB errors to avoid blocking printing.
     */
    public static 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,   // Y-m-d
            'time_in'      => $data['time_in'] ?? null,     // H:i:s
            'grade'        => (string)($data['grade'] ?? ''),
            'reason'       => (string)($data['reason'] ?? ''),
            'admin_name'   => (string)($data['admin_name'] ?? ''),
            'printed_by'   => $printedBy,
            'printed_at'   => now(), // use UTC if your app timezone is UTC
        ];

        try {
            // create() returns model; treat as success if created
            $created = static::query()->create($row);
            return !empty($created->id);
        } catch (QueryException $e) {
            Log::error('LateSlipLog::logSlip failed: ' . $e->getMessage());
            return false;
        } catch (\Throwable $e) {
            Log::error('LateSlipLog::logSlip failed: ' . $e->getMessage());
            return false;
        }
    }

    /* Optional relationship */
    public function printer()
    {
        return $this->belongsTo(User::class, 'printed_by');
    }
}