<?php

namespace App\Services;

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

class ProfileCompletionService
{
    public function requiredFieldsForUser(User $user): array
    {
        if ($user->role_key === 'student' && $user->school_id) {
            $settings = DB::table('school_settings')->where('school_id', $user->school_id)->first();

            if ($settings && $settings->required_student_fields) {
                $configured = json_decode($settings->required_student_fields, true);
                if (is_array($configured) && count($configured) > 0) {
                    return $configured;
                }
            }

            return ['mobile', 'father_mobile', 'mother_mobile'];
        }

        return match ($user->role_key) {
            'teacher' => ['mobile', 'national_code'],
            default => ['mobile', 'email'],
        };
    }

    public function complete(User $user, array $data): void
    {
        $user->fill([
            'mobile' => $data['mobile'] ?? $user->mobile,
            'national_code' => $data['national_code'] ?? $user->national_code,
            'must_complete_profile' => false,
            'must_change_password' => false,
            'profile_completed_at' => now(),
            'last_profile_update_at' => now(),
        ])->save();
    }
}
