<?php

namespace App\Services\Roles;

use App\Models\Staff;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class RoleStaffService
{
    public function syncStaffRecord(User $user, array $newRoleNames): void
    {
        $excludedRoles = ['parent', 'student', 'guest'];
        $loweredNewRoles = array_map('strtolower', $newRoleNames);

        $existingStaff = Staff::query()->where('user_id', $user->id)->first();
        $existingRoles = [];
        if ($existingStaff && !empty($existingStaff->role_name)) {
            $existingRoles = array_map('strtolower', array_map('trim', explode(',', $existingStaff->role_name)));
        }

        $allRoles = array_unique(array_merge($existingRoles, $loweredNewRoles));
        $staffRoles = array_filter($newRoleNames, fn ($role) => !in_array(strtolower($role), $excludedRoles, true));
        $activeRole = !empty($staffRoles) ? $staffRoles[0] : 'inactive';

        $email = $this->generateUniqueStaffEmail($user->firstname ?? '', $user->lastname ?? '', (int) $user->id);

        $payload = [
            'user_id' => (int) $user->id,
            'firstname' => $user->firstname ?? '',
            'lastname' => $user->lastname ?? '',
            'email' => $email,
            'phone' => $user->cellphone ?? '',
            'role_name' => implode(', ', $allRoles),
            'active_role' => $activeRole,
            'school_year' => $user->school_year ?? '',
        ];

        $saved = Staff::upsertStaff($payload);
        if (!$saved) {
            Log::warning('Failed to upsert staff record.', ['user_id' => $user->id]);
        }
    }

    private function generateUniqueStaffEmail(string $firstname, string $lastname, int $userId): string
    {
        $domain = '@alrahmaisgl.org';

        $firstname = strtolower(preg_replace('/[^a-z]/i', '', $firstname));
        $lastname = strtolower(preg_replace('/[^a-z]/i', '', $lastname));

        $min = 1;
        $max = max(1, strlen($firstname));
        $base = '';
        $email = '';

        for ($i = $min; $i <= $max; $i++) {
            $base = substr($firstname, 0, $i) . $lastname;
            $email = $base . $domain;

            $exists = Staff::query()
                ->where('email', $email)
                ->where('user_id', '!=', $userId)
                ->exists();
            if (!$exists) {
                return $email;
            }
        }

        return $base . $userId . $domain;
    }
}
