<?php

namespace App\Services;

use App\Models\UserModel;
use CodeIgniter\Database\BaseConnection;

class SchoolIdService
{
    protected $db;
    protected $userModel;

    public function __construct()
    {
        $this->db = \Config\Database::connect();
        $this->userModel = new UserModel();
    }

    public function assignSchoolIdToUser($userId)
    {
        $user = $this->userModel->find($userId);
        if (!$user || $user['school_id']) {
            return $user['school_id'] ?? null;
        }

        $schoolId = $this->generateUserSchoolId();

        $this->userModel->update($userId, ['school_id' => $schoolId]);

        return $schoolId;
    }

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

    // Match the real prefix: STU + year
    $studentMax = $this->db->table('students')
        ->select('MAX(school_id) AS max_id')
        ->like('school_id', "STU{$year}", 'after')
        ->get()
        ->getRowArray();

    if (!empty($studentMax['max_id'])) {
        // Skip "STUyy" (5 chars)
        $numericPart = substr($studentMax['max_id'], 5);
        $maxId = (int) $numericPart;
    }

    $nextId = str_pad($maxId + 1, 5, '0', STR_PAD_LEFT);
    return "STU{$year}{$nextId}";
}


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

        // Get maximum user ID for current year
        $userMax = $this->db->table('users')->select('MAX(school_id) AS max_id')
            ->notLike('school_id', 'S%') // Exclude student IDs
            ->like('school_id', $year, 'after')->get()->getRowArray();

        if (!empty($userMax['max_id'])) {
            $numericPart = substr($userMax['max_id'], 2); // Skip 2-digit year
            $maxId = max($maxId, (int)$numericPart);
        }

        $nextId = str_pad($maxId + 1, 5, '0', STR_PAD_LEFT);
        return "{$year}{$nextId}";
    }
}
