<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Update_Voting extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Show_Vote_Data_To_Update');
        $this->load->model('Update_Vote_Model');
    }

    public function vote_update() {
        $participant_name = trim(urldecode($this->input->get('participant_name')));
        $ballot_name = trim(urldecode($this->input->get('ballot_name')));
        $ip_address = $this->input->get('ip_address');

        $client_id = trim(urldecode($this->session->userdata('client')));

        // Get vote count
        $vote_count = (int) $this->Show_Vote_Data_To_Update->participant_vote($participant_name, $ballot_name);

        // Get client name
        $client_name = $this->get_client_name($client_id);
        if (!$client_name) {
            $this->session->set_flashdata('vote_done', 'Client not found.');
            redirect($this->get_redirect_url());
        }

        // Update client vote
        $status1 = $this->Update_Vote_Model->Update_Client_Vote_Status($client_id, $ballot_name, $client_name, $participant_name, $ip_address);

        // Update participant vote
        $vote_data = ['vote' => $vote_count + 1];
        $status2 = $this->Update_Vote_Model->Update_Participant_Vote($participant_name, $vote_data, $ballot_name);

        if ($status1 && $status2) {
            $this->session->set_flashdata('vote_done', 'YOUR VOTE IS SUBMITTED, THANK YOU');
        } else {
            $this->session->set_flashdata('vote_done', 'YOUR VOTE IS NOT REGISTERED, TRY AGAIN');
        }

        redirect($this->get_redirect_url());
    }

    public function multiple_vote_update() {
        // Validate session
        if (!$this->session->userdata('client')) {
            $this->session->set_flashdata('error', 'Session expired. Please login again.');
            redirect('/Login');
        }

        $participant_names = $this->input->post('participant_name', TRUE);
        $ballot_name = trim(urldecode($this->input->post('ballot_name', TRUE)));
        $ip_address = $this->input->server('REMOTE_ADDR');
        $client_id = trim(urldecode($this->session->userdata('client')));

        if (empty($participant_names)) {
            $this->session->set_flashdata('error', 'Please select at least one candidate.');
            redirect($this->get_redirect_url());
        }

        if (!is_array($participant_names)) {
            $participant_names = [$participant_names];
        }

        $client_name = $this->get_client_name($client_id);
        if (!$client_name) {
            $this->session->set_flashdata('error', 'User not found.');
            redirect($this->get_redirect_url());
        }

        $success_count = 0;
        foreach ($participant_names as $participant_name) {
            $participant_name = trim(urldecode($participant_name));
            $vote_count = (int) $this->Show_Vote_Data_To_Update->participant_vote($participant_name, $ballot_name);
            $vote_data = ['vote' => $vote_count + 1];

            $status1 = $this->Update_Vote_Model->Update_Client_Vote_Status($client_id, $ballot_name, $client_name, $participant_name, $ip_address);
            $status2 = false;

            if ($status1) {
                $status2 = $this->Update_Vote_Model->Update_Participant_Vote($participant_name, $vote_data, $ballot_name);
                if (!$status2) {
                    $this->Update_Vote_Model->rollback_client_vote($client_id, $ballot_name);
                }
            }

            if ($status1 && $status2) {
                $success_count++;
            }
        }

        if ($success_count == count($participant_names)) {
            $this->session->set_flashdata('success', 'All your votes have been successfully submitted. Thank you!');
        } elseif ($success_count > 0) {
            $this->session->set_flashdata('warning', "$success_count out of ".count($participant_names)." votes submitted successfully.");
        } else {
            $this->session->set_flashdata('error', 'Failed to submit any votes. Please try again.');
        }

        redirect($this->get_redirect_url());
    }

    private function get_client_name($client_id) {
        $query = $this->db->select('name')->from('users')->where('cid', $client_id)->get();
        if ($query->num_rows() > 0) {
            return $query->row()->name;
        }
        return false;
    }

    private function get_redirect_url() {
        $client_id = trim($this->session->userdata('client'));
        $client_id = str_replace(' ', '%20', $client_id);
        return base_url('index.php/Show_Voting_Data_Client/VotingTitlesDataClient/'.$client_id);
    }
}
