<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class SchoolIdService
{
    public function assignSchoolIdToUser(int $userId): ?string
    {
        $user = User::query()->find($userId);
        if (!$user) {
            return null;
        }

        $existing = (string) ($user->school_id ?? '');
        if ($existing !== '') {
            return $existing;
        }

        $schoolId = $this->generateUserSchoolId();
        $user->school_id = $schoolId;
        $user->save();

        return $schoolId;
    }

    public function generateStudentSchoolId(): string
    {
        $year = date('y');
        $maxId = 0;

        $row = DB::table('students')
            ->selectRaw('MAX(school_id) AS max_id')
            ->where('school_id', 'like', "STU{$year}%")
            ->first();

        if (!empty($row?->max_id)) {
            $numericPart = substr((string) $row->max_id, 5);
            $maxId = (int) $numericPart;
        }

        $nextId = str_pad($maxId + 1, 5, '0', STR_PAD_LEFT);

        return "STU{$year}{$nextId}";
    }

    public function generateUserSchoolId(): string
    {
        $year = date('y');
        $maxId = 0;

        $row = DB::table('users')
            ->selectRaw('MAX(school_id) AS max_id')
            ->where('school_id', 'not like', 'S%')
            ->where('school_id', 'like', "{$year}%")
            ->first();

        if (!empty($row?->max_id)) {
            $numericPart = substr((string) $row->max_id, 2);
            $maxId = max($maxId, (int) $numericPart);
        }

        $nextId = str_pad($maxId + 1, 5, '0', STR_PAD_LEFT);

        return "{$year}{$nextId}";
    }
}
