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

class ApplicationController extends CI_Controller
{
    public function index()
    {
        $query = $this->db->select('*')
            ->from('course')
            ->get();

        $view_data['records']  = $query->result();


        $data = array(
            'title' => 'Dashboard',
            'page' => 'Dashboard',
            'content' => $this->load->view('sample', $view_data, true),
            // 'content' => $this->load->view('masters/courseview', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }
    public function Course()
    {

        $course_name = $this->input->post('course_name');
        $short_name = $this->input->post('short_name');
        $id = $this->input->post('id');

        if ($id) {
            $update_array = array(
                'course_name'    => $course_name,
                'short_name'    => $short_name,
            );
            $update = $this->mcommon->common_edit('course', $update_array, array('id' => $id));


            if ($update) {


                $this->session->set_flashdata('alert_success', 'Course Updated successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        } else {
            $user_array = array(
                'course_name'    => $course_name,
                'short_name'    => $short_name,
            );
            $insert = $this->mcommon->common_insert('course', $user_array);

            if ($insert) {


                $this->session->set_flashdata('alert_success', 'Course Added successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        }


        redirect('ApplicationController/');
    }



    public function appFees()
    {
        $this->db->select('fees.id,fees.fees,c.course_name,fees.course, fees.status');
        $this->db->from('application_fees as fees');
        $this->db->join('course as c', 'c.id = fees.course', 'left');
        $query = $this->db->get();
        $view_data['records'] = $query->result();

        $courses = $this->db->select('*')
            ->from('course')
            ->where('status', '1')
            ->get();

        $view_data['courses']  = $courses->result();

        //   print_r($view_data['courses']);
        // die();

        $data = array(
            'title' => 'Application Fees',
            'page' => 'Application Fees',
            'content' => $this->load->view('masters/applicationFees', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }





    public function addEditFees()
    {

        $id = $this->input->post('id');
        $courseId = $this->input->post('courseId');
        $fees = $this->input->post('fees');

        if ($id) {
            $update_array = array(
                'course'    => $courseId,
                'fees'    => $fees,
            );

            $update = $this->mcommon->common_edit('application_fees', $update_array, array('id' => $id));


            if ($update) {


                $this->session->set_flashdata('alert_success', 'Application Fees Updated Successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        } else {
            $user_array = array(
                'course'    => $courseId,
                'fees'    => $fees,
            );
            $insert = $this->mcommon->common_insert('application_fees', $user_array);


            if ($insert) {


                $this->session->set_flashdata('alert_success', 'Application Fees Added successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        }


        redirect('ApplicationController/appFees');
    }



    public function tution()
    {
        $query = $this->db->select('*')
            ->from('tution')
            ->get();

        // print_r($query->result());
        // die();
        $view_data['records']  = $query->result();
        $data = array(
            'title' => 'Dashboard',
            'page' => 'Dashboard',
            'content' => $this->load->view('masters/tution', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }
    public function addEditTution()
    {

        $tution_name = $this->input->post('tution_name');
        $id = $this->input->post('id');

        if ($id) {
            $update_array = array(
                'tution_name'    => $tution_name,
            );
            $update = $this->mcommon->common_edit('tution', $update_array, array('id' => $id));


            if ($update) {


                $this->session->set_flashdata('alert_success', 'tution Updated successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        } else {
            $user_array = array(
                'tution_name'    => $tution_name,
            );
            $insert = $this->mcommon->common_insert('tution', $user_array);


            if ($insert) {


                $this->session->set_flashdata('alert_success', 'tution Added successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        }


        redirect('ApplicationController/tution');
    }


    public function tutionFees()
    {


        $query = $this->db->select('*')
            ->from('tution_fees')
            ->where('status', '1')
            ->get();


        $this->db->select('fees.id,fees.fees,c.tution_name,fees.tution, fees.courses, fees.status, co.course_name,');
        $this->db->from('tution_fees as fees');
        $this->db->join('tution as c', 'c.id = fees.tution', 'left');
        $this->db->join('course as co', 'co.id = fees.courses', 'left');
        // $this->db->where('fees.status=', 1);
        $query = $this->db->get();
        $view_data['records'] = $query->result();

        $tution = $this->db->select('*')
            ->from('tution')
            ->where('status', '1')
            ->get();

        $courses = $this->db->select('*')
            ->from('course')
            ->where('status', '1')
            ->get();

        $view_data['courses']  = $courses->result();
        $view_data['tution']  = $tution->result();

        //   print_r($view_data['tutions']);
        // die();

        $data = array(
            'title' => 'tution Fees',
            'page' => 'tution Fees',
            'content' => $this->load->view('masters/tutionFees', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }


    public function addEditTutionFees()
    {

        $id = $this->input->post('id');
        $tutionId = $this->input->post('tutionId');
        $courses = $this->input->post('courseId');
        $fees = $this->input->post('fees');

        if ($id) {
            $update_array = array(
                'tution'    => $tutionId,
                'courses' => $courses,
                'fees'    => $fees,
            );

            $update = $this->mcommon->common_edit('tution_fees', $update_array, array('id' => $id));


            if ($update) {
                $this->session->set_flashdata('alert_success', 'tution Fees Updated Successfully!');
            } else {
                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        } else {
            $user_array = array(
                'tution'    => $tutionId,
                'courses' => $courses,
                'fees'    => $fees,
            );
            $insert = $this->mcommon->common_insert('tution_fees', $user_array);


            if ($insert) {


                $this->session->set_flashdata('alert_success', 'tution Fees Added successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        }


        redirect('ApplicationController/tutionFees');
    }


    public function accadamicStatusChange()
    {
        $id     = $this->input->post('id');
        $table  = $this->input->post('table');
        $status  = $this->input->post('status');

        $update_array = array(
            'status'    => 1,
        );

        $this->mcommon->common_update($table, 'status', 0);
        $update = $this->mcommon->common_edit($table, $update_array, array('id' => $id));

        if ($update) {
            $this->session->set_flashdata('alert_success', 'Status Changed Successfully!');
        } else {
            $this->session->set_flashdata('alert_danger', 'Something went wrong');
        }

        redirect($_SERVER['HTTP_REFERER']);
    }



    public function commonStatusChange()
    {
        $id     = $this->input->post('id');
        $table  = $this->input->post('table');
        $status  = $this->input->post('status');
     
        $newStatus = ($status == 1 ) ? 0 : 1;

        $update_array = array(
            'status'    => $newStatus,
        );
        $update = $this->mcommon->common_edit($table, $update_array, array('id' => $id));

        if ($update) {
            $this->session->set_flashdata('alert_success', 'Status Changed Successfully!');
        } else {
            $this->session->set_flashdata('alert_danger', 'Something went wrong');
        }
        // $this->db
        // return view
        redirect($_SERVER['HTTP_REFERER']);
        // redirect('ApplicationController/');
    }

    public function instruction()
    {

        $query = $this->db->select('*')
            ->from('instruction')
            ->get();

        // $view_data['instruction'] = $this->mcommon->specific_row('instruction', array('id' => 1));


        $view_data['instruction'] = $query->result();
        $data = array(
            'title' => 'Instruction',
            'page' => 'Instruction',
            'content' => $this->load->view('masters/instruction', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }

    public function accadamicYear()
    {

        $query = $this->db->select('*')
            ->from('accadamic_year')
            ->where('status', '1')
            ->get();

        $this->db->select('year.id,year.year,year.status,year.created_at');
        $this->db->from('accadamic_year as year');
        // $this->db->where('year.status=',1);
        $query = $this->db->get();
        $view_data['records'] = $query->result();

        $year = $this->db->select('*')
            ->from('accadamic_year')
            // ->where('status', '1')
            ->get();

        $view_data['year']  = $year->result();

        $data = array(
            'title' => 'Accadamic Year',
            'page' => 'Accadamic Year',
            'content' => $this->load->view('masters/accadamicYear', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }

    public function addCourse()
    {

        $id = $this->input->post('id');
        $year = $this->input->post('year');

        $update_array = array(
            'year'    => $year,
        );
        if ($id!="") {
            $update = $this->mcommon->common_edit('accadamic_year', $update_array, array('id' => $id));

            if ($update) {
                $this->session->set_flashdata('alert_success', 'Accadamic Year Updated Successfully!');
            } else {
                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        } else {
            $insert = $this->mcommon->common_insert('accadamic_year', $update_array);

            if ($insert) {
                $this->session->set_flashdata('alert_success', 'Accadamic Year Added successfully!');
            } else {
                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        }
        redirect('ApplicationController/accadamicYear');
    }


    public function hash_passwd($password, $random_salt = '')
    {
        // If no salt provided for older PHP versions, make one
        if (!is_php('5.5') && empty($random_salt)) {
            $random_salt = $this->random_salt();
        }

        // PHP 5.5+ uses new password hashing function
        if (is_php('5.5')) {
            return password_hash($password, PASSWORD_BCRYPT, ['cost' => 11]);
        }

        // PHP < 5.5 uses crypt
        else {
            return crypt($password, '$2y$10$' . $random_salt);
        }
    }

    public function random_salt()
    {
        $this->CI->load->library('encryption');

        $salt = substr(bin2hex($this->CI->encryption->create_key(64)), 0, 22);

        return strlen($salt) != 22
            ? substr(md5(mt_rand()), 0, 22)
            : $salt;
    }

    public function faculty()
    {
        $this->db->select('*');
        $this->db->from('faculty');
        $query = $this->db->get();
        $view_data['records'] = $query->result();
        $data = array(
            'title' => 'Faculty',
            'page' => 'Faculty',
            'content' => $this->load->view('faculty/view', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }
    public function facultyadd()
    {
        $data = array(
            'title' => 'Facultyadd',
            'page' => 'Facultyadd',
            'content' => $this->load->view('faculty/add', '', true),
        );
        $this->load->view('base/base_template', $data);
    }
    public function store()
    {
        $name = $this->input->post('facultyname');
        $mobile = $this->input->post('mobile');
        $email = $this->input->post('email');
        $password = $this->input->post('password');
        $c_password = $this->input->post('confirm_password');

        // $this->form_validation->set_rules('facultyname', 'Username', 'required');
        // $this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]', array('is_unique' => 'Email already exists!.'));
        // $this->form_validation->set_rules('mobile', 'Mobile', 'required|is_unique[users.mobile]', array('is_unique' => 'Mobile already exists!.'));
        // $this->form_validation->set_rules('mobile', 'Mobile', 'required');
        // $this->form_validation->set_rules('password', 'Password', 'required|regex_match[/^(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])[A-Za-z0-9!@#$%^&*]{8,}$/]', array('regex_match' => 'The %s must contain at least one uppercase letter, one number, one special character, and be at least 8 characters long.'));
        // $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]', array('matches' => 'Passwords do not match.'));

        // if($this->form_validation->run() == true){
        $insert_array = array(
            'f_name'          =>  $name,
            'f_email'         =>  $email,
            'f_mobile'        =>  $mobile,
            'passwd'        =>  password_hash($password, PASSWORD_DEFAULT), //$this->hash_passwd($password),
        );

        $user_array = array(
            'name'          =>  $name,
            'email'         =>  $email,
            'mobile'        =>  $mobile,
            'passwd'        =>  password_hash($password, PASSWORD_DEFAULT), //$this->hash_passwd($password),
            'status'        =>  2,
            'auth_level'    =>  5,
        );


        $insert = $this->mcommon->common_insert('users', $user_array);
        $insert = $this->mcommon->common_insert('faculty', $insert_array);

        if ($insert) {

            $this->session->set_flashdata('alert_success', 'Faculty added successfully!');
            redirect('ApplicationController/faculty');
        }
        // } else {
        //     $this->session->set_flashdata('alert_danger', 'Error in registration!');
        // }

    }
    public function edit($id)
    {

        $view_data['records'] = $this->mcommon->specific_row('faculty', array('id' => $id));
        // print_r($view_data['records'] );
        // die();
        $data = array(
            'title' => '',
            'page' => '',
            'content' => $this->load->view('faculty/edit', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }
    public function update()
    {
        $id = $this->uri->segment(3);

        $name = $this->input->post('facultyname');
        $mobile = $this->input->post('mobile');
        $email = $this->input->post('email');

        $password = $this->input->post('password');
        $c_password = $this->input->post('confirm_password');

        $update_array = array(
            'f_name'          =>  $name,
            'f_email'         =>  $email,
            'f_mobile'        =>  $mobile,
            'passwd'        =>  password_hash($password, PASSWORD_DEFAULT), // $this->hash_passwd($password),
        );

        $user_array = array(
            'name'          =>  $name,
            'email'         =>  $email,
            'mobile'        =>  $mobile,
            'passwd'        =>  password_hash($password, PASSWORD_DEFAULT), //$this->hash_passwd($password),
            'status'        =>  2,
        );
        $update = $this->mcommon->common_edit('users', $user_array, array('email' => $email));
        $update = $this->mcommon->common_edit('faculty', $update_array, array('id' => $id));
        if ($update) {
            $this->session->set_flashdata('alert_success', 'updated successfully!');
            redirect('ApplicationController/faculty');
        } else {
            $this->session->set_flashdata('alert_danger', 'updated failure!');
            redirect('ApplicationController/edit');
        }
    }
    public function delete($id)
    {
        $delete = $this->mcommon->common_delete('faculty', array('id' => $id));

        $this->session->set_flashdata('alert_danger', 'Record Deleted successfully!');
        redirect('ApplicationController/faculty');
    }
    


    public function draftformdetails()
    {

        $view_data['courses'] = $this->mcommon->records_all('course');
        // print_r(  $view_data['courses'] );exit;

        $this->db->select('*, applications.id as appid, applications.status as apstatus,ai.payment_mode ');
        $this->db->from('applications');
        $this->db->join('course', 'course.id = applications.course_id', 'left');
        $this->db->join('users', 'users.user_id = applications.user_id', 'left');
        $this->db->join('accomodation_info as ai', 'ai.application_id = applications.id', 'left');
        $this->db->join('application_other_info as athinfo', 'athinfo.application_id = applications.id', 'left');
        // $this->db->where('athinfo.tab_status', '0');
        $this->db->where('applications.payment_status', '0');
        $query = $this->db->get();

        $view_data['records'] = $query->result();
        // echo'<pre>'; print_r( $view_data['records']);
        // exit();
        $view_data['page'] = 'Draft List';

        $data = array(
            'title' => 'Draft List',
            'page' => 'Draft List',
            'content' => $this->load->view('masters/Pendinglist', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }


    public function pendingformdetails()
    {
        $view_data['courses'] = $this->mcommon->records_all('course');

        $this->db->select('*, applications.id as appid, applications.status as apstatus,ai.payment_mode,applications.email as appEmail');
        $this->db->from('applications');
        $this->db->join('course', 'course.id = applications.course_id', 'left');
        $this->db->join('users', 'users.user_id = applications.user_id','left');
        $this->db->join('accomodation_info as ai', 'ai.application_id = applications.id','left');
        $this->db->join('application_other_info as athinfo', 'athinfo.application_id = applications.id','left');
        // $this->db->where('athinfo.tab_status', '1');
        $this->db->where('applications.payment_status', '1');
        $query = $this->db->get();

        $view_data['records'] = $query->result();
        // echo'<pre>'; print_r( $view_data['records']);
        // exit();
        $view_data['page'] = 'Pending List';

        $data = array(
            'title' => 'Pending List',
            'page' => 'Pending List',
            'content' => $this->load->view('masters/Pendinglist', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }

    public function completedformdetails()
    {

        $view_data['courses'] = $this->mcommon->records_all('course');
        $this->db->select('*, applications.id as appid, applications.status as apstatus');
        $this->db->from('applications');
        $this->db->join('course', 'course.id = applications.course_id', 'left');
        $this->db->join('users', 'users.user_id = applications.user_id', 'left');
        $this->db->join('parent_info as pi', 'pi.application_id = applications.id', 'left');
        $this->db->join('accomodation_info as ai', 'ai.application_id = applications.id', 'left');
        $this->db->where('applications.payment_status', '2');
        $query = $this->db->get();

        $view_data['records'] = $query->result();
        $view_data['page'] = 'Completed List';
        $view_data['schedule'] =  $this->mcommon->records_all('exam_schedule',array('status',1));
        $view_data['question_category'] =  $this->mcommon->records_all('question_category',array('status',1));

        $data = array(
            'title' => 'Completed List',
            'page' => 'Completed List',
            'content' => $this->load->view('masters/Completedlist', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    
    }


    public function formdetails()
    {

        $courses = $this->db->select('*')
            ->from('course')
            ->where('status', '1')
            ->get();
        $view_data['courses'] = $courses->result();

        $this->db->select('*, applications.id as appid, applications.status as apstatus');
        $this->db->from('applications');
        $this->db->join('course', 'course.id = applications.course_id', 'left');
        $this->db->join('users', 'users.user_id = applications.user_id');
        $this->db->where('applications.short_list', '1');
        $query = $this->db->get();

        $view_data['records'] = $query->result();
        $view_data['page'] = 'Shortlisted';

        $data = array(
            'title' => 'Shortlisted',
            'page' => 'Shortlisted',
            'content' => $this->load->view('masters/Applicationlist', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }


    public function shortList()
    {

        $shortList     = $this->input->post('id');

        // echo '<pre>';
        // print_r($shortList);
        // die();

        foreach ($shortList as $valu) {
            $update_array = array(
                'short_list' =>  1,
            );
            $update = $this->mcommon->common_edit('applications', $update_array, array('id' => $valu));
        }
        echo  json_encode($update);
    }
    public function viewApplication($userId)
    {


        $view_data['academicYear'] = $this->mcommon->specific_row('accadamic_year', array('status' => 1));
        $view_data['userDetails']  = $this->mcommon->specific_row('users', array('user_id' => $userId));

        $applicationId = $this->mcommon->specific_row_value('applications', array('user_id' => $userId), 'id');

        if ($applicationId) {

            // $this->db->select('*, applications.dob as dateofbirth');
            // $this->db->from('applications as applications');
            // $this->db->join('course as c', 'c.id = applications.course_id', 'left');
            // $this->db->where('applications.id', $applicationId);
            // $query = $this->db->get();
            // $view_data['personalInfo'] = $query->row_array();


            $this->db->select('*, applications.dob as dateofbirth');
            $this->db->from('applications');
            $this->db->join('course', 'course.id = applications.course_id', 'left');
            $this->db->join('users', 'users.user_id = applications.user_id');
            $this->db->where('applications.id', $applicationId);
            $query = $this->db->get();
            $view_data['personalInfo']          = $query->row();


            $view_data['parentInfo']        =  $this->mcommon->specific_row('parent_info', array('application_id' => $applicationId));
            $view_data['educationWorkInfo']  =  $this->mcommon->records_all('education_work_experience', array('application_id' => $applicationId));
            $view_data['otherInfo']          =  $this->mcommon->specific_row('application_other_info', array('application_id' => $applicationId));
            $view_data['accomodation_info']          =  $this->mcommon->specific_row('accomodation_info', array('application_id' => $applicationId));
        }


        $query = $this->db->select('*')
            ->from('course')
            ->get();

        $data = array(
            'title' => 'Application preview',
            'page' => 'Application preview',
            'content' => $this->load->view('masters/previewapplication', $view_data, true),
        );
        $this->load->view('base/login_template', $data);
    }
   

    public function downloadApplication($userId)
    {

        $this->load->library('m_pdf');
        $view_data['academicYear'] = $this->mcommon->specific_row('accadamic_year', array('status' => 1));
        $view_data['userDetails']  = $this->mcommon->specific_row('users', array('user_id' => $userId));

        $applicationId = $this->mcommon->specific_row_value('applications', array('user_id' => $userId), 'id');

        if ($applicationId) {

            $this->db->select('*, applications.dob as dateofbirth');
            $this->db->from('applications');
            $this->db->join('course', 'course.id = applications.course_id', 'left');
            $this->db->join('users', 'users.user_id = applications.user_id');
            $this->db->where('applications.id', $applicationId);
            $query = $this->db->get();
            $view_data['personalInfo']          = $query->row();


            $view_data['parentInfo']        =  $this->mcommon->specific_row('parent_info', array('application_id' => $applicationId));
            $view_data['educationWorkInfo']  =  $this->mcommon->records_all('education_work_experience', array('application_id' => $applicationId));
            $view_data['otherInfo']          =  $this->mcommon->specific_row('application_other_info', array('application_id' => $applicationId));
            $view_data['accomodation_info']          =  $this->mcommon->specific_row('accomodation_info', array('application_id' => $applicationId));

            $html = $this->load->view('masters/previewapplication', $view_data, true);
            $this->load->library('m_pdf');
            $pdf = $this->m_pdf->load();
            $pdf->WriteHTML($html);
            $pdf->Output('Application_' . $userId . '.pdf', 'D');
            ob_clean();
            ob_flush();
        }

       
    }



    public function scoreList()
    {

        $courses = $this->db->select('*')
            ->from('course')
            ->where('status', '1')
            ->get();
        $view_data['courses'] = $courses->result();

        $this->db->select('*, applications.id as appid, applications.status as apstatus');
        $this->db->from('applications');
        $this->db->join('course', 'course.id = applications.course_id', 'left');
        $this->db->join('users', 'users.user_id = applications.user_id');
        $this->db->where('applications.short_list', '1');
        $query = $this->db->get();



        $view_data['records'] = $query->result();
        $view_data['page'] = 'Shortlisted';

        $data = array(
            'title' => 'Score',
            'page' => 'Score',
            'content' => $this->load->view('score/scoreList', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }


    public function viewScores($appId)
    {
        $this->db->select('*, applications.id as appid, applications.status as apstatus,users.name as facultyName');
        $this->db->from('applications');
        $this->db->join('score', 'score.application_id = applications.id', 'left');
        $this->db->join('users', 'users.user_id = score.facultyId', 'left');
        $this->db->where('applications.id', $appId);
        $query = $this->db->get();

        $view_data['records'] = $query->result();


        // echo '<pre>';
        // print_r($view_data['records']);
        // exit();

        $data = array(
            'title' => 'View Score',
            'page' => 'View Score',
            'content' => $this->load->view('score/viewScores', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }
    public function referenceno()
    {
        
        $view_data['record'] = $this->mcommon->specific_row('reference_no', array('id' => 1));
        // print_r($view_data); exit;
        $data = array(
            'title' => 'Referenceno',
            'page' => 'Referenceno',
            'content' => $this->load->view('masters/referenceno', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }
    public function store_refno()
    {

        $inputid = $_POST['id'];
        // print_r($inputid);
        $ref_num = $this->input->post('Reference_no');
        $mobile = $this->input->post('mobile');
        $email = $this->input->post('email');


        $records = $this->mcommon->specific_row('reference_no', array('id' => $inputid));
        // print_r($records['ref_number']); exit;
        if ($records['ref_number'] == $ref_num) {
            $update_array = array(
                'ref_number' => $ref_num,
                'mobile' => $mobile,
                'email' => $email,
            );
        } else {
            $update_array = array(
                'ref_number' => $ref_num,
                'ref_status' => 1,
                'mobile' => $mobile,
                'email' => $email,
            );
        }

        // $id =  $view_data['records']['id'];
        // $num = $view_data['records']['ref_number'];

        if ($records) {
            $update = $this->mcommon->common_edit('reference_no', $update_array, array('id' => $inputid));
            redirect('ApplicationController/referenceno');
        } else {
            $insert = $this->mcommon->common_insert('reference_no', $update_array);
        }
        if ($insert) {
            redirect('ApplicationController/referenceno');
        }
    }


    public function applicationedit($appId)
    {


      

        $states = $query = $this->db->select('*')
            ->from('states')
            ->get();

        $countries =  $query = $this->db->select('*')
            ->from('countries')
            ->get();

        $cities =  $query = $this->db->select('*')
            ->from('cities')
            ->get();

        $view_data['states']  = $states->result();
        $view_data['countries']  = $countries->result();
        $view_data['cities']  = $cities->result();

        $application = $this->mcommon->specific_row('applications', array('id' => $appId));
        $applicationId = $application['id'];
        $userId = $application['user_id'];

        $view_data['academicYear'] = $this->mcommon->specific_row('accadamic_year', array('status' => 1));
        $view_data['userDetails']  = $this->mcommon->specific_row('users', array('user_id' => $userId));


        if ($applicationId) {
            $view_data['personalInfo']       =  $this->mcommon->specific_row('applications', array('id' => $applicationId));
            $view_data['parentInfo']        =  $this->mcommon->specific_row('parent_info', array('application_id' => $applicationId));
            $view_data['educationInfo']  =  $this->mcommon->records_all('education_work_experience', array('application_id' => $applicationId));
            $view_data['otherInfo']          =  $this->mcommon->specific_row('application_other_info', array('application_id' => $applicationId));
            $view_data['accomodation_info']  =  $this->mcommon->specific_row('accomodation_info', array('application_id' => $applicationId));
        }

        // echo '<pre>';
        // print_r($view_data['accomodation_info'] );
        // die();

        $query = $this->db->select('*')
            ->from('course')
            ->get();

        $view_data['courses']  = $query->result();



        $data = array(
            'title' => 'Application Form',
            'page' => 'Application Form',
            'academicYear' => '',
            'referenceNo' => '',
            'content' => $this->load->view('application/edit_application', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }




    public function updateApplication()
    {
        $input = $this->input->post();


        if ($_FILES['photo']['name']) {
            if (!is_dir('./attachments/application/')) {
                mkdir('./attachments/application/', 0777, true);
            }
            $upload_path = 'attachments/application/';
            $upload_path_table = base_url() . 'attachments/application/';
            $banner = $_FILES['photo']['name'];
            $expbanner = explode('.', $banner);
            $bannerexptype = $expbanner[1];
            $date = date('m/d/Yh:i:sa', time());
            $rand = rand(10000, 99999);
            $encname = $date . $rand;
            $bannername = md5($encname) . '.' . $bannerexptype;
            $bannerpath = $upload_path . $bannername;
            move_uploaded_file($_FILES["photo"]["tmp_name"], $bannerpath);
            $cover_pic = $upload_path_table . $bannername;
        } else {

            $cover_pic = isset($input['oldPhoto'])  ? $input['oldPhoto'] : '';
        }


        $personal_array = array(

            'academic_year       '  => isset($input['academicYear'])               &&  $input['academicYear']              ? $input['academicYear'] : 'dd',
            'course_id            '  => isset($input['course_id'])               &&  $input['course_id']              ? $input['course_id'] : 'dd',
            'application_fees     '  => isset($input['application_fee'])         &&  $input['application_fee']         ? $input['application_fee'] : '',
            'first_name           '  => isset($input['first_name'])              &&  $input['first_name']             ? $input['first_name'] : '',
            'middle_name          '  => isset($input['middle_name'])             &&  $input['middle_name']            ? $input['middle_name'] : '',
            'last_name            '  => isset($input['last_name'])               &&  $input['last_name']              ? $input['last_name'] : '',
            'image_url            '  => $cover_pic,
            'gender               '  => isset($input['gender'])                  &&  $input['gender']                 ? $input['gender'] : '',
            'dob                  '  => isset($input['dob'])                     &&  $input['dob']                    ? $input['dob'] : '',
            'nationality          '  => isset($input['nationality'])             &&  $input['nationality']    ? $input['nationality'] : '',
            'communication_address'  => isset($input['communication_address'])   &&  $input['communication_address']  ? $input['communication_address'] : '',
            'country_code         '  => isset($input['country_code'])            &&  $input['country_code']           ? $input['country_code'] : '',
            'cuntry         '  => isset($input['cuntry'])            &&  $input['cuntry']           ? $input['cuntry'] : '',
            'state         '  => isset($input['state'])            &&  $input['state']           ? $input['state'] : '',
            'city         '  => isset($input['city'])            &&  $input['city']           ? $input['city'] : '',
            'pincode         '  => isset($input['pincode'])            &&  $input['pincode']           ? $input['pincode'] : '',
            'landline             '  => isset($input['landline'])                &&  $input['landline']               ? $input['landline'] : '',
            'mobile               '  => isset($input['mobile'])                  &&  $input['mobile']                 ? $input['mobile'] : '',
            'email                '  => isset($input['email'])                   &&  $input['email']                  ? $input['email'] : '',
            'payment_status       '  =>  isset($input['payment_status_select'])              &&  $input['payment_status_select']                  ? $input['payment_status_select'] : '0',
            'application_no       '  =>  isset($input['application_no'])              &&  $input['application_no']                  ? $input['application_no'] : '0',
        );


        // echo '<pre>';
        // print_r($personal_array);
        // die();



        $personalUpdate = $this->mcommon->common_edit('applications', $personal_array, array('id' => $input['applicationId']));
        $parentId = $input['parentId'];

        $applicationId = $input['applicationId'];


        if ($_FILES['community_certificate']['name']) {
            if (!is_dir('./attachments/application/')) {
                mkdir('./attachments/application/', 0777, true);
            }
            $upload_path = 'attachments/application/';
            $upload_path_table = base_url() . 'attachments/application/';
            $banner = $_FILES['community_certificate']['name'];
            $expbanner = explode('.', $banner);
            $bannerexptype = $expbanner[1];
            $date = date('m/d/Yh:i:sa', time());
            $rand = rand(10000, 99999);
            $encname = $date . $rand;
            $bannername = md5($encname) . '.' . $bannerexptype;
            $bannerpath = $upload_path . $bannername;
           
            move_uploaded_file($_FILES["community_certificate"]["tmp_name"], $bannerpath);
            $community_certificate = $upload_path_table . $bannername;
          
        } else {
            $community_certificate =  isset($input['oldCommunity'])  ? $input['oldCommunity'] : '';
        }
      
        if ($_FILES['income_certificate']['name']) {
            if (!is_dir('./attachments/application/')) {
                mkdir('./attachments/application/', 0777, true);
            }
            $upload_path = 'attachments/application/';
            $upload_path_table = base_url() . 'attachments/application/';
            $banner = $_FILES['income_certificate']['name'];
            $expbanner = explode('.', $banner);
            $bannerexptype = $expbanner[1];
            $date = date('m/d/Yh:i:sa', time());
            $rand = rand(10000, 99999);
            $encname = $date . $rand;
            $bannername = md5($encname) . '.' . $bannerexptype;
            $bannerpath = $upload_path . $bannername;
            move_uploaded_file($_FILES["income_certificate"]["tmp_name"], $bannerpath);
            $income_certificate = $upload_path_table . $bannername;
        } else {
            $income_certificate =  isset($input['oldIncome'])  ? $input['oldIncome'] : '';
        }
// echo  $income_certificate  ;

        $certificates_Array = array(
            'community_certificate'     =>  $community_certificate,
            'income_certificate'        =>  $income_certificate,
            'apply_scholarship'     =>  isset($input['apply_scholarship'])  ? $input['apply_scholarship'] : '0',

        );
        // print_r( $certificates_Array);exit;

        $update = $this->mcommon->common_edit('applications', $certificates_Array, array('id' => $applicationId));




        $parent_array = array(
            'application_id'              => $applicationId,
            'father_name               '  => isset($input['father_name'])                 &&  $input['father_name']                ? $input['father_name'] : '',
            'father_occupation         '  => isset($input['father_occupation'])           &&  $input['father_occupation']          ? $input['father_occupation'] : '',
            'father_home_address       '  => isset($input['father_home_address'])         &&  $input['father_home_address']        ? $input['father_home_address'] : '',
            'father_home_country_code  '  => isset($input['father_countrycode'])    &&  $input['father_countrycode']   ? $input['father_countrycode'] : '',
            'father_home_landline      '  => isset($input['father_home_landline'])        &&  $input['father_home_landline']       ? $input['father_home_landline'] : '',
            'father_home_email         '  => isset($input['father_home_email'])           &&  $input['father_home_email']          ? $input['father_home_email'] : '',
            'father_home_mobile        '  => isset($input['father_home_mobile'])          &&  $input['father_home_mobile']         ? $input['father_home_mobile'] : '',
            'father_office_address     '  => isset($input['father_office_address'])       &&  $input['father_office_address']      ? $input['father_office_address'] : '',
            'father_office_country_code'  => isset($input['fatherofficecountrycode'])  &&  $input['fatherofficecountrycode'] ? $input['fatherofficecountrycode'] : '',
            'father_office_landline    '  => isset($input['father_office_landline'])      &&  $input['father_office_landline']     ? $input['father_office_landline'] : '',
            'father_office_mobile      '  => isset($input['father_office_mobile'])        &&  $input['father_office_mobile']       ? $input['father_office_mobile'] : '',
            'father_office_email       '  => isset($input['father_office_email'])         &&  $input['father_office_email']        ? $input['father_office_email'] : '',

            'mother_name               '  => isset($input['mother_name'])                 &&  $input['mother_name']                ? $input['mother_name'] : '',
            'mother_occupation         '  => isset($input['mother_occupation'])           &&  $input['mother_occupation']          ? $input['mother_occupation'] : '',
            'mother_home_addressss     '  => isset($input['mother_home_addressss'])       &&  $input['mother_home_addressss']      ? $input['mother_home_addressss'] : '',
            'addressCheckbox           '  => isset($input['addressCheckbox'])             ? '1' :   '0',
            'mother_home_country_code  '  => isset($input['motherhomecountrycode'])    &&  $input['motherhomecountrycode']   ? $input['motherhomecountrycode'] : '',
            'mother_home_land_line     '  => isset($input['mother_home_land_line'])       &&  $input['mother_home_land_line']      ? $input['mother_home_land_line'] : '',
            'mother_home_mobile        '  => isset($input['mother_home_mobile'])          &&  $input['mother_home_mobile']         ? $input['mother_home_mobile'] : '',
            'mother_home_email         '  => isset($input['mother_home_email'])           &&  $input['mother_home_email']          ? $input['mother_home_email'] : '',
            'mother_office_address     '  => isset($input['mother_office_address'])       &&  $input['mother_office_address']      ? $input['mother_office_address'] : '',
            'mother_office_country_code'  => isset($input['motherofficecountrycode'])  &&  $input['motherofficecountrycode'] ? $input['motherofficecountrycode'] : '',
            'mother_office_land_line   '  => isset($input['mother_office_land_line'])     &&  $input['mother_office_land_line']    ? $input['mother_office_land_line'] : '',
            'mother_office_mobile      '  => isset($input['mother_office_mobile'])        &&  $input['mother_office_mobile']       ? $input['mother_office_mobile'] : '',
            'mother_office_email       '  => isset($input['mother_office_email'])         &&  $input['mother_office_email']        ? $input['mother_office_email'] : '',
            'annual_income_rs          '  => isset($input['annual_income_rs'])            &&  $input['annual_income_rs']           ? $input['annual_income_rs'] : '',
            'annual_income_words       '  => isset($input['annual_income_words'])         &&  $input['annual_income_words']        ? $input['annual_income_words'] : '',
        );


        $update = $this->mcommon->common_edit('parent_info', $parent_array, array('id' => $parentId));





        // Third form


        foreach ($input['education_institution'] as $key => $val) {

            $education_institutionArray = array(
                'application_id'                =>  $applicationId,
                'education_institution'         =>  $val,
                'education_year'                =>  isset($input['education_year'])     &&  $input['education_year'][$key]      ? $input['education_year'][$key] : '',
                'education_subject'             =>  isset($input['education_subject'])  &&  $input['education_subject'][$key]   ? $input['education_subject'][$key] : '',
                'education_degree'              =>  isset($input['education_degree'])   &&  $input['education_degree'][$key]    ? $input['education_degree'][$key] : '',
                'education_marks'               =>  isset($input['education_marks'])    &&  $input['education_marks'][$key]     ? $input['education_marks'][$key] : '',
            );




            if ($input['educationInstitutionChildId'][$key]) {  //update
                $education_work_experience1 = $this->mcommon->common_edit('education_work_experience', $education_institutionArray, array('id' => $input['educationInstitutionChildId'][$key]));
            } else if ($val) {              //insert
                $education_work_experience1 = $this->mcommon->common_insert('education_work_experience', $education_institutionArray);
            }
        }

        foreach ($input['high_school_name'] as $key => $val) {

            $education_work_experienceArray = array(
                'application_id'                =>   $applicationId,
                'high_school_name'              =>   $val,
                'high_school_year'              =>   isset($input['high_school_year'])    &&  $input['high_school_year'][$key] ? $input['high_school_year'][$key] : '',
                'educational_boards'            =>   isset($input['educational_boards'])  &&  $input['educational_boards'][$key] ? $input['educational_boards'][$key] : '',
                'high_school_marks'             =>   isset($input['high_school_marks'])   &&  $input['high_school_marks'][$key] ? $input['high_school_marks'][$key] : '',
            );


            if ($input['highSchoolChild'][$key]) {  //update
                $education_work_experience2 = $this->mcommon->common_edit('education_work_experience', $education_work_experienceArray, array('id' => $input['highSchoolChild'][$key]));
            } else if ($val) {              //insert
                $education_work_experience2 = $this->mcommon->common_insert('education_work_experience', $education_work_experienceArray);
            }
        }

        foreach ($input['higher_secondary_name'] as $key => $val) {


            $education_work_experienceArray1 = array(
                'application_id'                =>   $applicationId,
                'higher_secondary_name'              =>   $val,
                'higher_secondary_year'              =>   isset($input['higher_secondary_year'])    &&  $input['higher_secondary_year'][$key] ? $input['higher_secondary_year'][$key] : '',
                'higher_school_education_boards'     =>   isset($input['higher_school_education_boards'])  &&  $input['higher_school_education_boards'][$key] ? $input['higher_school_education_boards'][$key] : '',
                'higher_secondary_marks'             =>   isset($input['higher_secondary_marks'])   &&  $input['higher_secondary_marks'][$key] ? $input['higher_secondary_marks'][$key] : '',
            );

            if ($input['highSecondaryChild'][$key]) {  //update
                $education_work_experience5 = $this->mcommon->common_edit('education_work_experience', $education_work_experienceArray1, array('id' => $input['highSecondaryChild'][$key]));
            } else if ($val) {              //insert
                $education_work_experience5 = $this->mcommon->common_insert('education_work_experience', $education_work_experienceArray1);
            }
        }

        foreach ($input['other_education_institution'] as $key => $val) {

            $other_education_institutionArray = array(
                'application_id'                 =>   $applicationId,
                'other_education_institution'    =>   $val,
                'other_education_year'           =>   isset($input['other_education_year'])         && $input['other_education_year'][$key]        ? $input['other_education_year'][$key] : '',
                'other_education_subject'        =>   isset($input['other_education_subject'])      && $input['other_education_subject'][$key]     ? $input['other_education_subject'][$key] : '',
                'other_education_certificate'    =>   isset($input['other_education_certificate'])  && $input['other_education_certificate'][$key] ? $input['other_education_certificate'][$key] : '',
                'other_education_award'          =>   isset($input['other_education_award'])        && $input['other_education_award'][$key]       ? $input['other_education_award'][$key] : '',
            );

            if ($input['otherEducationChild'][$key]) {  //update
                $education_work_experience3 = $this->mcommon->common_edit('education_work_experience', $other_education_institutionArray, array('id' => $input['otherEducationChild'][$key]));
            } else if ($val) {              //insert
                $education_work_experience3 = $this->mcommon->common_insert('education_work_experience', $other_education_institutionArray);
            }
        }

        foreach ($input['worked_organisation'] as $key => $val) {

            $worked_organisation = array(
                'application_id'                 =>   $applicationId,
                'worked_organisation'            =>   $val,
                'worked_year'                    =>   isset($input['worked_year']) && $input['worked_year'][$key]             ? $input['worked_year'][$key] : '',
                'worked_title'                   =>   isset($input['worked_title']) && $input['worked_title'][$key]            ? $input['worked_title'][$key] : '',
                'worked_responsibilities'        =>   isset($input['worked_responsibilities']) && $input['worked_responsibilities'][$key] ? $input['worked_responsibilities'][$key] : '',
            );

            if ($input['workedChild'][$key]) {  //update
                $education_work_experience4 = $this->mcommon->common_edit('education_work_experience', $worked_organisation, array('id' => $input['workedChild'][$key]));
            } else if ($val) {              //insert
                $education_work_experience4 = $this->mcommon->common_insert('education_work_experience', $worked_organisation);
            }
        }


        $application_update = array(
            'academic_awards'        => isset($input['academic_awards'])         && $input['academic_awards']         ? $input['academic_awards'] : '',
            'extracurricular'        => isset($input['extracurricular'])         && $input['extracurricular']         ? $input['extracurricular'] : '',

        );



        $update = $this->mcommon->common_edit('applications', $application_update, array('id' => $applicationId));

        $otherId       = $input['otherId'];


        $otherInfo_array = array(

            'application_id'                =>   $applicationId,
            'media_professionals'           => isset($input['media_professionals'])   &&    $input['media_professionals'] ? $input['media_professionals'] : '',
            'broadcast_podcast'             => isset($input['broadcast_podcast'])     &&    $input['broadcast_podcast']   ? $input['broadcast_podcast']   : '',
            'journalist_reason'             => isset($input['journalist_reason'])     &&    $input['journalist_reason']   ? $input['journalist_reason']   : '',
        );

        // echo '<pre>';
        // print_r($otherInfo_array);
        // die();


        if ($otherId) {

            $update = $this->mcommon->common_edit('application_other_info', $otherInfo_array, array('id' => $otherId));
        } else {              //insert

            $otherInfoInsert = $this->mcommon->common_insert('application_other_info', $otherInfo_array);
        }




        //fifth form

        $accomodationId     = $input['accomodationId'];

        // if ($_FILES['community_certificate']['name']) {
        //     if (!is_dir('./attachments/application/')) {
        //         mkdir('./attachments/application/', 0777, true);
        //     }
        //     $upload_path = 'attachments/application/';
        //     $upload_path_table = base_url() . 'attachments/application/';
        //     $banner = $_FILES['community_certificate']['name'];
        //     $expbanner = explode('.', $banner);
        //     $bannerexptype = $expbanner[1];
        //     $date = date('m/d/Yh:i:sa', time());
        //     $rand = rand(10000, 99999);
        //     $encname = $date . $rand;
        //     $bannername = md5($encname) . '.' . $bannerexptype;
        //     $bannerpath = $upload_path . $bannername;
        //     move_uploaded_file($_FILES["community_certificate"]["tmp_name"], $bannerpath);

        //     $community_certificate = $upload_path_table . $bannername;

        //     $updateArray = array(
        //         'community_certificate' => $community_certificate
        //     );
        //     $update = $this->mcommon->common_edit('applications', $updateArray, array('id' => $applicationId));
        // }



        $finalStatus = $input['payment_mode'] == 1 ? 1 : 0;



        $accomodationInfoArray = array(
            'application_id'                =>  $applicationId,
            'residential_accommodation'     =>  isset($input['residential_accommodation'])          ?   $input['residential_accommodation'] : '',
            'application_fee_checked'       =>  isset($input['application_fee_checked'])            ?   $input['application_fee_checked'] : '',
            'payment_mode'                  =>  isset($input['payment_mode'])                       ?   $input['payment_mode']   : '',
            'self_certification'            =>  isset($input['self_certification'])                 ?   1   : '',
            'tab_status'                    =>  isset($input['tab_status'])                         ?   $input['tab_status']      : '0',
        );


        //             echo '<pre>';
        // print_r($accomodationInfoArray);
        // die();

        if ($accomodationId) {  //update
            $update = $this->mcommon->common_edit('accomodation_info', $accomodationInfoArray, array('id' => $accomodationId));
        }else{
           $this->mcommon->common_insert('accomodation_info', $accomodationInfoArray, array('id' => $accomodationId));
        }



        $status = $this->mcommon->specific_row_value('applications', array('id' => $applicationId), 'payment_status');


        //               echo '<pre>';
        // print_r($status);
        // die();

        if ($personalUpdate) {
            $this->session->set_flashdata('alert_success', 'Application Updated successfully!');

            if ($status == 0) {
                redirect('ApplicationController/draftformdetails');
            } elseif ($status == 1) {
                redirect('ApplicationController/pendingformdetails');
            } else {
                redirect('ApplicationController/completedformdetails');
            }
        }
    }















    public function completelist($userId)
    {

        $view_data['academicYear'] = $this->mcommon->specific_row('accadamic_year', array('status' => 1));
        $view_data['userDetails']  = $this->mcommon->specific_row('users', array('user_id' => $userId));
        $applicationId = $this->mcommon->specific_row_value('applications', array('user_id' => $userId), 'id');

        if ($applicationId) {
            $view_data['personalInfo']       =  $this->mcommon->specific_row('applications', array('id' => $applicationId));
            $view_data['parentInfo']        =  $this->mcommon->specific_row('parent_info', array('application_id' => $applicationId));
            $view_data['educationInfo']  =  $this->mcommon->records_all('education_work_experience', array('application_id' => $applicationId));
            $view_data['otherInfo']          =  $this->mcommon->specific_row('application_other_info', array('application_id' => $applicationId));
            $view_data['accomodation_info']  =  $this->mcommon->specific_row('accomodation_info', array('application_id' => $applicationId));
        }

        // echo '<pre>';
        // print_r($view_data['userDetails']['reference_no']);
        // die();
        // echo '<pre>';
        // print_r($view_data['personalInfo']);
        // print_r($view_data['parentInfo']  );
        // print_r( $view_data['educationInfo'] );
        // print_r(  $view_data['otherInfo'] );
        // print_r( $view_data['accomodation_info']);

        $states = $query = $this->db->select('*')
            ->from('countries')
            ->get();

        $countries =  $query = $this->db->select('*')
            ->from('states')
            ->get();

        $cities =  $query = $this->db->select('*')
            ->from('cities')
            ->get();

        $view_data['states']  = $states->result();
        $view_data['countries']  = $countries->result();
        $view_data['cities']  = $cities->result();


        $query = $this->db->select('*')
            ->from('course')
            ->get();



        $view_data['courses']  = $query->result();


        $data = array(
            'title' => 'Application Form',
            'page' => 'Application Form',
            'academicYear' => $view_data['academicYear'],
            'referenceNo' => $view_data['userDetails']['reference_no'],
            'content' => $this->load->view('application/application_form', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }
    public function shortlist1($userId)
    {

        $view_data['academicYear'] = $this->mcommon->specific_row('accadamic_year', array('status' => 1));
        $view_data['userDetails']  = $this->mcommon->specific_row('users', array('user_id' => $userId));
        $applicationId = $this->mcommon->specific_row_value('applications', array('user_id' => $userId), 'id');

        if ($applicationId) {
            $view_data['personalInfo']       =  $this->mcommon->specific_row('applications', array('id' => $applicationId));
            $view_data['parentInfo']        =  $this->mcommon->specific_row('parent_info', array('application_id' => $applicationId));
            $view_data['educationInfo']  =  $this->mcommon->records_all('education_work_experience', array('application_id' => $applicationId));
            $view_data['otherInfo']          =  $this->mcommon->specific_row('application_other_info', array('application_id' => $applicationId));
            $view_data['accomodation_info']  =  $this->mcommon->specific_row('accomodation_info', array('application_id' => $applicationId));
        }

        // echo '<pre>';
        // print_r($view_data['userDetails']['reference_no']);
        // die();
        // echo '<pre>';
        // print_r($view_data['personalInfo']);
        // print_r($view_data['parentInfo']  );
        // print_r( $view_data['educationInfo'] );
        // print_r(  $view_data['otherInfo'] );
        // print_r( $view_data['accomodation_info']);



        $query = $this->db->select('*')
            ->from('course')
            ->get();

        $view_data['courses']  = $query->result();


        $data = array(
            'title' => 'Application Form',
            'page' => 'Application Form',
            'academicYear' => $view_data['academicYear'],
            'referenceNo' => $view_data['userDetails']['reference_no'],
            'content' => $this->load->view('application/application_form', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }




    //AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

    public function addApplication()
    {

        $userId = $this->session->userdata('user_id');

        $input = $this->input->post();


        // echo '<pre>';
        // print_r($input);
        // die();

        if ($_FILES['photo']['name']) {
            if (!is_dir('./attachments/application/')) {
                mkdir('./attachments/application/', 0777, true);
            }
            $upload_path = 'attachments/application/';
            $upload_path_table = base_url() . 'attachments/application/';
            $banner = $_FILES['photo']['name'];
            $expbanner = explode('.', $banner);
            $bannerexptype = $expbanner[1];
            $date = date('m/d/Yh:i:sa', time());
            $rand = rand(10000, 99999);
            $encname = $date . $rand;
            $bannername = md5($encname) . '.' . $bannerexptype;
            $bannerpath = $upload_path . $bannername;
            move_uploaded_file($_FILES["photo"]["tmp_name"], $bannerpath);
            $cover_pic = $upload_path_table . $bannername;
        } else {

            $cover_pic = isset($input['oldPhoto'])  ? $input['oldPhoto'] : '';
        }


        $personal_array = array(

            'user_id             '  => $userId,
            'academic_year            '  => isset($input['academicYear'])               &&  $input['academicYear']              ? $input['academicYear'] : 'dd',
            'course_id            '  => isset($input['course_id'])               &&  $input['course_id']              ? $input['course_id'] : 'dd',
            'application_fees     '  => isset($input['application_fee'])         &&  $input['application_fee']         ? $input['application_fee'] : '',
            'first_name           '  => isset($input['first_name'])              &&  $input['first_name']             ? $input['first_name'] : '',
            'middle_name          '  => isset($input['middle_name'])             &&  $input['middle_name']            ? $input['middle_name'] : '',
            'last_name            '  => isset($input['last_name'])               &&  $input['last_name']              ? $input['last_name'] : '',
            'image_url            '  => $cover_pic,
            'gender               '  => isset($input['gender'])                  &&  $input['gender']                 ? $input['gender'] : '',
            'dob                  '  => isset($input['dob'])                     &&  $input['dob']                    ? $input['dob'] : '',
            'communication_address'  => isset($input['communication_address'])   &&  $input['communication_address']  ? $input['communication_address'] : '',
            'country_code         '  => isset($input['country_code'])            &&  $input['country_code']           ? $input['country_code'] : '',
            'landline             '  => isset($input['landline'])                &&  $input['landline']               ? $input['landline'] : '',
            'mobile               '  => isset($input['mobile'])                  &&  $input['mobile']                 ? $input['mobile'] : '',
            'email                '  => isset($input['email'])                   &&  $input['email']                  ? $input['email'] : '',
            'status               '  => isset($input['draft'])                   &&  $input['draft']                  ? $input['draft'] : '0',
            'tab_status           '  => isset($input['tab_status'])              &&  $input['tab_status']                  ? $input['tab_status'] : '0',
        );
        //  echo '<pre>';
        //         print_r($personal_array);
        //         die();

        if ($input['applicationId']) {  //update

            $update = $this->mcommon->common_edit('applications', $personal_array, array('id' => $input['applicationId']));

            if ($update) {
                $this->session->set_flashdata('alert_success', 'Personal Info Updated successfully!');
                redirect($_SERVER['HTTP_REFERER']);
                // redirect('ApplicationController');
            }
        } else {              //insert

            $personalInsert = $this->mcommon->common_insert('applications', $personal_array);

            if ($personalInsert) {
                $this->session->set_flashdata('alert_success', 'Personal Info Saved successfully!');
                redirect($_SERVER['HTTP_REFERER']);
                // redirect('ApplicationController');
            }
        }



        $this->session->set_flashdata('alert_danger', 'Something went wrong');
    }


    public function addApplication2()
    {

        $userId = $this->session->userdata('user_id');

        $input = $this->input->post();

        // echo '<pre>';
        // print_r($input);
        // die();

        $parentId = $input['parentId'];

        $applicationId = $input['applicationId'];


        if ($_FILES['community_certificate']['name']) {
            if (!is_dir('./attachments/application/')) {
                mkdir('./attachments/application/', 0777, true);
            }
            $upload_path = 'attachments/application/';
            $upload_path_table = base_url() . 'attachments/application/';
            $banner = $_FILES['community_certificate']['name'];
            $expbanner = explode('.', $banner);
            $bannerexptype = $expbanner[1];
            $date = date('m/d/Yh:i:sa', time());
            $rand = rand(10000, 99999);
            $encname = $date . $rand;
            $bannername = md5($encname) . '.' . $bannerexptype;
            $bannerpath = $upload_path . $bannername;
            move_uploaded_file($_FILES["community_certificate"]["tmp_name"], $bannerpath);
            $community_certificate = $upload_path_table . $bannername;
        } else {
            $community_certificate =  isset($input['oldCommunity'])  ? $input['oldCommunity'] : '';
        }

        if ($_FILES['income_certificate']['name']) {
            if (!is_dir('./attachments/application/')) {
                mkdir('./attachments/application/', 0777, true);
            }
            $upload_path = 'attachments/application/';
            $upload_path_table = base_url() . 'attachments/application/';
            $banner = $_FILES['income_certificate']['name'];
            $expbanner = explode('.', $banner);
            $bannerexptype = $expbanner[1];
            $date = date('m/d/Yh:i:sa', time());
            $rand = rand(10000, 99999);
            $encname = $date . $rand;
            $bannername = md5($encname) . '.' . $bannerexptype;
            $bannerpath = $upload_path . $bannername;
            move_uploaded_file($_FILES["income_certificate"]["tmp_name"], $bannerpath);
            $income_certificate = $upload_path_table . $bannername;
        } else {
            $income_certificate =  isset($input['oldIncome'])  ? $input['oldIncome'] : '';
        }


        $certificates_Array = array(
            'community_certificate'     =>  $community_certificate,
            'income_certificate'        =>  $income_certificate,
            'apply_scholarship'     =>  isset($input['apply_scholarship'])  ? $input['apply_scholarship'] : '0',

        );

        $update = $this->mcommon->common_edit('applications', $certificates_Array, array('id' => $applicationId));




        $parent_array = array(
            'application_id'              => $applicationId,
            'father_name               '  => isset($input['father_name'])                 &&  $input['father_name']                ? $input['father_name'] : '',
            'father_occupation         '  => isset($input['father_occupation'])           &&  $input['father_occupation']          ? $input['father_occupation'] : '',
            'father_home_address       '  => isset($input['father_home_address'])         &&  $input['father_home_address']        ? $input['father_home_address'] : '',
            'father_home_country_code  '  => isset($input['father_home_country_code'])    &&  $input['father_home_country_code']   ? $input['father_home_country_code'] : '',
            'father_home_landline      '  => isset($input['father_home_landline'])        &&  $input['father_home_landline']       ? $input['father_home_landline'] : '',
            'father_home_email         '  => isset($input['father_home_email'])           &&  $input['father_home_email']          ? $input['father_home_email'] : '',
            'father_home_mobile        '  => isset($input['father_home_mobile'])          &&  $input['father_home_mobile']         ? $input['father_home_mobile'] : '',
            'father_office_address     '  => isset($input['father_office_address'])       &&  $input['father_office_address']      ? $input['father_office_address'] : '',
            'father_office_country_code'  => isset($input['father_office_country_code'])  &&  $input['father_office_country_code'] ? $input['father_office_country_code'] : '',
            'father_office_landline    '  => isset($input['father_office_landline'])      &&  $input['father_office_landline']     ? $input['father_office_landline'] : '',
            'father_office_mobile      '  => isset($input['father_office_mobile'])        &&  $input['father_office_mobile']       ? $input['father_office_mobile'] : '',
            'father_office_email       '  => isset($input['father_office_email'])         &&  $input['father_office_email']        ? $input['father_office_email'] : '',

            'mother_name               '  => isset($input['mother_name'])                 &&  $input['mother_name']                ? $input['mother_name'] : '',
            'mother_occupation         '  => isset($input['mother_occupation'])           &&  $input['mother_occupation']          ? $input['mother_occupation'] : '',
            'mother_home_addressss     '  => isset($input['mother_home_addressss'])       &&  $input['mother_home_addressss']      ? $input['mother_home_addressss'] : '',
            'addressCheckbox           '  => isset($input['addressCheckbox'])             ? '1' :   '0',
            'mother_home_country_code  '  => isset($input['mother_home_country_code'])    &&  $input['mother_home_country_code']   ? $input['mother_home_country_code'] : '',
            'mother_home_land_line     '  => isset($input['mother_home_land_line'])       &&  $input['mother_home_land_line']      ? $input['mother_home_land_line'] : '',
            'mother_home_mobile        '  => isset($input['mother_home_mobile'])          &&  $input['mother_home_mobile']         ? $input['mother_home_mobile'] : '',
            'mother_home_email         '  => isset($input['mother_home_email'])           &&  $input['mother_home_email']          ? $input['mother_home_email'] : '',
            'mother_office_address     '  => isset($input['mother_office_address'])       &&  $input['mother_office_address']      ? $input['mother_office_address'] : '',
            'mother_office_country_code'  => isset($input['mother_office_country_code'])  &&  $input['mother_office_country_code'] ? $input['mother_office_country_code'] : '',
            'mother_office_land_line   '  => isset($input['mother_office_land_line'])     &&  $input['mother_office_land_line']    ? $input['mother_office_land_line'] : '',
            'mother_office_mobile      '  => isset($input['mother_office_mobile'])        &&  $input['mother_office_mobile']       ? $input['mother_office_mobile'] : '',
            'mother_office_email       '  => isset($input['mother_office_email'])         &&  $input['mother_office_email']        ? $input['mother_office_email'] : '',
            'annual_income_rs          '  => isset($input['annual_income_rs'])            &&  $input['annual_income_rs']           ? $input['annual_income_rs'] : '',
            'annual_income_words       '  => isset($input['annual_income_words'])         &&  $input['annual_income_words']        ? $input['annual_income_words'] : '',
            'tab_status                '  => isset($input['tab_status'])                  &&  $input['tab_status']                 ? $input['tab_status'] : '0',
        );



        // echo '<pre>';
        // print_r($parent_array);
        // die();

        if ($parentId) {  //update

            $update = $this->mcommon->common_edit('parent_info', $parent_array, array('id' => $parentId));

            if ($update) {
                $this->session->set_flashdata('alert_success', 'Parent Info Updated successfully!');
                // redirect('ApplicationController');
                redirect($_SERVER['HTTP_REFERER']);
            }
        } else {              //insert

            $parentInsert = $this->mcommon->common_insert('parent_info', $parent_array);

            if ($parentInsert) {
                $this->session->set_flashdata('alert_success', 'Parent Info Saved successfully!');
                // redirect('ApplicationController');
                redirect($_SERVER['HTTP_REFERER']);
            }
        }



        $this->session->set_flashdata('alert_danger', 'Something went wrong');
    }



    public function addApplication3()
    {

        $userId = $this->session->userdata('user_id');

        $input = $this->input->post();

        // echo '<pre>';
        // print_r($input);
        // die();     


        $applicationId = $input['applicationId'];


        foreach ($input['education_institution'] as $key => $val) {

            $education_institutionArray = array(
                'application_id'                =>  $applicationId,
                'education_institution'         =>  $val,
                'education_year'                =>  isset($input['education_year'])     &&  $input['education_year'][$key]      ? $input['education_year'][$key] : '',
                'education_subject'             =>  isset($input['education_subject'])  &&  $input['education_subject'][$key]   ? $input['education_subject'][$key] : '',
                'education_degree'              =>  isset($input['education_degree'])   &&  $input['education_degree'][$key]    ? $input['education_degree'][$key] : '',
                'education_marks'               =>  isset($input['education_marks'])    &&  $input['education_marks'][$key]     ? $input['education_marks'][$key] : '',
            );


            if ($input['educationInstitutionChildId'][$key]) {  //update
                $education_work_experience1 = $this->mcommon->common_edit('education_work_experience', $education_institutionArray, array('id' => $input['educationInstitutionChildId'][$key]));
            } else {              //insert
                $education_work_experience1 = $this->mcommon->common_insert('education_work_experience', $education_institutionArray);
            }
        }

        foreach ($input['high_school_name'] as $key => $val) {

            $education_work_experienceArray = array(
                'application_id'                =>   $applicationId,
                'high_school_name'              =>   $val,
                'high_school_year'              =>   isset($input['high_school_year'])    &&  $input['high_school_year'][$key] ? $input['high_school_year'][$key] : '',
                'educational_boards'            =>   isset($input['educational_boards'])  &&  $input['educational_boards'][$key] ? $input['educational_boards'][$key] : '',
                'high_school_marks'             =>   isset($input['high_school_marks'])   &&  $input['high_school_marks'][$key] ? $input['high_school_marks'][$key] : '',
            );




            if ($input['highSchoolChild'][$key]) {  //update
                $education_work_experience2 = $this->mcommon->common_edit('education_work_experience', $education_work_experienceArray, array('id' => $input['highSchoolChild'][$key]));
            } else {              //insert
                $education_work_experience2 = $this->mcommon->common_insert('education_work_experience', $education_work_experienceArray);
            }
        }

        foreach ($input['other_education_institution'] as $key => $val) {

            $other_education_institutionArray = array(
                'application_id'                 =>   $applicationId,
                'other_education_institution'    =>   $val,
                'other_education_year'           =>   isset($input['other_education_year'])         && $input['other_education_year'][$key]        ? $input['other_education_year'][$key] : '',
                'other_education_subject'        =>   isset($input['other_education_subject'])      && $input['other_education_subject'][$key]     ? $input['other_education_subject'][$key] : '',
                'other_education_certificate'    =>   isset($input['other_education_certificate'])  && $input['other_education_certificate'][$key] ? $input['other_education_certificate'][$key] : '',
                'other_education_award'          =>   isset($input['other_education_award'])        && $input['other_education_award'][$key]       ? $input['other_education_award'][$key] : '',
            );

            if ($input['otherEducationChild'][$key]) {  //update
                $education_work_experience3 = $this->mcommon->common_edit('education_work_experience', $other_education_institutionArray, array('id' => $input['otherEducationChild'][$key]));
            } else {              //insert
                $education_work_experience3 = $this->mcommon->common_insert('education_work_experience', $other_education_institutionArray);
            }
        }

        foreach ($input['worked_organisation'] as $key => $val) {

            $worked_organisation = array(
                'application_id'                 =>   $applicationId,
                'worked_organisation'            =>   $val,
                'worked_year'                    =>   isset($input['other_education_award']) && $input['worked_year'][$key]             ? $input['worked_year'][$key] : '',
                'worked_title'                   =>   isset($input['other_education_award']) && $input['worked_title'][$key]            ? $input['worked_title'][$key] : '',
                'worked_responsibilities'        =>   isset($input['other_education_award']) && $input['worked_responsibilities'][$key] ? $input['worked_responsibilities'][$key] : '',
            );


            if ($input['workedChild'][$key]) {  //update
                $education_work_experience4 = $this->mcommon->common_edit('education_work_experience', $worked_organisation, array('id' => $input['workedChild'][$key]));
            } else {              //insert
                $education_work_experience4 = $this->mcommon->common_insert('education_work_experience', $worked_organisation);
            }
        }


        $application_update = array(
            'academic_awards'        => isset($input['academic_awards'])         && $input['academic_awards']         ? $input['academic_awards'] : '',
            'extracurricular'        => isset($input['extracurricular'])         && $input['extracurricular']         ? $input['extracurricular'] : '',

        );

        $update = $this->mcommon->common_edit('applications', $application_update, array('id' => $applicationId));


        $tabStatusArray = array(
            'tab_status'             => isset($input['tab_status']) &&  $input['tab_status'] ? $input['tab_status'] : '0',
        );
        $education_work_experience4 = $this->mcommon->common_edit('education_work_experience', $tabStatusArray, array('application_id' => $applicationId));




        if ($education_work_experience1 || $education_work_experience2 || $education_work_experience3 || $education_work_experience4) {

            $this->session->set_flashdata('alert_success', 'Education Info Saved successfully!');
            redirect('ApplicationController');
        } else {

            $this->session->set_flashdata('alert_danger', 'Something went wrong');
        }
    }






    public function addApplication4()
    {

        $userId = $this->session->userdata('user_id');

        $input = $this->input->post();

        //        echo '<pre>';
        // print_r($input);
        // die(); 

        $applicationId = $input['applicationId'];
        $otherId       = $input['otherId'];


        $otherInfo_array = array(

            'application_id'                =>   $applicationId,
            'media_professionals'           => isset($input['media_professionals'])   &&    $input['media_professionals'] ? $input['media_professionals'] : '',
            'broadcast_podcast'             => isset($input['broadcast_podcast'])     &&    $input['broadcast_podcast']   ? $input['broadcast_podcast']   : '',
            'journalist_reason'             => isset($input['journalist_reason'])     &&    $input['journalist_reason']   ? $input['journalist_reason']   : '',
            'tab_status'                    => isset($input['tab_status'])            &&  $input['tab_status']            ? $input['tab_status']          : '0',

        );

        // echo '<pre>';
        // print_r($cover_pic);
        // die();


        if ($otherId) {  //update

            $update = $this->mcommon->common_edit('application_other_info', $otherInfo_array, array('id' => $otherId));

            if ($update) {
                $this->session->set_flashdata('alert_success', 'Other Info Updated successfully!');
                // redirect('ApplicationController');
                redirect($_SERVER['HTTP_REFERER']);
            }
        } else {              //insert

            $otherInfoInsert = $this->mcommon->common_insert('application_other_info', $otherInfo_array);

            if ($otherInfoInsert) {
                $this->session->set_flashdata('alert_success', 'Other Info Saved successfully!');
                // redirect('ApplicationController');
                redirect($_SERVER['HTTP_REFERER']);
            }
        }



        $this->session->set_flashdata('alert_danger', 'Something went wrong');
    }



    public function addApplication5()
    {

        $userId = $this->session->userdata('user_id');

        $input = $this->input->post();


        $applicationId      = $input['applicationId'];
        $accomodationId     = $input['accomodationId'];




        if ($_FILES['community_certificate']['name']) {
            if (!is_dir('./attachments/application/')) {
                mkdir('./attachments/application/', 0777, true);
            }
            $upload_path = 'attachments/application/';
            $upload_path_table = base_url() . 'attachments/application/';
            $banner = $_FILES['community_certificate']['name'];
            $expbanner = explode('.', $banner);
            $bannerexptype = $expbanner[1];
            $date = date('m/d/Yh:i:sa', time());
            $rand = rand(10000, 99999);
            $encname = $date . $rand;
            $bannername = md5($encname) . '.' . $bannerexptype;
            $bannerpath = $upload_path . $bannername;
            move_uploaded_file($_FILES["community_certificate"]["tmp_name"], $bannerpath);

            $community_certificate = $upload_path_table . $bannername;

            $updateArray = array(
                'community_certificate' => $community_certificate
            );
            $update = $this->mcommon->common_edit('applications', $updateArray, array('id' => $applicationId));
        }



        $updateArray = array(
            'status'    =>  1,
        );

        $update = $this->mcommon->common_edit('applications', $updateArray, array('id' => $applicationId));




        $accomodationInfoArray = array(
            'application_id'                =>  $applicationId,
            'residential_accommodation'     =>  isset($input['residential_accommodation'])          ?   $input['residential_accommodation'] : '',
            'application_fee_checked'       =>  isset($input['application_fee_checked'])            ?   $input['application_fee_checked'] : '',
            'payment_mode'                  =>  isset($input['payment_mode'])                       ?   $input['payment_mode']   : '',
            'self_certification'            =>  isset($input['self_certification'])                 ?   1   : '',
            'tab_status'                    =>  isset($input['tab_status'])                         ?   $input['tab_status']      : '0',

        );


        // echo '<pre>';
        // print_r($cover_pic);
        // die();



        if ($accomodationId) {  //update

            $update = $this->mcommon->common_edit('accomodation_info', $accomodationInfoArray, array('id' => $accomodationId));

            if ($update) {
                $this->session->set_flashdata('alert_success', 'Accomodation Info Updated successfully!');
                // redirect('ApplicationController');
                redirect($_SERVER['HTTP_REFERER']);
            }
        } else {              //insert

            $otherInfoInsert = $this->mcommon->common_insert('accomodation_info', $accomodationInfoArray);

            if ($otherInfoInsert) {
                $this->session->set_flashdata('alert_success', 'Accomodation Info Saved successfully!');
                // redirect('ApplicationController');
                redirect($_SERVER['HTTP_REFERER']);
            }
        }

        $this->session->set_flashdata('alert_danger', 'Something went wrong');
    }
    public function paymenthistry()
    {
        if ($this->input->post()) {
            // $name = $this->input->post('name');
            $bankname = $this->input->post('bankname');
            $transaction = $this->input->post('transaction');
            $date = $this->input->post('date');
            $amount = $this->input->post('amount');
            $appid =  $this->input->post('appid');
            $userid =  $this->input->post('userid');
            $paymentmode = $this->input->post('paymentmode');


            $insert_array = array(
                'user_id' => $userid,
                'application_id' => $appid,
                'payment_status' => $paymentmode,
                'payment_response' => '',
                // 'user_name' => $name,
                'transaction_no' => $transaction,
                'payment_date' => $date,
                'amount' => $amount,
                'bankname' => $bankname,
            );

            $insert = $this->mcommon->common_insert('payment_history', $insert_array);
            if ($insert) {
                $aplicatin = array(
                    'status'  => '1',
                );
                $update = $this->mcommon->common_edit('applications', $aplicatin, array('id' => $appid));
                $this->session->set_flashdata('alert_success', 'successfully inserted');
                redirect('ApplicationController/pendingformdetails');
            }
        }
    }

    public function mailSendOnPendingList($applicationId)
    {

        $this->db->select('*, applications.id as appid, course.course_name as course_name, applications.status as apstatus');
        $this->db->from('applications');
        $this->db->join('course', 'course.id = applications.course_id', 'left');
        $this->db->join('users', 'users.user_id = applications.user_id');
        $this->db->join('accomodation_info as ai', 'ai.application_id = applications.id');
        $this->db->where('applications.id', $applicationId);
        $query  = $this->db->get();
        $applicationdatas  = $query->result();

        $view_data['name'] = $applicationdatas[0]->first_name;
        $view_data['course_id'] = $applicationdatas[0]->course_id;
        $view_data['refno'] = $applicationdatas[0]->reference_no;
        $view_data['userId'] = $applicationdatas[0]->user_id;

        if ($view_data['course_id'] == 1) {

            $subject = 'Application Form – ACJ Postgraduate Diploma in Integrated Multimedia 
            Journalism';

        } else if ($view_data['course_id'] == 2) {

            $subject =  'Application Form – ACJ-Bloomberg Postgraduate Diploma in Business and 
            Financial Multimedia Journalism';

        } else {

            $subject = 'Application Form – ACJ Postgraduate Diploma Programmes';

        }

        $to_email = $applicationdatas[0]->email;

        $mailtemplate = $this->load->view('acknowledgement/without_payment', $view_data, true);

        $this->load->library('email');
        $this->email->set_newline("\r\n");
        $from_email_address = 'acjadmissions@asianmedia.org.in';
        $from_email_name = 'Asian College of Journalism';
        $this->email->from($from_email_address, $from_email_name);
        $this->email->to($to_email);
        $this->email->subject($subject);
        $this->email->message($mailtemplate);


        //     $application_details  = $this->mcommon->specific_row('applications', array('id' => $appid));
        //     $to_email = $application_details['email'];
        //     $view_data['name'] = $application_details['first_name'].' '.$application_details['last_name'];
        //     $payment_status = $application_details['payment_status'];

        //    if($payment_status == 0){
        //     $teplate_for = 6;       //content for draft
        //    }else{
        //     $teplate_for = 0;       //content for pending
        //    }

        //     $view_data['content'] = $this->load->view('acknowledgement/without_payment', $view_data, true);


        // echo '<pre>';
        // print_r($view_data['content']);
        // die();

        // $mailtemplate = $this->load->view('emailTemplateMaster/mailtemp', $view_data, true);

        //         $this->load->library('email');
        //         $this->email->set_newline("\r\n");
        //         $from_email_address='acjadmissions@asianmedia.org.in';
        //         $from_email_name='Asian College of Journalism';
        //         $email_subject='Asian College of Journalism';
        //         // $email_message=$email_array['message'];
        //         $this->email->from($from_email_address, $from_email_name);
        //         $this->email->to($to_email);
        //         $this->email->subject($view_data['content']['email_subject']);
        //         $this->email->message($mailtemplate);
        // $result = $this->email->send();



        if ($this->email->send()) {
            $this->session->set_flashdata('alert_success', 'successfully Mail Send');
            redirect($_SERVER['HTTP_REFERER']);
        } else {
            echo $this->email->print_debugger();
            exit;
            $this->session->set_flashdata('alert_danger', 'something Error');
            redirect($_SERVER['HTTP_REFERER']);
        }
    }



    public function mailSendOnShortlist($appid)
    {
        $application_details  = $this->mcommon->specific_row('applications', array('id' => $appid));


        $to_email = $application_details['email'];


        $view_data['name'] = $application_details['first_name'] . ' ' . $application_details['last_name'];


        $view_data['content'] = $this->mcommon->specific_row('mail_template', array('template_for' => 2));

        // echo '<pre>';
        // print_r($view_data['content']);
        // die();

        $mailtemplate = $this->load->view('emailTemplateMaster/mailtemp', $view_data, true);

        $this->load->library('email');
        $this->email->set_newline("\r\n");
        $from_email_address = 'acjadmissions@asianmedia.org.in';
        $from_email_name = 'Asian College of Journalism';
        $email_subject = 'Asian College of Journalism';
        // $email_message=$email_array['message'];
        $this->email->from($from_email_address, $from_email_name);
        $this->email->to($to_email);
        $this->email->subject($view_data['content']['email_subject']);
        $this->email->message($mailtemplate);
        // $result = $this->email->send();

        if ($this->email->send()) {
            $this->session->set_flashdata('alert_success', 'successfully Mail Send');
            redirect($_SERVER['HTTP_REFERER']);
        } else {
            echo $this->email->print_debugger();
            exit;
            $this->session->set_flashdata('alert_danger', 'something Error');
            redirect($_SERVER['HTTP_REFERER']);
        }
    }



    public function mailSendOnCompletedList($appid)
    {

        $this->db->select('*, applications.id as appid, course.course_name as course_name, applications.status as apstatus');
        $this->db->from('applications');
        $this->db->join('course', 'course.id = applications.course_id', 'left');
        $this->db->join('users', 'users.user_id = applications.user_id');
        $this->db->join('accomodation_info as ai', 'ai.application_id = applications.id');
        $this->db->where('applications.id', $appid);
        $query  = $this->db->get();
        $applicationdatas  = $query->result();

        $view_data['name'] = $applicationdatas[0]->first_name;
        $view_data['course_id'] = $applicationdatas[0]->course_id;
        $view_data['refno'] = $applicationdatas[0]->reference_no;
        $view_data['userId'] = $applicationdatas[0]->user_id;

        if ($view_data['course_id'] == 1) {

            $subject = 'Application Form – ACJ Postgraduate Diploma in Integrated Multimedia 
            Journalism';

        } else if ($view_data['course_id'] == 2) {

            $subject =  'Application Form – ACJ-Bloomberg Postgraduate Diploma in Business and 
            Financial Multimedia Journalism';

        } else {

            $subject = 'Application Form – ACJ Postgraduate Diploma Programmes';

        }

        $to_email = $applicationdatas[0]->email;

        $mailtemplate = $this->load->view('acknowledgement/with_payment', $view_data, true);

        $this->load->library('email');
        $this->email->set_newline("\r\n");
        $from_email_address = 'acjadmissions@asianmedia.org.in';
        $from_email_name = 'Asian College of Journalism';
        $this->email->from($from_email_address, $from_email_name);
        $this->email->to($to_email);
        $this->email->subject($subject);
        $this->email->message($mailtemplate);
        if ($this->email->send()) {
            $this->session->set_flashdata('alert_success', 'successfully Mail Send');
            redirect($_SERVER['HTTP_REFERER']);
        } else {
            echo $this->email->print_debugger();
            exit;
            $this->session->set_flashdata('alert_danger', 'something Error');
            redirect($_SERVER['HTTP_REFERER']);
        }


    }

    public function examType()
    {

        $view_data['records'] =  $this->mcommon->records_all('exam_type',array('status',1));

        $data = array(
            'title' => 'Exam Type',
            'page' => 'Exam Type',
            'content' => $this->load->view('masters/examType', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }





    public function addEditExamType()
    {

        $id = $this->input->post('id');
        $exam_type = $this->input->post('exam_type');
        $total_marks = $this->input->post('total_marks');
        $total_questions = $this->input->post('total_questions');
        $each_mark = $this->input->post('each_mark');
        $timing = $this->input->post('timing');


        if ($id) {
            $update_array = array(
                'exam_type_name'    => $exam_type,
                'total_marks'    => $total_marks,
                'total_questions'    => $total_questions,
                'each_mark'    => $each_mark,
                'status'      => 1,
                'timing'    => $timing,
            );

            $update = $this->mcommon->common_edit('exam_type', $update_array, array('id' => $id));


            if ($update) {


                $this->session->set_flashdata('alert_success','Exam Type Updated Successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        } else {
            
            $user_array = array(
                'exam_type_name'    => $exam_type,
                'total_marks'    => $total_marks,
                'total_questions'    => $total_questions,
                'each_mark'    => $each_mark,
                'status'      => 1,
                'timing'    => $timing,
            );
            $insert = $this->mcommon->common_insert('exam_type', $user_array);


            if ($insert) {


                $this->session->set_flashdata('alert_success', 'Exam Type Added successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        }


        redirect('ApplicationController/examType');
    }

    public function sectionCategory()
    {

        $view_data['records'] =  $this->mcommon->records_all('section_category',array('status',1));
        $view_data['exam_type'] =  $this->mcommon->records_all('exam_type',array('status',1));

        $data = array(
            'title' => 'Section Category',
            'page' => 'Section Category',
            'content' => $this->load->view('masters/sectionCategory', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }


    public function addEditsectionCategory()
    {

        $id = $this->input->post('id');
        $exam_type = $this->input->post('exam_type');
        $category = $this->input->post('category');
      


        if ($id) {
            $update_array = array(
                'exam_type'    => $exam_type,
                'category'    => $category,
                'status'      => 1,
            );

            $update = $this->mcommon->common_edit('section_category', $update_array, array('id' => $id));


            if ($update) {


                $this->session->set_flashdata('alert_success','Exam Type Updated Successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        } else {
            
            $user_array = array(
                'exam_type'    => $exam_type,
                'category'    => $category,
                'status'      => 1,
            );
            $insert = $this->mcommon->common_insert('section_category', $user_array);


            if ($insert) {


                $this->session->set_flashdata('alert_success', 'Exam Type Added successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        }

        redirect('ApplicationController/sectionCategory');
    }

    public function createQuestion()
    {

        $view_data['records'] =  $this->mcommon->records_all('section_category',array('status',1));
        $view_data['exam_type'] =  $this->mcommon->records_all('exam_type',array('status',1));

        $data = array(
            'title' => 'Section Category',
            'page' => 'Section Category',
            'content' => $this->load->view('questions/view', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }
    public function viewQuestion()
    {
        
        $view_data['records'] =  $this->mcommon->records_all('question');
        $view_data['exam_type'] =  $this->mcommon->records_all('exam_type',array('status',1));
        $view_data['academic_year'] =  $this->mcommon->records_all('accadamic_year',array('status',1));
        $view_data['schedule'] =  $this->mcommon->records_all('exam_schedule',array('status',1));
        $view_data['category'] =  $this->mcommon->records_all('section_category',array('status',1));
        $data = array(
            'title' => 'View Question ',
            'page' => 'View Question',
            'content' => $this->load->view('questions/view', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }
    public function questionAdd()
    {

        if(isset($_POST['submit'])){
          
            $academic = $this->input->post('academic');
            $exam_type = $this->input->post('exam_type');
            $category = $this->input->post('category');
            $schedule = $this->input->post('schedule');
            $question = $this->input->post('question');
            $option_a = $this->input->post('option_a');
            $option_b = $this->input->post('option_b');
            $option_c = $this->input->post('option_c');
            $option_d = $this->input->post('option_d');
            $answer = $this->input->post('answer');

            $record = $this->mcommon->specific_row('exam_type', array('id' => $exam_type));

            $totalQuestions = isset($record['total_questions']) ? $record['total_questions'] : 0;

            $count = $this->mcommon->getQuestionCount($exam_type,$category);

            if($totalQuestions == $count)
            {
                $this->session->set_flashdata('alert_danger', 'Question Limit Exceeded successfully!');
                redirect('ApplicationController/viewQuestion');
                exit();
            }

            $insert_array = array(
                        'academic'          =>  $academic,
                        'exam_type'         =>  $exam_type,
                        'category'          =>  $category,
                        'schedule_id'          => $schedule,
                        'question'          =>  $question,
                        'option_a'          =>  $option_a,
                        'option_b'          =>  $option_b,
                        'option_c'          =>  $option_c,
                        'option_d'          =>  $option_d,
                        'answer'            =>  $answer,
                       
                    );
            
                    $insert = $this->mcommon->common_insert('question', $insert_array);
            
                    if ($insert) {
            
                        $this->session->set_flashdata('alert_success', 'Question  added successfully!');
                        redirect('ApplicationController/viewQuestion');
                    
                    } else {
                        $this->session->set_flashdata('alert_danger', 'Error in Add Question!');
                    }

        }else{

            $view_data['exam_type'] =  $this->mcommon->records_all('exam_type',array('status',1));
            $view_data['academic_year'] =  $this->mcommon->records_all('accadamic_year',array('status',1));
            $view_data['category'] =  $this->mcommon->records_all('section_category',array('status',1));
            $view_data['schedule'] =  $this->mcommon->records_all('exam_schedule',array('status',1));

            $data = array(
                'title' => 'Add  Question',
                'page' => 'Add  Question',
                'content' => $this->load->view('questions/add', $view_data, true),
            );
            $this->load->view('base/base_template', $data);
        }
            
        }

        public function questionEdit($id){
         
           
        if(isset($_POST['submit'])){

            $academic = $this->input->post('academic');
            $exam_type = $this->input->post('exam_type');
            $category = $this->input->post('category');
            $schedule = $this->input->post('schedule');
            $question = $this->input->post('question');
            $option_a = $this->input->post('option_a');
            $option_b = $this->input->post('option_b');
            $option_c = $this->input->post('option_c');
            $option_d = $this->input->post('option_d');
            $answer = $this->input->post('answer');

            $update_array = array(

                        'academic'          =>  $academic,
                        'exam_type'         =>  $exam_type,
                        'category'          =>  $category,
                        'schedule_id'       =>  $schedule,
                        'question'          =>  $question,
                        'option_a'          =>  $option_a,
                        'option_b'          =>  $option_b,
                        'option_c'          =>  $option_c,
                        'option_d'          =>  $option_d,
                        'answer'            =>  $answer,
                    );
                  
                    $update = $this->mcommon->common_edit('question',$update_array,array('id' => $id));
            
                    if ($update) {
            
                        $this->session->set_flashdata('alert_success', 'Question  Updated successfully!');
                        redirect('ApplicationController/viewQuestion');
                    
                    } else {
                        $this->session->set_flashdata('alert_danger', 'Error in Updated Question!');
                    }

        }else{

            $view_data['default'] = $this->mcommon->specific_row('question', array('id' => $id));
            $view_data['exam_type'] =  $this->mcommon->records_all('exam_type',array('status',1));
            $view_data['academic_year'] =  $this->mcommon->records_all('accadamic_year',array('status',1));
            $view_data['category'] =  $this->mcommon->records_all('section_category',array('status',1));
            $view_data['schedule'] =  $this->mcommon->records_all('exam_schedule',array('status',1));
            $data = array(
                'title' => 'Edit  Question',
                'page' => 'Edit  Question',
                'content' => $this->load->view('questions/edit', $view_data, true),
            );
            $this->load->view('base/base_template', $data);
        }

        }

        

        public function examSchedule()
    {
        $view_data['academic_year'] =  $this->mcommon->records_all('accadamic_year', array('status', 1));
        $view_data['records'] =  $this->mcommon->records_all('exam_schedule', array('status', 1));
        $view_data['exam_type'] =  $this->mcommon->records_all('exam_type', array('status', 1));

        $data = array(
            'title' => 'Exam Schedule',
            'page' => 'Exam Schedule',
            'content' => $this->load->view('masters/examSchedule', $view_data, true),
        );
        $this->load->view('base/base_template', $data);
    }





    public function addEditexamSchedule()
    {

        $id = $this->input->post('id');
        $schedule = $this->input->post('schedule');
        $academic = $this->input->post('academic');
        $exam_type1 = $this->input->post('exam_type1');
        $exam_type2 = $this->input->post('exam_type2');
        $objective_date = $this->input->post('objective_date');
        $objective_time = $this->input->post('objective_time');
        $essay_date = $this->input->post('essay_date');
        $essay_time = $this->input->post('essay_time');


        if ($id) {
            $update_array = array(
                'exam_schedule'     => $schedule,
                'academic'          => $academic,
                'exam_type1'        => $exam_type1,
                'exam_type2'        => $exam_type2,
                'objective_date'    => $objective_date,
                'objective_time'    => $objective_time,
                'essay_date'        => $essay_date,
                'essay_time'        => $essay_time,
                'status'            => 1,
            );

            $update = $this->mcommon->common_edit('exam_schedule', $update_array, array('id' => $id));


            if ($update) {


                $this->session->set_flashdata('alert_success', 'Exam Schedule Updated Successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        } else {

            $user_array = array(
                'exam_schedule'     => $schedule,
                'academic'          => $academic,
                'exam_type1'        => $exam_type1,
                'exam_type2'        => $exam_type2,
                'objective_date'    => $objective_date,
                'objective_time'    => $objective_time,
                'essay_date'        => $essay_date,
                'essay_time'        => $essay_time,
                'status'            => 1,
            );
            $insert = $this->mcommon->common_insert('exam_schedule', $user_array);


            if ($insert) {


                $this->session->set_flashdata('alert_success', 'Exam Schedule Added successfully!');
            } else {

                $this->session->set_flashdata('alert_danger', 'Something went wrong');
            }
        }


        redirect('ApplicationController/examSchedule');
    }


    public function assingExam()
    {

      

        $user_ids     = $this->input->post('user_ids');

        $schedule     = $this->input->post('schedule');
        $question_category     = $this->input->post('question_category');
   
       

        foreach ($user_ids as $id) {
            $insert_array = array(
                'user_id' =>  $id,
                'question_category' =>  $question_category,
                'schedule' =>  $schedule,
            );
            $insert = $this->mcommon->common_insert('exam_assigned', $insert_array);
            // if( $insert){
            //     redirect('ApplicationController/completedformdetails');
            // }
        }
        echo  json_encode($insert);
    }
     


}
