<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Listings extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('date');
        //$this->load->library('../controllers/activity');
        if (!$this->session->userdata('logged_in')) {
            $this->session->set_flashdata('noaccess', 'Sorry, you are not logged in');
            redirect('auth/login');
        }
    }

    public $data = array('subview' => 'Opps, forgot to set a subview');
    
    
        /**
	 * Display members own engines list
	 * @$sort_by
	 * @$sort_order
	 */

    public function my_engines_list($sort_by = 'manufacturer', $sort_order = 'asc') {

        $this->data['fields'] = array(
            'manufacturer' => 'Manufacturer:',
            'engine_model' => 'Model:',
            'esn' => 'ESN:',
            'lister' => 'Lister:',
            'transaction' => 'Transaction:',
            'location' => 'Location:',
            'asking_price' => 'Asking Price:',
            'monthly_rent' => 'Monthly Rent:',
            'available_date' => 'Available Date:'
        );

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

        $per_pg = 15;
        $total = $this->listings_model->get_totalcount();


        $config['base_url'] = base_url() . "epc_listings/listings/my_engines_list/$sort_by/$sort_order";
        $config['total_rows'] = $total;
        $config['per_page'] = $per_pg;
        $config['uri_segment'] = 6;
        $choice = $config['total_rows'] / $config['per_page'];
        $config['num_links'] = round($choice);


        $this->pagination->initialize($config);
        $page = ($this->uri->segment(6)) ? $this->uri->segment(6) : 0;

        $this->data['listings'] = $this->listings_model->get_listings($config['per_page'], $page, $sort_by, $sort_order);
        $this->data['links'] = $this->pagination->create_links();

        if ($this->data['links'] != '') {
            $this->data['start'] = (($this->pagination->cur_page - 1) * $this->pagination->per_page) + 1;
            $this->data['end'] = ($this->pagination->cur_page * $this->pagination->per_page);

            if ($this->data['end'] > $this->pagination->total_rows) {
                $this->data['end'] = $this->pagination->total_rows;
            }
        }


        $this->data['ptotal'] = $this->listings_model->get_ptotalcount();
        $this->data['total'] = $this->listings_model->get_totalcount();

        //load view and layout
        $this->data['subview'] = 'listings/my_engines_list';
        $this->data['sort_by'] = $sort_by;
        $this->data['sort_order'] = $sort_order;
        
        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
		{
	             //load the view passing $data values
                     $this->load->view("layouts/main_admin", $this->data);
		}
                else if ($this->ion_auth->logged_in() && !$this->ion_auth->is_admin())
		{
                    $idz = $this->ion_auth->get_user_id();
                    $user = $this->ion_auth->user($idz)->row();
            
            if($user->listing == 'Y')                  
		     //load the view passing $data values
                    {
                     $this->load->view("layouts/main_logged_in", $this->data);
                    }
                    
                    else
                    {
                        $this->data['subview'] = 'listings/listing_disabled';
                        $this->load->view("layouts/main_logged_in", $this->data);
                    }
		}
    }

        /**
	 * Add engine listing
	 */

    public function add_listing() {

        $this->form_validation->set_rules('manufacturer', 'Manufacturer', 'callback__company_dropdown|xss_clean');
        $this->form_validation->set_rules('engine_model', 'Engine Model', 'trim|required|xss_clean');
        $this->form_validation->set_rules('esn', 'ESN', 'trim|integer|required|xss_clean');
        $this->form_validation->set_rules('tsn', 'TSN', 'trim|integer|xss_clean');
        $this->form_validation->set_rules('csn', 'CSN', 'trim|integer|xss_clean');
        $this->form_validation->set_rules('tso', 'TSO', 'trim|integer|xss_clean');
        $this->form_validation->set_rules('cso', 'CSO', 'trim|integer|xss_clean');
        $this->form_validation->set_rules('first_limiter', 'First Limiter', 'trim|xss_clean');
        $this->form_validation->set_rules('limiting_module', 'Limiting Module', 'trim|xss_clean');
        $this->form_validation->set_rules('last_operator', 'Last Operator', 'trim|xss_clean');
        $this->form_validation->set_rules('location', 'Location', 'trim|xss_clean');
        $this->form_validation->set_rules('inlineradio', 'Lister', 'callback__radio_validation|xss_clean');
        $this->form_validation->set_rules('inlinecheck[]', 'Transaction', 'required|xss_clean');
        $this->form_validation->set_rules('asking_price', 'Asking Price', 'trim|xss_clean');
        $this->form_validation->set_rules('monthly_rent', 'Monthly Rent', 'trim|xss_clean');
        $this->form_validation->set_rules('available_date', 'Available Date', 'callback__date_validation|xss_clean');

        $this->data['total'] = $this->listings_model->get_totalcount();
        $this->data['ptotal'] = $this->listings_model->get_ptotalcount();

        if ($this->form_validation->run() == FALSE) {
//            $this->data['subview'] = 'listings/add_listing';
            
            if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
		{
                    $this->data['subview'] = 'listings/add_listing';
	             //load the view passing $data values
                     $this->load->view("layouts/main_admin", $this->data);
		}
                else if ($this->ion_auth->logged_in() && !$this->ion_auth->is_admin())
		{
                     $idz = $this->ion_auth->get_user_id();
                     $user = $this->ion_auth->user($idz)->row();
		     if($user->listing == 'Y')                  
		     //load the view passing $data values
                    {
                     $this->data['subview'] = 'listings/add_listing';
                     $this->load->view("layouts/main_logged_in", $this->data);
                    }
                    
                    else
                    {
                        $this->data['subview'] = 'listings/listing_disabled';
                        $this->load->view("layouts/main_logged_in", $this->data);
                    }
		}
           
        } else {
            
            
        $this->form_validation->set_rules('userfile', 'Mini Pack', 'callback__file_validation|xss_clean');  
        
        if ($this->form_validation->run() == TRUE) {
            

            $sel = $this->input->post('inlinecheck');
            $data = array(
                'status' => 'A',
                'id' => $this->ion_auth->get_user_id(),
                'manufacturer' => $this->input->post('company_dropdown'),
                'engine_model' => $this->input->post('engine_model'),
                'esn' => $this->input->post('esn'),
                'tsn' => $this->input->post('tsn'),
                'csn' => $this->input->post('csn'),
                'tso' => $this->input->post('tso'),
                'cso' => $this->input->post('cso'),
                'first_limiter' => $this->input->post('first_limiter'),
                'limiting_module' => $this->input->post('limiting_module'),
                'last_operator' => $this->input->post('last_operator'),
                'location' => $this->input->post('location'),
                'lister' => $this->input->post('inlineradio'),
                'transaction' => implode("/", $sel),
                'asking_price' => $this->input->post('asking_price'),
                'monthly_rent' => $this->input->post('monthly_rent'),
                'available_date' => $this->input->post('available_date'),
                'mini_pack_name' => $this->data['upload_data']['file_name'],
                'mini_pack_folder' => $this->data['folder'],
                'mini_pack_path' => $this->data['upload_data']['full_path']
            );
            
            
            
            if ($this->listings_model->add_listing($data)) {
                $this->load->library('../controllers/activity');
                $idz = $this->ion_auth->get_user_id();
                $user = $this->ion_auth->user($idz)->row();
                
                $this->session->set_flashdata('engine_added', 'Engine has been added to your list.');
                
                $date = date('Y-m-d');
                date_default_timezone_set('America/New_York');
                $time = date('h:i:s a', time());
                $this->activity->insert($user->email, 'added engine listing', $date, $time);
                redirect('epc_listings/listings/my_engines_list');
            }
        }
        
        else
        {
            $this->data['subview'] = 'listings/add_listing';
            $this->load->view("layouts/main_logged_in", $this->data);
            //echo $this->upload->display_errors('<p class="alert alert-dismissable alert-danger">','</p>');
        }
        
        
      }
    }
    
    
        /**
	 * Edit engine listing
	 * @$listing id
	 */

    public function edit_listing($listing_id) {

        $this->form_validation->set_rules('manufacturer', 'Manufacturer', 'callback__company_dropdown|xss_clean');
        $this->form_validation->set_rules('engine_model', 'Engine Model', 'trim|required|xss_clean');
        $this->form_validation->set_rules('esn', 'ESN', 'trim|integer|required|xss_clean');
        $this->form_validation->set_rules('tsn', 'TSN', 'trim|integer|xss_clean');
        $this->form_validation->set_rules('csn', 'CSN', 'trim|integer|xss_clean');
        $this->form_validation->set_rules('tso', 'TSO', 'trim|integer|xss_clean');
        $this->form_validation->set_rules('cso', 'CSO', 'trim|integer|xss_clean');
        $this->form_validation->set_rules('first_limiter', 'First Limiter', 'trim|xss_clean');
        $this->form_validation->set_rules('limiting_module', 'Limiting Module', 'trim|xss_clean');
        $this->form_validation->set_rules('last_operator', 'Last Operator', 'trim|xss_clean');
        $this->form_validation->set_rules('location', 'Location', 'trim|xss_clean');
        $this->form_validation->set_rules('inlineradio', 'Lister', 'required|xss_clean');
        $this->form_validation->set_rules('inlinecheck[]', 'Transaction', 'required|xss_clean');
        $this->form_validation->set_rules('asking_price', 'Asking Price', 'trim|xss_clean');
        $this->form_validation->set_rules('monthly_rent', 'Monthly Rent', 'trim|xss_clean');
        $this->form_validation->set_rules('available_date', 'Available Date', 'callback__date_validation|xss_clean');
        

        $this->data['total'] = $this->listings_model->get_totalcount();
        $this->data['ptotal'] = $this->listings_model->get_ptotalcount();


        if ($this->form_validation->run() == FALSE) {
            $this->data['this_listing'] = $this->listings_model->get_listing_data($listing_id);

            
            
            if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
		{
                    $this->data['subview'] = 'listings/edit_listing';
	             //load the view passing $data values
                     $this->load->view("layouts/main_admin", $this->data);
		}
                else if ($this->ion_auth->logged_in() && !$this->ion_auth->is_admin())
		{
                        $idz = $this->ion_auth->get_user_id();
                        $user = $this->ion_auth->user($idz)->row();
		     if($user->listing == 'Y')                  
		     //load the view passing $data values
                    {
                     $this->data['subview'] = 'listings/edit_listing';    
                     $this->load->view("layouts/main_logged_in", $this->data);
                    }
                    
                    else
                    {
                        $this->data['subview'] = 'listings/listing_disabled';
                        $this->load->view("layouts/main_logged_in", $this->data);
                    }
		}
            
        } else {
            
            $this->data['this_listing'] = $this->listings_model->get_listing_data($listing_id);
            $mini_p_fol = $this->data['this_listing']->mini_pack_folder;
                
            $this->form_validation->set_rules('userfile', 'Mini Pack', 'callback__editfile_validation['.$mini_p_fol.']|xss_clean');
                
                if ($this->form_validation->run() == TRUE) {
            
            
            if ($this->listings_model->edit_listing($listing_id, $this->data['upload_data'])) {
                $this->load->library('../controllers/activity');
                $idz = $this->ion_auth->get_user_id();
                $user = $this->ion_auth->user($idz)->row();
                
                $this->session->set_flashdata('engine_updated', "Engine listing number: $listing_id has been updated");
                $date = date('Y-m-d');
                date_default_timezone_set('America/New_York');
                $time = date('h:i:s a', time());
                $this->activity->insert($user->email, 'updated engine listing', $date, $time);
                redirect('epc_listings/listings/my_engines_list');
            }
                }
                
                else
        {
            $this->data['subview'] = 'listings/edit_listing';
            $this->load->view("layouts/main_logged_in", $this->data);
            //echo $this->upload->display_errors('<p class="alert alert-dismissable alert-danger">','</p>');
        }
        }
    }
    
    
        /**
	 * Delete engine listing
	 * @$listing id
	 */

    public function delete_listing($listing_id) {
        
                        $idz = $this->ion_auth->get_user_id();
                        $user = $this->ion_auth->user($idz)->row();
                        $em5 = $user->email;
                        
		     if($user->listing == 'Y')                  
		     //load the view passing $data values
                    {
                    $this->data['this_listing'] = $this->listings_model->get_listing_data($listing_id);
                    $del_fol = $this->data['this_listing']->mini_pack_folder;    
                         
                         
                     $this->listings_model->delete_listing($listing_id);
                     $this->session->set_flashdata('engine_deleted', "Engine listing number: $listing_id has been deleted");
                     delete_files('./members/'.$em5.'/engine_listings/'.$del_fol.'/');
                     rmdir('./members/'.$em5.'/engine_listings/'.$del_fol);
                     
                     $this->load->library('../controllers/activity');
                     $date = date('Y-m-d');
                     date_default_timezone_set('America/New_York');
                     $time = date('h:i:s a', time());
                     $this->activity->insert($em5, 'deleted engine listing', $date, $time);
                     
                     redirect('epc_listings/listings/my_engines_list');
                    }
                    
                    else
                    {
                        $this->data['subview'] = 'listings/listing_disabled';
                        $this->load->view("layouts/main_logged_in", $this->data);
                    }
    }
    
        /**
	 * Display engine listing to user
	 * @$listing_id
	 */

    public function display_listing($listing_id) {

        $this->data['this_listing'] = $this->listings_model->get_listing_data($listing_id);

        $this->data['total'] = $this->listings_model->get_totalcount();
        $this->data['ptotal'] = $this->listings_model->get_ptotalcount();

        $this->data['subview'] = 'listings/display_listing';
        
        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
		{
	             //load the view passing $data values
                     $this->load->view("layouts/main_admin", $this->data);
		}
                else if ($this->ion_auth->logged_in() && !$this->ion_auth->is_admin())
		{
		     $idz = $this->ion_auth->get_user_id();
                    $user = $this->ion_auth->user($idz)->row();
            
                    if($user->listing == 'Y')                  
		     //load the view passing $data values
                    {
                     $this->load->view("layouts/main_logged_in", $this->data);
                    }
                    
                    else
                    {
                        $this->data['subview'] = 'listings/listing_disabled';
                        $this->load->view("layouts/main_logged_in", $this->data);
                    }
		}

    }
    
        /**
	 * Validates engine manufacturer dropdown
	 */

    public function _company_dropdown() {

        if ($this->input->post('company_dropdown') == '--Select Manufacturer--') {
            $this->form_validation->set_message('_company_dropdown', 'The Manufacturer field is required.');
            return FALSE;
        }


        $companies = array('--Select Manufacturer--', 'CFM International', 'Engine Alliance', 'GE Aviation', 'Honeywell Aerospace',
            'International Aero Engines', 'Pratt & Whitney', 'Rolls Royce', 'Williams International');

        $selected = $this->input->post('company_dropdown');

        if (in_array($selected, $companies)) {
            return TRUE;
        } else {
            $this->form_validation->set_message('_company_dropdown', 'Invalid Manufacturer');
            return FALSE;
        }
    }
    
    
        /**
	 * Validates part condition dropdown
	 */
    public function _part_condition_dropdown() {

        if ($this->input->post('part_condition_dropdown') == '--Select Part Condition--') {
            $this->form_validation->set_message('_part_condition_dropdown', 'The Part Condition field is required.');
            return FALSE;
        }


        $parts_conditions = array('--Select Part Condition--', 'AR', 'NE', 'NS', 'OH',
            'SV');

        $selected1 = $this->input->post('part_condition_dropdown');

        if (in_array($selected1, $parts_conditions)) {
            return TRUE;
        } else {
            $this->form_validation->set_message('_part_condition_dropdown', 'Invalid Part Condition');
            return FALSE;
        }
    }
    
    
        /**
	 * Validates tag part condition dropdown
	 */
    public function _tag_dropdown() {

        if ($this->input->post('tag_dropdown') == '--Select Tag--') {
            $this->form_validation->set_message('_tag_dropdown', 'The Tag field is required.');
            return FALSE;
        }


        $tags = array('--Select Tag--', 'AR', 'DUAL', 'EASA', 'FAA');

        $selected2 = $this->input->post('tag_dropdown');

        if (in_array($selected2, $tags)) {
            return TRUE;
        } else {
            $this->form_validation->set_message('_tag_dropdown', 'Invalid Tag');
            return FALSE;
        }
    }
    

        /**
	 * Validates engine file being uploaded
	 */
    public function _file_validation() {
        
        $id = $this->ion_auth->get_user_id();
        $user = $this->ion_auth->user($id)->row();
        $em = $user->email;
        
        $datestring = 'YmdHis';
        $time = time();
        $date = date($datestring, $time);

        //set the path where the files uploaded will be copied
        $config['upload_path'] = './members/'.$em.'/engine_listings/'.$date;

        // set the filter image types
        $config['allowed_types'] = 'pdf|gif|jpg|png|docx|doc|txt|rtf';

        //overwrite image
//        $config['overwrite'] = TRUE;
        
        //load the upload library
        $this->load->library('upload', $config);
        //$this->upload->initialize($config);

        if (isset($_FILES['userfile']) && !empty($_FILES['userfile']['name'])) {
            
            
        
            if (!is_dir('members/'.$em.'/engine_listings/'.$date)) {
                mkdir('./members/'.$em.'/engine_listings/'.$date, 0777, true);
            }
            
            $this->data['folder'] = $date;

            if (!$this->upload->do_upload('userfile')) {


                $this->form_validation->set_message('_file_validation', 'Invalid Format. Type of format allowed: pdf,gif,jpg,png,docx,doc,txt,rtf.');
                return FALSE;
            } else {
                
                $this->data['upload_data'] = $this->upload->data();
                return TRUE;
            }
        } else {
            mkdir('./members/'.$em.'/engine_listings/'.$date, 0777, true);
            $this->data['folder'] = $date;
//        $this->form_validation->set_message('_file_validation', 'No file to upload');
            return TRUE;
        }
    }
    
    
        /**
	 * Validates radio selection
	 */
    public function _radio_validation() {

        if (!isset($_POST['inlineradio'])) {
            $this->form_validation->set_message('_radio_validation', 'The Lister Field is required.');
            return FALSE;
        } else {
            return TRUE;
        }
    }
    
        /**
	 * Validates date entered
	 */
    public function _date_validation() {
        $str = $_POST['available_date'];

        if (empty($_POST['available_date'])) {
            $this->form_validation->set_message('_date_validation', 'The Date Field is required.');
            return FALSE;
        } else {
            if (preg_match("/^(0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])[-](19\d\d|2\d\d\d)$/", $str, $match) && checkdate($match[1], $match[2], $match[3])) {

                return TRUE;
            } else {
                $this->form_validation->set_message('_date_validation', 'Invalid Date Format. Enter as Day-Month-Year');
                return FALSE;
            }
        }
    }

        /**
	 * Validate edit file upload
	 * @$userfile
	 * @$mini_p_fol
	 */
    public function _editfile_validation($userfile, $mini_p_fol) {
        
        
        $id1 = $this->ion_auth->get_user_id();
        $user1 = $this->ion_auth->user($id1)->row();
        $em1 = $user1->email;

        //set the path where the files uploaded will be copied
        $config['upload_path'] = './members/'.$em1.'/engine_listings/'.$mini_p_fol;

        // set the filter image types
        $config['allowed_types'] = 'pdf|gif|jpg|png|docx|doc|txt|rtf';

        //overwrite image
//        $config['overwrite'] = TRUE;
        
        //load the upload library
        $this->load->library('upload', $config);
//        $this->upload->initialize($config);

        if (isset($_FILES['userfile']) && !empty($_FILES['userfile']['name'])) {
            
            delete_files('./members/'.$em1.'/engine_listings/'.$mini_p_fol.'/');
            
             if (!$this->upload->do_upload('userfile')) {
               
                $this->form_validation->set_message('_editfile_validation', 'Invalid Format. Type of format allowed: pdf,gif,jpg,png,docx,doc,txt,rtf.');
                return FALSE;
            } else {
                
                $this->data['upload_data'] = $this->upload->data();
                return TRUE;
            }
        } else {
//        $this->form_validation->set_message('_editfile_validation', 'No file to upload');
            return TRUE;
        }
    }
    
        /**
	 * Display members own engine parts list
	 * @$sort_by = 'part_number'
	 * @$sort_order = 'asc'
	 */
    public function my_engine_parts_list($sort_by = 'part_number', $sort_order = 'asc') {

        $this->data['fields'] = array(
            'part_number' => 'Part Number:',
            'part_description' => 'Part Description:',
            'part_condition' => 'Part Condition:',
            'enginep_model' => 'Engine Model:',
            'tag' => 'Tag:',
            'quantity' => 'Quantity:',
            'lister' => 'Lister:',
            'transaction' => 'Transaction:',
            'location' => 'Location:',
            'asking_price' => 'Asking Price:',
            'monthly_rent' => 'Monthly Rent:',
            'available_date' => 'Available Date:'
        );

        $pper_pg = 15;
        $ptotal = $this->listings_model->get_ptotalcount();


        $config['base_url'] = base_url() . "epc_listings/listings/my_engine_parts_list/$sort_by/$sort_order";
        $config['total_rows'] = $ptotal;
        $config['per_page'] = $pper_pg;
        $config['uri_segment'] = 6;
        $choice = $config['total_rows'] / $config['per_page'];
        $config['num_links'] = round($choice);


        $this->pagination->initialize($config);
        $ppage = ($this->uri->segment(6)) ? $this->uri->segment(6) : 0;

        $this->data['plistings'] = $this->listings_model->get_plistings($config['per_page'], $ppage, $sort_by, $sort_order);


        $this->data['plinks'] = $this->pagination->create_links();


        if ($this->data['plinks'] != '') {
            $this->data['pstart'] = (($this->pagination->cur_page - 1) * $this->pagination->per_page) + 1;
            $this->data['pend'] = ($this->pagination->cur_page * $this->pagination->per_page);

            if ($this->data['pend'] > $this->pagination->total_rows) {
                $this->data['pend'] = $this->pagination->total_rows;
            }
        }

        $this->data['ptotal'] = $this->listings_model->get_ptotalcount();
        $this->data['total'] = $this->listings_model->get_totalcount();

        $this->data['subview'] = 'listings/my_engine_parts_list';
        $this->data['sort_by'] = $sort_by;
        $this->data['sort_order'] = $sort_order;
        
        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
		{
	             //load the view passing $data values
                     $this->load->view("layouts/main_admin", $this->data);
		}
                else if ($this->ion_auth->logged_in() && !$this->ion_auth->is_admin())
		{
                    $idz = $this->ion_auth->get_user_id();
                    $user = $this->ion_auth->user($idz)->row();
                    if($user->listing == 'Y')                  
		     //load the view passing $data values
                    {
                     $this->load->view("layouts/main_logged_in", $this->data);
                    }
                    
                    else
                    {
                        $this->data['subview'] = 'listings/listing_disabled';
                        $this->load->view("layouts/main_logged_in", $this->data);
                    }
		     //load the view passing $data values
		}
    }
    
    
        /**
	 * Add engine part listing
	 */
    public function add_plisting() {

        $this->form_validation->set_rules('part_number', 'Part number', 'trim|required|xss_clean');
        $this->form_validation->set_rules('part_description', 'Part Description', 'max_length[300]|trim|xss_clean');
        $this->form_validation->set_rules('part_condition', 'Part Condition', 'callback__part_condition_dropdown|xss_clean');
        $this->form_validation->set_rules('enginep_model', 'Engine Model', 'trim|xss_clean');
        $this->form_validation->set_rules('tag', 'Tag', 'callback__tag_dropdown|xss_clean');
        $this->form_validation->set_rules('quantity', 'Quantity', 'trim|required|integer|xss_clean');
        $this->form_validation->set_rules('inlineradio', 'Lister', 'callback__radio_validation|xss_clean');
        $this->form_validation->set_rules('inlinecheck[]', 'Transaction', 'required|xss_clean');
        $this->form_validation->set_rules('location', 'Location', 'trim|xss_clean');
        $this->form_validation->set_rules('asking_price', 'Asking Price', 'trim|xss_clean');
        $this->form_validation->set_rules('monthly_rent', 'Monthly Rent', 'trim|xss_clean');
        $this->form_validation->set_rules('available_date', 'Available Date', 'callback__date_validation|xss_clean');

        $this->data['ptotal'] = $this->listings_model->get_ptotalcount();
        $this->data['total'] = $this->listings_model->get_totalcount();

        if ($this->form_validation->run() == FALSE) {
            
            
            if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
		{
                     $this->data['subview'] = 'listings/add_plisting';
	             //load the view passing $data values
                     $this->load->view("layouts/main_admin", $this->data);
		}
                else if ($this->ion_auth->logged_in() && !$this->ion_auth->is_admin())
		{
		     $idz = $this->ion_auth->get_user_id();
                    $user = $this->ion_auth->user($idz)->row();
            
                    if($user->listing == 'Y')                  
		     //load the view passing $data values
                    {
                     $this->data['subview'] = 'listings/add_plisting';   
                     $this->load->view("layouts/main_logged_in", $this->data);
                    }
                    
                    else
                    {
                        $this->data['subview'] = 'listings/listing_disabled';
                        $this->load->view("layouts/main_logged_in", $this->data);
                    }
		}
                
        } else {
            
            $this->form_validation->set_rules('userfile1', 'Record', 'callback__filep_validation|xss_clean');
            
            if ($this->form_validation->run() == TRUE) {

            $sel1 = $this->input->post('inlinecheck');
            $data = array(
                'status' => 'A',
                'id' => $this->ion_auth->get_user_id(),
                'part_number' => $this->input->post('part_number'),
                'part_description' => $this->input->post('part_description'),
                'part_condition' => $this->input->post('part_condition_dropdown'),
                'enginep_model' => $this->input->post('enginep_model'),
                'tag' => $this->input->post('tag_dropdown'),
                'quantity' => $this->input->post('quantity'),
                'lister' => $this->input->post('inlineradio'),
                'transaction' => implode("/", $sel1),
                'asking_price' => $this->input->post('asking_price'),
                'monthly_rent' => $this->input->post('monthly_rent'),
                'available_date' => $this->input->post('available_date'),
                'record_name' => $this->data['upload_data']['file_name'],
                'record_folder' => $this->data['folder'],
                'record_path' => $this->data['upload_data']['full_path']    
            );

            if ($this->listings_model->add_plisting($data)) {
                $this->load->library('../controllers/activity');
                $idz = $this->ion_auth->get_user_id();
                $user = $this->ion_auth->user($idz)->row();
                
                $this->session->set_flashdata('engine_part_added', 'Part has been added to your list.');
                
                
                $date = date('Y-m-d');
                date_default_timezone_set('America/New_York');
                $time = date('h:i:s a', time());
                $this->activity->insert($user->email, 'added part listing', $date, $time);

                redirect('epc_listings/listings/my_engine_parts_list');
            }
        }
        
        else
        {
            $this->data['subview'] = 'listings/add_plisting';
            $this->load->view("layouts/main_logged_in", $this->data);
            //echo $this->upload->display_errors('<p class="alert alert-dismissable alert-danger">','</p>');
        }
        
        }
    }
    
    
        /**
	 * Delete engine part listing
         * @$listing_id
	 */
    public function delete_plisting($listing_id) {
        
                    $idz = $this->ion_auth->get_user_id();
                    $user = $this->ion_auth->user($idz)->row();
                    $em6 = $user->email;
            
                    if($user->listing == 'Y')                  
		     //load the view passing $data values
                    {
                     $this->data['this_plisting'] = $this->listings_model->get_plisting_data($listing_id);
                     $delp_fol = $this->data['this_plisting']->record_folder;
                    
                    
                     $this->listings_model->delete_plisting($listing_id);
                     $this->session->set_flashdata('engine_part_deleted', "Part listing number: $listing_id has been deleted");
                     delete_files('./members/'.$em6.'/part_listings/'.$delp_fol.'/');
                     rmdir('./members/'.$em6.'/part_listings/'.$delp_fol);
                     
                     $this->load->library('../controllers/activity');
                     $date = date('Y-m-d');
                     date_default_timezone_set('America/New_York');
                     $time = date('h:i:s a', time());
                     $this->activity->insert($em6, 'deleted part listing', $date, $time);
                     redirect('epc_listings/listings/my_engine_parts_list');
                    }
                    
                    else
                    {
                        $this->data['subview'] = 'listings/listing_disabled';
                        $this->load->view("layouts/main_logged_in", $this->data);
                    }
    }
    
    
        /**
	 * Display engine part listing to user
         * @$listing_id
	 */
    public function display_plisting($listing_id) {

        $this->data['this_plisting'] = $this->listings_model->get_plisting_data($listing_id);

        $this->data['ptotal'] = $this->listings_model->get_ptotalcount();
        $this->data['total'] = $this->listings_model->get_totalcount();
        $this->data['subview'] = 'listings/display_plisting';
        
        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
		{
	             //load the view passing $data values
                     $this->load->view("layouts/main_admin", $this->data);
		}
                else if ($this->ion_auth->logged_in() && !$this->ion_auth->is_admin())
		{
		     $idz = $this->ion_auth->get_user_id();
                    $user = $this->ion_auth->user($idz)->row();
            
                    if($user->listing == 'Y')                  
		     //load the view passing $data values
                    {
                     $this->load->view("layouts/main_logged_in", $this->data);
                    }
                    
                    else
                    {
                        $this->data['subview'] = 'listings/listing_disabled';
                        $this->load->view("layouts/main_logged_in", $this->data);
                    }
		}
    }
    
    
        /**
	 * Edit engine part listing
         * @$listing_id
	 */
    public function edit_plisting($listing_id) {

        $this->form_validation->set_rules('part_number', 'Part number', 'trim|required|xss_clean');
        $this->form_validation->set_rules('part_description', 'Part Description', 'max_length[300]|trim|xss_clean');
        $this->form_validation->set_rules('part_condition', 'Part Condition', 'callback__part_condition_dropdown|xss_clean');
        $this->form_validation->set_rules('tag', 'Tag', 'callback__tag_dropdown|xss_clean');
        $this->form_validation->set_rules('quantity', 'Quantity', 'trim|required|integer|xss_clean');
        $this->form_validation->set_rules('inlineradio', 'Lister', 'callback__radio_validation|xss_clean');
        $this->form_validation->set_rules('inlinecheck[]', 'Transaction', 'required|xss_clean');
        $this->form_validation->set_rules('location', 'Location', 'trim|xss_clean');
        $this->form_validation->set_rules('asking_price', 'Asking Price', 'trim|xss_clean');
        $this->form_validation->set_rules('monthly_rent', 'Monthly Rent', 'trim|xss_clean');
        $this->form_validation->set_rules('available_date', 'Available Date', 'callback__date_validation|xss_clean');

        $this->data['total'] = $this->listings_model->get_totalcount();
        $this->data['ptotal'] = $this->listings_model->get_ptotalcount();


        if ($this->form_validation->run() == FALSE) {
            $this->data['this_plisting'] = $this->listings_model->get_plisting_data($listing_id);

            
            
            if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
		{
                     $this->data['subview'] = 'listings/edit_plisting';
	             //load the view passing $data values
                     $this->load->view("layouts/main_admin", $this->data);
		}
                else if ($this->ion_auth->logged_in() && !$this->ion_auth->is_admin())
		{
		    $idz = $this->ion_auth->get_user_id();
                    $user = $this->ion_auth->user($idz)->row();
            
                    if($user->listing == 'Y')                  
		     //load the view passing $data values
                    {
                     $this->data['subview'] = 'listings/edit_plisting';   
                     $this->load->view("layouts/main_logged_in", $this->data);
                    }
                    
                    else
                    {
                        $this->data['subview'] = 'listings/listing_disabled';
                        $this->load->view("layouts/main_logged_in", $this->data);
                    }
		}
                
        } else {
            
            $this->data['this_plisting'] = $this->listings_model->get_plisting_data($listing_id);
            $record_fol = $this->data['this_plisting']->record_folder;
                
            $this->form_validation->set_rules('userfile', 'Record', 'callback__editfilep_validation['.$record_fol.']|xss_clean');
                
            if ($this->form_validation->run() == TRUE) {

            if ($this->listings_model->edit_plisting($listing_id, $this->data['upload_data1'])) {
                $this->load->library('../controllers/activity');
                $idz = $this->ion_auth->get_user_id();
                $user = $this->ion_auth->user($idz)->row();
                
                $this->session->set_flashdata('engine_part_updated', "Part listing number: $listing_id has been updated");
                
                $date = date('Y-m-d');
                date_default_timezone_set('America/New_York');
                $time = date('h:i:s a', time());
                $this->activity->insert($user->email, 'updated part listing', $date, $time);
                redirect('epc_listings/listings/my_engine_parts_list');
            }
            }
            
            else
            {
                $this->data['subview'] = 'listings/edit_plisting';
                $this->load->view("layouts/main_logged_in", $this->data);
            //echo $this->upload->display_errors('<p class="alert alert-dismissable alert-danger">','</p>');
            }
            
        }
    }
    
    
        /**
	 * Validates engine part file being uploaded
	 */
    public function _filep_validation() {
        
        $id = $this->ion_auth->get_user_id();
        $user = $this->ion_auth->user($id)->row();
        $em = $user->email;
        
        $datestring = 'YmdHis';
        $time = time();
        $date = date($datestring, $time);

        //set the path where the files uploaded will be copied
        $config['upload_path'] = './members/'.$em.'/part_listings/'.$date;

        // set the filter image types
        $config['allowed_types'] = 'pdf|gif|jpg|png|docx|doc|txt|rtf';

        //overwrite image
//        $config['overwrite'] = TRUE;
        
        //load the upload library
        $this->load->library('upload', $config);
        //$this->upload->initialize($config);

        if (isset($_FILES['userfile']) && !empty($_FILES['userfile']['name'])) {
        
            if (!is_dir('members/'.$em.'/part_listings/'.$date)) {
                mkdir('./members/'.$em.'/part_listings/'.$date, 0777, true);
            }
            
            $this->data['folder'] = $date;

            if (!$this->upload->do_upload('userfile')) {


                $this->form_validation->set_message('_filep_validation', 'Invalid Format. Type of format allowed: pdf,gif,jpg,png,docx,doc,txt,rtf.');
                return FALSE;
            } else {
                
                $this->data['upload_data'] = $this->upload->data();
                return TRUE;
            }
        } else {
            mkdir('./members/'.$em.'/part_listings/'.$date, 0777, true);
            $this->data['folder'] = $date;
//        $this->form_validation->set_message('_file_validation', 'No file to upload');
            return TRUE;
        }
    }
    
    
        /**
	 * Validates engine part file being edited
         * @$userfile
         * @$record_fol
	 */
    public function _editfilep_validation($userfile, $record_fol) {
        
        
        $id1 = $this->ion_auth->get_user_id();
        $user1 = $this->ion_auth->user($id1)->row();
        $em1 = $user1->email;

        //set the path where the files uploaded will be copied
        $config['upload_path'] = './members/'.$em1.'/part_listings/'.$record_fol;

        // set the filter image types
        $config['allowed_types'] = 'pdf|gif|jpg|png|docx|doc|txt|rtf';

        //overwrite image
//        $config['overwrite'] = TRUE;
        
        //load the upload library
        $this->load->library('upload', $config);
//        $this->upload->initialize($config);

        if (isset($_FILES['userfile']) && !empty($_FILES['userfile']['name'])) {
            
            delete_files('./members/'.$em1.'/part_listings/'.$record_fol.'/');
            
             if (!$this->upload->do_upload('userfile')) {
               
                $this->form_validation->set_message('_editfilep_validation', 'Invalid Format. Type of format allowed: pdf,gif,jpg,png,docx,doc,txt,rtf.');
                return FALSE;
            } else {
                
                $this->data['upload_data1'] = $this->upload->data();
                return TRUE;
            }
        } else {
//        $this->form_validation->set_message('_editfile_validation', 'No file to upload');
            return TRUE;
        }
    }

}

