<?php

namespace App\Modules\Attendance\Models;

use CodeIgniter\Model;

/**
 * Token QR untuk absen mapel: guru generate, siswa scan.
 */
class QrAttendanceTokenModel extends Model
{
    protected $table            = 'qr_attendance_tokens';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $allowedFields    = [
        'schedule_id',
        'token',
        'expires_at',
        'created_by_user_id',
    ];
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    /** Token valid (default) 15 menit */
    public const VALID_MINUTES = 15;

    /**
     * Generate token untuk schedule_id. Returns token string or null on failure.
     */
    public function generateForSchedule(int $scheduleId, ?int $createdByUserId = null): ?string
    {
        $token = bin2hex(random_bytes(16));
        $expires = date('Y-m-d H:i:s', strtotime('+' . self::VALID_MINUTES . ' minutes'));

        $id = $this->insert([
            'schedule_id'         => $scheduleId,
            'token'               => $token,
            'expires_at'          => $expires,
            'created_by_user_id'  => $createdByUserId,
        ]);

        return $id ? $token : null;
    }

    /**
     * Validate token: return row (schedule_id, expires_at) if valid and not expired; null otherwise.
     */
    public function validateToken(string $token): ?array
    {
        $row = $this->where('token', $token)->first();
        if (!$row || !is_array($row)) {
            return null;
        }
        $expiresAt = $row['expires_at'] ?? null;
        if (!$expiresAt || strtotime($expiresAt) < time()) {
            return null;
        }
        return [
            'schedule_id' => (int) $row['schedule_id'],
            'expires_at'  => $row['expires_at'],
        ];
    }
}
