Sindbad~EG File Manager

Current Path : /var/www/html/votacao.camarasap.rs.gov.br/src/Controller/
Upload File :
Current File : /var/www/html/votacao.camarasap.rs.gov.br/src/Controller/CouncilorsVotingsController.php

<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\EventInterface;
use Cake\ORM\TableRegistry;

/**
 * CouncilorsVotings Controller
 *
 * @method \App\Model\Entity\CouncilorsVoting[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class CouncilorsVotingsController extends AppController
{
    /**
     * Index method
     *
     * @return \Cake\Http\Response|null|void Renders view
     */

    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');

    }

    public function beforeFilter(EventInterface $event)
    {
        parent::beforeFilter($event);
        $this->viewBuilder()->setLayout('ajax'); // Use 'ajax' layout for AJAX requests
    }
    
    public function index()
    {
        $this->viewBuilder()->disableAutoLayout();
        $this->loadModel('Votings');
        $this->loadModel('Meetings');

        $activeVotings = $this->Votings->find('all')->where(['active' => true]);

        foreach ($activeVotings as $voting) {
            $meeting = $this->Meetings->get($voting->meeting_id);

            $voting->meeting = $meeting;
        }

        $this->set(compact('activeVotings'));
    }

    /**
     * View method
     *
     * @param string|null $id Councilors Voting id.
     * @return \Cake\Http\Response|null|void Renders view
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view()
    {
        $this->viewBuilder()->disableAutoLayout();
        $this->loadModel('Votings');
        $this->loadModel('VotingVotes');
        $this->loadModel('Meetings');

        $voting = $this->Votings->find('all', [
            'conditions' => [
                'active' => true,
            ],
            'order' => [
                'created' => 'DESC',
            ],
        ])->first();
        $hasVoting = $voting ? true : false;
        $id = $hasVoting ? $voting->id : null;
        $councilior = $this->getLoggedCouncilorId();
        $councilorId = $councilior->id;
        $hasVoted = $hasVoting ? $this->hasVoted($id, $councilorId) : false;
        $voteType = 'in_favor';
        $meeting = $hasVoting ? $this->Meetings->get($voting->meeting_id) : null;
        $counciliorPresent = $this->isCouncilorPresentInMeeting($councilorId);

        if ($this->request->is('ajax')) {
            $votingIdConsult = $this->request->getParam('pass')[0];
            $councilorIdConsult = $this->request->getParam('pass')[1];
            return $this->_checkUpdatesAjax($votingIdConsult, $councilorIdConsult);
        }

        if ($hasVoted) {
            $voteType = $this->getVoteType($id, $councilorId);
        }
        
        $proVotes = $hasVoting ? $this->getVoteCount($id, 'in_favor') : null;
        $contraVotes = $hasVoting ? $this->getVoteCount($id, 'against') : null;
        $abstentionVotes = $hasVoting ? $this->getVoteCount($id, 'abstention') : null;

        $this->set(compact('councilior', 'voting', 'meeting','councilorId', 'hasVoted', 'voteType', 'proVotes', 'contraVotes', 'abstentionVotes', 'hasVoting', 'counciliorPresent'));
    }

    public function submitVote()
    {
        $this->autoRender = false;
        $this->loadModel('VotingVotes');
        $this->loadModel('Votings');
        $this->loadModel('Meetings');

        if ($this->request->is('ajax')) {
            $votingId = $this->request->getData('votingId');
            $councilorId = $this->request->getData('councilorId');
            $selectedVote = $this->request->getData('voteType');
            $voting = $this->Votings->find('all', [
                'conditions' => [
                    'active' => true,
                ],
                'order' => [
                    'created' => 'DESC',
                ],
            ])->first();
            $meeting = $this->Meetings->get($voting->meeting_id);

            if (!$this->hasVoted($votingId, $councilorId)) {
                $votingVote = $this->VotingVotes->newEmptyEntity();
                $votingVote->voting_id = $votingId;
                $votingVote->councilor_id = $councilorId;
                $votingVote->vote = $selectedVote;

                if ($this->VotingVotes->save($votingVote)) {
                    $presentCouncilorsCount = $this->countPresentCouncilors($meeting->id);
                    $votedCouncilors = $this->getVotedCouncilorsCount($voting->id);

                    if ($presentCouncilorsCount === $votedCouncilors) {
                        $voting = $this->Votings->get($votingId);
                        $voting->active = false;
                        $this->Votings->save($voting);

                        $approvalThreshold = ceil($presentCouncilorsCount / 2);
                        $inFavorVotes = $this->getVoteCount($votingId, 'in_favor');

                        if ($inFavorVotes >= $approvalThreshold) {
                            $meeting->message = $voting->name . ' / APROVADO';
                        } else {
                            $meeting->message = $voting->name . ' / REPROVADO';
                        }

                        $this->Meetings->save($meeting);

                        $this->response = $this->response->withType('application/json')->withStringBody(json_encode(['success' => true, 'message' => $meeting->message]));
                        return $this->response;
                    }
                } else {
                    $this->response = $this->response->withType('application/json')->withStringBody(json_encode(['success' => false, 'error' => 'Erro ao salvar o voto. Tente novamente.']));
                    return $this->response;
                }
            } else {
                $this->response = $this->response->withType('application/json')->withStringBody(json_encode(['success' => false, 'error' => 'Você já votou nesta votação.']));
                return $this->response;
            }
        }
    }


    protected function countPresentCouncilors($meetingId)
    {
        $meetingPresencesTable = TableRegistry::getTableLocator()->get('MeetingPresences');
        $presentCouncilors = $meetingPresencesTable->find()
        ->where(['meeting_id' => $meetingId, 'present' => true])
        ->count();

        return $presentCouncilors;
    }

    protected function getVotedCouncilorsCount($votingId)
    {
        $votedCouncilorsCount = $this->VotingVotes->find()
            ->where(['voting_id' => $votingId])
            ->count();

        return $votedCouncilorsCount;
    }

    protected function getLoggedCouncilorId()
    {
        $user = $this->Authentication->getIdentity();

        if ($user) {
            $this->loadModel('Councilors');

            $councilor = $this->Councilors->findByUserId($user->id)->first();

            if ($councilor) {
                return $councilor;
            }
        }

        return null;
    }

    private function isCouncilorPresentInMeeting($councilorId) {
        $this->loadModel('MeetingPresences');
        $this->loadModel('Meetings');
        
        $activeMeeting = $this->Meetings->find()
            ->where(['active' => true])
            ->order(['id' => 'DESC'])
            ->first();
    
        if (empty($activeMeeting)) {
            return false;
        }
    
        $presence = $this->MeetingPresences->find()
            ->where([
                'councilor_id' => $councilorId,
                'meeting_id' => $activeMeeting->id,
                'present' => 1,
            ])
            ->first();
    
        return !empty($presence);
    }

    protected function hasVoted($votingId, $councilorId)
    {
        $votingVote = $this->VotingVotes->find()
            ->where(['voting_id' => $votingId, 'councilor_id' => $councilorId])
            ->first();

        return $votingVote !== null;
    }

    protected function getVoteCount($votingId, $voteType)
    {
        $voteCount = $this->VotingVotes->find()
            ->where(['voting_id' => $votingId, 'vote' => $voteType])
            ->count();

        return $voteCount;
    }

    protected function getVoteType($votingId, $councilorId)
    {
        $this->loadModel('VotingVotes');

        $voteType = $this->VotingVotes
            ->find()
            ->where(['voting_id' => $votingId, 'councilor_id' => $councilorId])
            ->first()
            ->vote;

        return $voteType;
    }

    protected function _checkUpdatesAjax($votingId, $councilorId) {
        $this->loadModel('Votings');
        $this->loadModel('VotingVotes');
        $currentVotingIsActive = true;
    
        $data = [
            'isToReload' => false,
        ];
    
        if ($votingId != 0) {
            $voting = $this->Votings->get($votingId);
            $currentVotingIsActive = $voting->active;
    
            $data['proVotes'] = $this->getVoteCount($votingId, 'in_favor');
            $data['contraVotes'] = $this->getVoteCount($votingId, 'against');
            $data['abstentionVotes'] = $this->getVoteCount($votingId, 'abstention');
        }
    
        $votingActive = $this->Votings->find()
            ->where([
                'active' => true,
                'id !=' => $votingId,
            ])
            ->count() > 0;
    
        if (!$currentVotingIsActive) {
            $data['isToReload'] = true;
        }
    
        if ($votingActive) {
            $data['isToReload'] = true;
        }
    
        return $this->response
            ->withType('application/json')
            ->withStringBody(json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR));
    }
    

    /**
     * Add method
     *
     * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $this->request->allowMethod(['post']);

        $votingId = $this->request->getData('voting_id');
        $councilorId = $this->request->getData('councilor_id');
        $vote = $this->request->getData('vote');


        $votingVotesTable = TableRegistry::getTableLocator()->get('VotingVotes');
        $votingVote = $votingVotesTable->newEntity([
            'voting_id' => $votingId,
            'councilor_id' => $councilorId,
            'vote' => $vote,
        ]);

        if ($votingVotesTable->save($votingVote)) {
            $message = 'Voto registrado com sucesso.';
        } else {
            $message = 'Erro ao registrar o voto. Por favor, tente novamente.';
        }

        $this->set([
            'message' => $message,
            '_serialize' => ['message'],
        ]);
    }

    /**
     * Edit method
     *
     * @param string|null $id Councilors Voting id.
     * @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function edit($id = null)
    {
        //
    }

    /**
     * Delete method
     *
     * @param string|null $id Councilors Voting id.
     * @return \Cake\Http\Response|null|void Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        //
    }
}

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists