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

class Add_Participant_Controller extends CI_Controller {

    public function AddCandidates() {
        $this->load->model('Add_Ballot_Model');
        
        $all_data['data'] = $this->Add_Ballot_Model->Show_Ballot();
        $this->load->view('Add_Candidates_View', $all_data);    
    }

    public function VotingCandidates() {
        if(isset($_SESSION['candidate_added'])){
            unset($_SESSION['candidate_added']);
        }

        $ballot = $this->input->post('ballot');
        $this->load->database();

        // Get total number of candidates from ballot table
        $query = $this->db->get_where('ballot', ['ballot_name' => $ballot]);
        $result = $query->row();
        $total_candidates = $result ? (int)$result->total_candidates : 1;

        // Upload configuration
        $config['upload_path'] = './upload/';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['encrypt_name'] = TRUE;
        $this->load->library('upload');

        $this->load->model('Add_Candidate_Model');
        $all_success = true;

        for ($i = 1; $i <= $total_candidates; $i++) {
            $candidate_name = $this->input->post("candidate_name_$i");
            $place = $this->input->post("candidate_place_$i");
            $image_field = "candidate_image_$i";
            $image_url = "";

            if (!empty($_FILES[$image_field]['name'])) {
                $_FILES['file']['name']     = $_FILES[$image_field]['name'];
                $_FILES['file']['type']     = $_FILES[$image_field]['type'];
                $_FILES['file']['tmp_name'] = $_FILES[$image_field]['tmp_name'];
                $_FILES['file']['error']    = $_FILES[$image_field]['error'];
                $_FILES['file']['size']     = $_FILES[$image_field]['size'];

                $this->upload->initialize($config);

                if ($this->upload->do_upload('file')) {
                    $upload_data = $this->upload->data();
                    $image_url = base_url("upload/" . $upload_data['file_name']);
                } else {
                    $all_success = false;
                    log_message('error', 'Upload error: ' . $this->upload->display_errors());
                    continue;
                }
            }

            // Data to insert
            $data = [
                'participant_name' => $candidate_name,
                'ballot_name'      => $ballot,
                'img_url'          => $image_url,
                'place'            => $place,
                'vote'             => 0
            ];

            if (!$this->Add_Candidate_Model->Insert_Data_Candidates($data)) {
                $all_success = false;
            }
        }

        if ($all_success) {
            $this->session->set_flashdata('candidate_added', 'All candidates added successfully.');
        } else {
            $this->session->set_flashdata('candidate_added', 'Some candidates could not be added.');
        }

        redirect(base_url() . 'index.php/Add_Participant_Controller/AddCandidates', 'refresh');
    }

    public function getTotalCandidates() {
        $ballot_name = $this->input->post('ballot_name');
        $this->load->database();
        $query = $this->db->get_where('ballot', ['ballot_name' => $ballot_name]);
        $result = $query->row();
        echo json_encode(['total_candidates' => $result ? $result->total_candidates : 0]);
    }
}
