<?php

namespace App\Rules;

use App\Services\ThirdPartyApiServices\Amplivo\SponsorService;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\Request;

class CheckSponsor implements Rule
{
    protected $message;
    protected $sponsor;
    protected $request;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->sponsor = new SponsorService();
        $this->request = new Request();
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if ($attribute === 'introduced_by') {
            if (isset($value) && !empty($value)) {
                $isValidUsername = $this->sponsor->isValidUsername($value);
                if ($isValidUsername === "Not found") {
                    return $this->fail('This sponsor is not valid.');
                } /*elseif ($isValidUsername['Status'] === 'abandoned') {
                    return $this->fail('This sponsor is not valid.');
                }*/
            }
        }

        return true;
    }

    /**
     * @param $message
     * @return false
     */
    protected function fail($message)
    {
        $this->message = $message;
        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}
