<?php

namespace App\Auth;

use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class MD5EloquentUserProvider extends EloquentUserProvider
{
    /**
     * Retrieve a user by the given credentials.
     */
    public function retrieveByCredentials(array $credentials): ?Authenticatable
    {
        if (empty($credentials) ||
           (count($credentials) === 1 &&
            array_key_exists('password', $credentials))) {
            return null;
        }

        // Build the query
        $query = $this->newModelQuery();

        foreach ($credentials as $key => $value) {
            if ($key !== 'password') {
                // Use StrUserID for username field
                if ($key === 'username') {
                    $query->where('StrUserID', $value);
                } else {
                    $query->where($key, $value);
                }
            }
        }

        return $query->first();
    }

    /**
     * Validate a user against the given credentials.
     */
    public function validateCredentials(Authenticatable $user, array $credentials): bool
    {
        $plain = $credentials['password'];
        $hashed = md5($plain);
        $stored = $user->getAuthPassword();

        // Log للتحقق
        Log::info('MD5 Auth Validation', [
            'user_id' => $user->getAuthIdentifier(),
            'username' => $user->StrUserID ?? 'N/A',
            'plain' => $plain,
            'hashed' => $hashed,
            'stored' => $stored,
            'match' => ($hashed === $stored)
        ]);

        return $hashed === $stored;
    }

    /**
     * Rehash the user's password if required and supported.
     */
    public function rehashPasswordIfRequired(Authenticatable $user, array $credentials, bool $force = false): void
    {
        // MD5 doesn't need rehashing
    }
}
