<?php

namespace Dashboard\Controllers;

use Dashboard\Core\Controller;

class VoteController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_VOTES');
    }

    public function index()
    {
        $voteLinks = db()->query("SELECT * FROM VoteLinks ORDER BY id DESC");
        $voteLinks = $voteLinks->fetchAll();
        return view('votes.index', compact('voteLinks'));
    }

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

    public function store()
    {
        validate([
            'name' => 'required',
            'link' => 'required'
        ]);

        $insertVoteLinks = db()->prepare("INSERT INTO VoteLinks (name, link) VALUES (?, ?)");
        $insertVoteLinks->execute(array(input("name"), input("link")));
        return back()->flash("success", t__('Vote Link has been added successfully!'));
    }

    public function edit($id)
    {
        $voteLink = db()->prepare("SELECT * FROM VoteLinks WHERE id = ?");
        $voteLink->execute(array($id));
        $voteLink = $voteLink->fetch();

        if (!$voteLink) return view('404');

        return view('votes.edit', compact('voteLink'));
    }

    public function update($id)
    {
        validate([
            'name' => 'required',
            'link' => 'required'
        ]);

        $updateVoteLinks = db()->prepare("UPDATE VoteLinks SET name = ?, link = ? WHERE id = ?");
        $updateVoteLinks->execute(array(input("name"), input("link"), $id));
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

    public function destroy($id)
    {
        $deleteVoteLink = db()->prepare("DELETE FROM VoteLinks WHERE id = ?");
        $deleteVoteLink->execute(array($id));
        return back();
    }
}