<?php

namespace App\Services\Reports;

class SlipPrinterFormatterService
{
    public function toDbDate(?string $value): ?string
    {
        $value = trim((string) $value);
        if ($value === '') {
            return null;
        }
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
            return $value;
        }
        if (preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/', $value)) {
            $dt = \DateTime::createFromFormat('!m/d/Y', $value);
            return $dt ? $dt->format('Y-m-d') : null;
        }
        if (preg_match('/^\d{1,2}-\d{1,2}-\d{4}$/', $value)) {
            $dt = \DateTime::createFromFormat('!m-d-Y', $value);
            return $dt ? $dt->format('Y-m-d') : null;
        }
        $ts = strtotime($value);
        return $ts ? date('Y-m-d', $ts) : null;
    }

    public function toDbTime(?string $value): ?string
    {
        $value = trim((string) $value);
        if ($value === '') {
            return null;
        }
        $ts = strtotime($value);
        return $ts ? date('H:i:s', $ts) : null;
    }

    public function formatDisplayDate(?string $value): string
    {
        $value = trim((string) $value);
        if ($value === '' || $value === '0000-00-00') {
            return '';
        }
        $ts = strtotime($value);
        return $ts ? date('m/d/Y', $ts) : '';
    }

    public function formatDisplayTime(?string $value): string
    {
        $value = trim((string) $value);
        if ($value === '') {
            return '';
        }
        $ts = strtotime($value);
        if ($ts === false) {
            $ts = strtotime('today ' . $value);
        }
        return $ts ? date('h:i A', $ts) : '';
    }

    public function fitLine(string $line, int $width): string
    {
        $line = (string) $line;
        if (strlen($line) > $width) {
            return substr($line, 0, $width);
        }
        return $line . str_repeat(' ', $width - strlen($line));
    }

    public function buildSlipLines(array $data, int $width): array
    {
        $lines = [];
        $lines[] = $this->fitLine('Student Name: ' . (string) ($data['student_name'] ?? ''), $width);
        $lines[] = $this->fitLine('Date: ' . (string) ($data['date'] ?? '') . '  Time In: ' . (string) ($data['time_in'] ?? ''), $width);
        $lines[] = $this->fitLine('Grade: ' . (string) ($data['grade'] ?? ''), $width);
        $lines[] = $this->fitLine('Reason: ' . (string) ($data['reason'] ?? ''), $width);
        $lines[] = $this->fitLine('Admin: ' . (string) ($data['admin_name'] ?? ''), $width);
        return $lines;
    }
}
