<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Poll;
use Illuminate\Http\Request;

class PollController extends Controller
{
    public function index()
    {
        $polls = Poll::with('user')->orderBy('created_at', 'desc')->paginate(20);
        return view('admin.polls.index', compact('polls'));
    }

    public function create()
    {
        return view('admin.polls.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'options' => 'required|array|min:2',
            'options.*.text' => 'required|string',
            'description' => 'nullable|string',
            'ends_at' => 'nullable|date',
            'status' => 'required|in:draft,active,finished',
        ]);

        $poll = new Poll();
        $poll->user_id = auth()->id();
        $poll->title = $validated['title'];
        $poll->options = $validated['options'];
        $poll->description = $validated['description'] ?? null;
        $poll->ends_at = $validated['ends_at'] ?? null;
        $poll->status = $validated['status'];

        if ($request->hasFile('image')) {
            $poll->image = $request->file('image')->store('polls', 'public');
        }

        if ($request->status === 'active') {
            $poll->published_at = now();
        }

        $poll->save();

        return redirect()->route('admin.polls.index')
            ->with('success', 'Enquete criada com sucesso!');
    }

    public function show(Poll $poll)
    {
        $poll->load('votes');
        return view('admin.polls.show', compact('poll'));
    }

    public function results(Poll $poll)
    {
        $poll->load('votes');
        return view('admin.polls.results', compact('poll'));
    }
}

