<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Log;

class Participant extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
        'user_id',
        'giving_id',
        'prompt',
        'submission_url',
        'token',
    ];

    public static function findByToken(string $token): ?self
    {
        return self::where('token', $token)->first();
    }

    public function getUserData(): ?array
    {

        if (!$this->token) return null;

        $url = "https://sketchersunited.org/users/{$this->user_id}";

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($response !== false && $httpCode === 200) {

            return json_decode($response, true);
        }
        Log::info($this->user_id);
        return null;
    }

    public static function withoutReceivers()
    {
        return self::whereNotNull('giving_id')
            ->whereDoesntHave('receiver');
    }

    public function receiver(): BelongsTo
    {
        return $this->belongsTo(Participant::class, 'giving_id');
    }

    public function giver(): HasOne
    {
        return $this->hasOne(Participant::class, 'giving_id', 'id');
    }

    public function hasReceiver(): bool
    {
        return !is_null($this->giving_id); // The simplest and most direct check for an outgoing link
    }

    public function hasGiver(): bool
    {
       return $this->hasOne(Participant::class, 'giving_id', 'id')
            ->exists();
    }

    protected function isUnmatched(): Attribute
    {
        return Attribute::make(
            get: fn () => !$this->hasReceiver() && !$this->hasGiver(),
        );
    }

    protected function isDesperate(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->hasReceiver() xor $this->hasGiver(),
        );
    }

    public function withdraw(): bool
    {
        if (!$this->id) {
            return false;
        }

        $giver = Participant::where('giving_id', $this->id)->first();
        if ($giver) {
            $giver->giving_id = null;
            $giver->save();
        }

        $userB_id = $this->giving_id;
        if ($userB_id) {
            $this->giving_id = null;
        }

        $this->delete();

        return true;
    }
}
