<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;

class PollResource extends JsonResource
{
    public function toArray($request)
    {
        // Ensure options are loaded if not already loaded
        if (!$this->relationLoaded('options')) {
            $this->load('options');
        }

        $totalVotes = \Illuminate\Support\Facades\DB::table('poll_votes')
            ->where('poll_id', $this->id)
            ->count();

        $myOptionId = null;
        if (\Illuminate\Support\Facades\Auth::check()) {
            $myOptionId = \Illuminate\Support\Facades\DB::table('poll_votes')
                ->where('poll_id', $this->id)
                ->where('user_id', \Illuminate\Support\Facades\Auth::id())
                ->value('option_id');
        }

        return [
            'id' => $this->id,
            'title' => $this->title,
            'status' => $this->is_active ? 'active' : 'closed',
            'total_votes' => $totalVotes,
            'options' => $this->options->map(function ($option) use ($totalVotes) {
                $votes = \Illuminate\Support\Facades\DB::table('poll_votes')->where('option_id', $option->id)->count();
                $percentage = $totalVotes > 0 ? round(($votes / $totalVotes) * 100) : 0;
                return [
                    'id' => $option->id,
                    'text' => $option->option_text,
                    'votes' => $votes,
                    'percentage' => $percentage,
                ];
            }),
            'created_at' => $this->created_at->diffForHumans(),
            'voted' => $this->when(
                Auth::check(), 
                fn() => $this->votes()->where('user_id', Auth::id())->exists()
            ),
            'my_option_id' => $this->when(Auth::check(), fn() => $myOptionId)
        ];
    }
}