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

class Login extends CI_Controller {

    function __construct()
    {
        parent::__construct();
    }

	public function index()
	{
        $this->load->view('login');
    }

    public function validation()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('cid', 'text', 'required');


        if($this->form_validation->run())
        {
            $cid=$this->input->post('cid');

            $this->load->model('Can_login');

            if($this->Can_login->can($cid))
            {
                $this->otp_generate($cid);
            }
            else
            {
               echo "no data found";
            }
            
        }
        else
        {
            $this->session->set_flashdata('error','Fields cannot be empty');
            redirect(base_url().'index.php/Login');
        }
    }

    public function resend_otp()
    {
        $cid=$this->uri->segment('3');
        $cid=trim($cid);
        $cid=urldecode($cid);
        $this->otp_update($cid);
    }

    public function otp_update($cid)
    {
        $otp=rand(10000,99999);
        $cid=trim($cid);
        $cid=urldecode($cid);

        $this->session->unset_userdata('otp');
        $this->session->set_userdata('otp',$otp);

        $this->session->set_flashdata('otp_resent','otp is resent');
        $this->send_mail($cid,$otp);          
         
    }

    public function otp_generate($cid)
    {
        $otp=rand(10000,99999);
        $this->load->model('Insert_OTP_Model');
        $this->session->set_userdata('otp',$otp);
 
        $this->send_mail($cid,$otp);
         
    }

    public function send_mail($cid,$otp)
    {
        $this->load->model('Fetch_Mail_Model');
        $cid=trim($cid);
        $cid=urldecode($cid);
        if($this->Fetch_Mail_Model->Fetch_Mail($cid))
            {
                $email=$this->Fetch_Mail_Model->Fetch_Mail($cid); 
                
                /*$config = array(
                    'protocol' => 'smtp', 
                    'smtp_host' => 'ssl://smtp.gmail.com', 
                    'smtp_port' => 465, 
                    'smtp_user' => 'attendancedsce123@gmail.com', 
                    'smtp_pass' => 'dsce@2020', 
                    'mailtype' => 'html', 
                    'charset' => 'iso-8859-1'
                );

                $this->email->initialize($config);
                $this->email->set_mailtype("html");
                $this->email->set_newline("\r\n");

                $emailContent = 'OTP IS: ';
                $emailContent .=$otp;
                
              
                $this->email->from('attendancedsce123@gmail.com');
                $this->email->to($email);
                $this->email->subject('OTP');
                $this->email->message($emailContent);

                if($this->email->send())
                    echo "DONE";
                else
                    print_r( $this->email->print_debugger());   

                $this->session->set_flashdata('msg',"Mail has been sent successfully");
                $this->session->set_flashdata('msg_class','alert-success'); */
                // $this->load->model('Fetch_SMTP_Data');
                // if($smtp_data=$this->Fetch_SMTP_Data->Fetch_Smtp())
                // {
                //    // $smtp_data=$this->Fetch_SMTP_Data->Fetch_Smtp();
                //     //print_r( $smtp_data[0]->security.'://'.$smtp_data[0]->host);
                //         $config = array(
                //         'protocol' => $smtp_data[0]->protocol, 
                //         'smtp_host' => $smtp_data[0]->security.'://'.$smtp_data[0]->host, 
                //         'smtp_port' => $smtp_data[0]->port, 
                //         'smtp_user' => $smtp_data[0]->username, 
                //         'smtp_pass' => $smtp_data[0]->password,
                //         'mailtype' => 'html', 
                //         'charset' => 'iso-8859-1'
                //     );
    
                //     $this->email->initialize($config);
                //     $this->email->set_mailtype("html");
                //     $this->email->set_newline("\r\n");
    
                //     $emailContent = 'OTP IS: ';
                //     $emailContent .=$otp;
                    
                  
                //     $this->email->from('vote@evoting.site');
                //     $this->email->to($email);
                //     $this->email->subject('OTP ACCE');
                //     $this->email->message($emailContent);
    
                //     if($this->email->send())
                //         $this->session->set_flashdata('msg',"Mail has been sent successfully");
                //     else
                //         {
                //             print_r( $this->email->print_debugger());
                //             $this->session->set_flashdata('msg',"Mail not sent");
                            
                //         }   
    
                //     $this->verify_otp_view($cid);
                    
                // }
                // else
                //     {
                //         print_r( $this->email->print_debugger());
                //         $this->session->set_flashdata('msg',"Mail not sent");
                //     }					

//                 public function send_otp_email($email, $otp, $cid)
// {
    $this->load->model('Fetch_SMTP_Data');
    $this->load->library('email'); // Ensure email library is loaded

    $smtp_data = $this->Fetch_SMTP_Data->Fetch_Smtp();

    if (!empty($smtp_data)) {
        // Extract SMTP details from the first row
        $smtp = $smtp_data[0];

        // Email configuration
        $config = array(
            'protocol'    => $smtp->protocol,                 // usually 'smtp'
            'smtp_host'   => $smtp->host,                     // e.g. smtp.gmail.com
            'smtp_port'   => $smtp->port,                     // 465 (ssl), 587 (tls)
            'smtp_user'   => $smtp->username,                 // full email address
            'smtp_pass'   => $smtp->password,
            'smtp_crypto' => $smtp->security,                 // 'ssl' or 'tls'
            'mailtype'    => 'html',
            'charset'     => 'utf-8',
            'newline'     => "\r\n",
            'crlf'        => "\r\n",
            'wordwrap'    => TRUE,
        );

        $this->email->initialize($config);
        $this->email->set_newline("\r\n");
        $this->email->set_mailtype("html");

        // Email content
        $emailContent = "<h3>Your OTP is: <strong>{$otp}</strong></h3>";

        // From and To
        $this->email->from($smtp->username, 'eVoting System');
       $this->email->to($email->email);
        $this->email->subject('Your OTP for Verification');
        $this->email->message($emailContent);

        if ($this->email->send()) {
            $this->session->set_flashdata('msg', "Mail has been sent successfully.");
              echo  $otp;
        } else {
            // Output debug info if sending fails
            echo "<pre>";
            print_r($this->email->print_debugger());
            echo "</pre>";
            $this->session->set_flashdata('msg', "Mail not sent. See debug info.");
        }

    echo  $otp;

        // Redirect or load OTP view
        $this->verify_otp_view($cid);
    } else {
        $this->session->set_flashdata('msg', "SMTP configuration not found.");
        redirect('some_error_page'); // or handle gracefully
    }
// }


                /*$params = array(
                    'api_user'  => $user,
                    'api_key'   => $pass,
                    'x-smtpapi' => json_encode($json_string),
                    'to'        => 'example3@sendgrid.com',
                    'subject'   => 'testing from curl',
                    'html'      => 'testing body',
                    'text'      => 'testing body',
                    'from'      => 'example@sendgrid.com',
                  );
                
                
                $request =  $url.'api/mail.send.json';
                
                // Generate curl request
                $session = curl_init($request);
                // Tell curl to use HTTP POST
                curl_setopt ($session, CURLOPT_POST, true);
                // Tell curl that this is the body of the POST
                curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
                // Tell curl not to return headers, but do return the response
                curl_setopt($session, CURLOPT_HEADER, false);
                // Tell PHP not to use SSLv3 (instead opting for TLS)
                curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
                curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
                
                // obtain response
                $response = curl_exec($session);
                curl_close($session);
                
                // print everything out
                print_r($response);
                
                ?>
                */
         }

    }

    public function verify_otp_view($cid)
    {
        $cid=trim($cid);
        $cid=urldecode($cid);

        $datas['data']=$cid;
        $this->load->view('otp_verfiy_view',$datas);
    }

    public function verify_otp($cid)
    {
        $otp=$this->input->post('otp');
        $cid=urldecode($cid);
        $cid=trim($cid);
        $this->load->model('Can_login');
        $this->load->model('Voting_Titles_Admin_Data');

        if(($this->session->userdata('otp'))==$otp)
        {
            $this->session->unset_userdata('otp');
            // $zone=" ";
            //redirect(base_url()."index.php/Login/show_data/".$cid);
            
            // print_r($this->Voting_Titles_Admin_Data->Fetch_Data_User($cid));die();
            $zone=$this->Voting_Titles_Admin_Data->Fetch_Data_User($cid);
          // print_r($this->Voting_Titles_Admin_Data->Fetch_Data($zone));die();
        
        if($this->Voting_Titles_Admin_Data->Fetch_Data_User($cid))
            {   
                $zone=$this->Voting_Titles_Admin_Data->Fetch_Data_User($cid);

                if($this->Voting_Titles_Admin_Data->Fetch_Data($zone))
                {   
                    $this->session->set_userdata('client',$cid);
                    $all_data['data']=$this->Voting_Titles_Admin_Data->Fetch_Data($zone);
                    $this->load->view('Ballot_View_Client',$all_data);
                }
                else
                {
                    echo "no";
                }
            }
        else
        {
            echo "no";
        }
            
            
            
            
            
            
            
            
            
            
            
        }
        else
        {
            $this->session->set_flashdata('invalid_otp','Invalid OTP');
            redirect(base_url().'index.php/Login/verify_otp_view/'.$cid);
        }
    }

    public function show_data()
    {
        $cid = $this->uri->segment(3);   
        $cid=urldecode($cid);
        $cid=trim($cid);
        $this->load->model('Show_Data_Model');

        if($this->Show_Data_Model->User_data($cid))
            {
                $data=$this->Show_Data_Model->User_data($cid);

                if($data[0]->type == "super_admin")
                {
                    $this->load->model('Show_All_Data_Model');

                    if($this->Show_All_Data_Model->Fetch_Data())
                    {   
                        $all_data['data']=$this->Show_All_Data_Model->Fetch_Data();

                        $this->session->set_userdata('super_admin',$cid);

                        redirect(base_url().'index.php/Dashboard_Controller/Count_Func');
                    }    
                    
                }

                else if($data[0]->type == "admin")
                {
                    $this->load->model('Show_All_Data_Model');

                    if($this->Show_All_Data_Model->Fetch_Data())
                    {   
                        $all_data['data']=$this->Show_All_Data_Model->Fetch_Data();
                        $this->session->set_userdata('admin',$cid);

                        redirect(base_url().'index.php/Dashboard_Controller_Admin/Count_Func');
                    }    
                    
                }

                else
                {
                    $this->load->model('Show_Data_Model');

                    if($this->Show_Data_Model->User_data($cid))
                    {   
                        $all_data['data']=$this->Show_Data_Model->User_data($cid);
                      
                        $this->session->set_userdata('client',$cid);

                        $this->load->view('Client_Data_View',$all_data);
                        //echo " ".$all_data[0]->id;
                    } 
                    
                }
                
            }
            else
            {
                $this->session->set_flashdata('error'.'Invalid username and password');
                redirect(base_url().'index.php/Login');
            }
    }


    function Show_Data_Edit($email_name)
    {
        $this->load->model('Show_Data');
        $email_name=urldecode($email_name);
        $email_name=trim($email_name);
            if($this->Show_Data->User_data($email_name))
                {   
                    $all_data['data']=$this->Show_Data->User_data($email_name);

                    $this->load->view('client_data',$all_data);
                }
    }

    function Log_Out()
    {   
        $this->load->view('login');

        if($this->session->userdata('admin')){
 
            $this->session->unset_userdata('admin');
          
          }
        
        else if($this->session->userdata('super_admin')){
 
            $this->session->unset_userdata('super_admin');
          
          }
         
        else
        {
            $this->session->unset_userdata('client');
        }  
       
    }


    public function userList()
    {
        $this->load->model('Show_All_Data_Model');

        if($this->Show_All_Data_Model->Fetch_Data())
        {   
            $all_data['data']=$this->Show_All_Data_Model->Fetch_Data();
            //print_r($all_data['data']);die();
            
            $this->load->view('welcome_message',$all_data);
        }
    }

    public function userListAdmin()
    {
        $this->load->model('Show_All_Data_Model');

        if($this->Show_All_Data_Model->Fetch_Data())
        {   
            $all_data['data']=$this->Show_All_Data_Model->Fetch_Data();
            
            $this->load->view('welcome_message_admin',$all_data);
        }
    }
}
?>