<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;

class Election extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'starts_at',
        'ends_at',
        'candidate_upload_starts_at',
        'candidate_upload_ends_at',
        'voting_started_at',
        'is_active',
    ];

    protected $casts = [
        'starts_at' => 'datetime',
        'ends_at' => 'datetime',
        'candidate_upload_starts_at' => 'datetime',
        'candidate_upload_ends_at' => 'datetime',
        'voting_started_at' => 'datetime',
        'is_active' => 'boolean',
    ];

    public function candidates()
    {
        return $this->hasMany(Candidate::class);
    }

    public function ballots()
    {
        return $this->hasMany(Ballot::class);
    }

    public function receipts()
    {
        return $this->hasMany(VotingReceipt::class);
    }

    public function isOpen(): bool
    {
        $now = Carbon::now();

        return $this->is_active
            && $this->voting_started_at !== null
            && $now->between($this->voting_started_at, $this->ends_at);
    }

    public function canUploadCandidates(): bool
    {
        if (! $this->candidate_upload_starts_at || ! $this->candidate_upload_ends_at) {
            return false;
        }

        return Carbon::now()->between($this->candidate_upload_starts_at, $this->candidate_upload_ends_at);
    }
}
