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

require_once 'vendor/autoload.php';

use SimpleExcel\SimpleExcel;

class Subscribers extends CI_Controller
{
    /**
     * View Function (for ajax) to display create or edit Visitor Registration
     *
     * @param integer $visitor_id
     * @return html/string
     */
    public function createOrEdit($visitor_id = NULL, $msg = NULL)
    {
        $pagedata['subscribers'] = objToArr($this->AdminVisitorModel->getVisitor('subscriber.id', $visitor_id));
        $pagedata['flats'] = objToArr($this->AdminVisitorModel->flatList());
        $data['page'] = "Add Visitor";
        $data['menu'] = 'visitorreg';
        $data['msg'] = $msg;
        $this->load->view('admin/layout/header', $data);
        $this->load->view('admin/subscribers/create-or-edit', $pagedata);
    }

    /**
     * Function (for ajax) to process user create or edit form request
     *
     * @return redirect
     */
    public function saveVisitor()
    {
        $this->checkIfDemo();
        // if (isset($this->session->userdata('admin')['user_type']) && 
        //         ($this->session->userdata('admin')['user_type'] == 'security' || 
        //         $this->session->userdata('admin')['user_type'] == 'admin')) { 
        //     $this->form_validation->set_rules('flat_id', 'Flat Name', 'trim|required');
        //     $this->form_validation->set_rules('flat_owner', 'Flat Owner', 'required');      
        // }
        $this->form_validation->set_rules('visitor_name', 'Visitor Name', 'trim|required|min_length[2]|max_length[50]');
        $this->form_validation->set_rules('mobile', 'Mobile Number', 'min_length[2]|max_length[50]|numeric');
        $this->form_validation->set_rules('email', 'Email', 'required|min_length[2]|max_length[50]|valid_email');
        $this->form_validation->set_rules('visit_unit', 'Visit Unit', 'trim|required');
        $this->form_validation->set_rules('no_of_members', 'No of Members', 'trim|required');
        $this->form_validation->set_rules('purpose_of_visit', 'Purpose of Visit', 'trim|required');
        $this->form_validation->set_rules('visiting_date', 'Visiting Date', 'trim|required');
        $this->form_validation->set_rules('parking', 'Parking', 'trim|required');
        $this->form_validation->set_rules('duration', 'Duration', 'trim|required');
        
        $image = '';
        // if (empty($_FILES['id_proof']['name'][0]))
        // {
        //     $this->form_validation->set_rules('id_proof', 'Id Proof', 'required');
        // }

        $edit = $this->xssCleanInput('visitor_id') ? $this->xssCleanInput('visitor_id') : false;
        
        if ($this->form_validation->run() === FALSE) {
            echo json_encode(array(
                'success' => 'false',
                'messages' => $this->ajaxErrorMessage(array('error' => validation_errors()))
            ));
        } 
        else {
            $imageUpload = $this->uploadImage($edit);
            if ($imageUpload['success'] == 'false') {
                echo json_encode(array(
                    'success' => 'false',
                    'messages' => $this->ajaxErrorMessage(array('error' => $imageUpload['message']))
                ));
            } else {
                if (!empty($_FILES['id_proof']['name'][0]))
                    $image = $imageUpload['message'];
                if(!$edit)
                {
                    $id = $this->AdminVisitorModel->storeVisitor($edit, $image);
                    $mailData['subscribers'] = objToArr($this->AdminVisitorModel->getVisitor('visitor_id',$id));
                   
                } else {
                    $id = $this->AdminVisitorModel->storeVisitor($edit, $image);
                    $mailData['subscribers'] = objToArr($this->AdminVisitorModel->getVisitor('visitor_id',$id));
                    
                }
                echo json_encode(array(
                    'success' => 'true',
                    'messages' => $this->ajaxErrorMessage(array('success' => lang('user').' ' . ($edit ? lang('updated') : lang('created'))))
                ));
            }
        }
    }

    /**
     * Function (for ajax) to process save entry
     *
     * @return redirect
     */
    public function saveEntry()
    {
        $this->checkIfDemo();
        $this->form_validation->set_rules('entry_time', 'Entry Time', 'trim|required');
        //$this->form_validation->set_rules('parking_ticket', 'Parking Ticket', 'trim|required');

        $edit = $this->xssCleanInput('visit_entry_id') ? $this->xssCleanInput('visit_entry_id') : false;
        

        if ($this->form_validation->run() === FALSE) {
            echo json_encode(array(
                'success' => 'false',
                'messages' => $this->ajaxErrorMessage(array('error' => validation_errors()))
            ));
        } 
        else {
            if(!$edit)
            {
                $id = $this->AdminVisitorEntryModel->storeVisitorEntry($edit);
                if($this->xssCleanInput('parking_ticket') != '')
                {
                    if($this->xssCleanInput('exit_time') == '')
                        $this->AdminVisitorEntryModel->bookParkingSlot($this->xssCleanInput('parking_ticket'), '1');
                    else
                        $this->AdminVisitorEntryModel->bookParkingSlot($this->xssCleanInput('parking_ticket'), '0');
                }
                $this->AdminVisitorModel->updateVisted($this->xssCleanInput('visitor_id'));
                
            } else {
                $id = $this->AdminVisitorEntryModel->storeVisitorEntry($edit);
                if($this->xssCleanInput('parking_ticket') != '')
                {
                    if($this->xssCleanInput('exit_time') == '')
                        $this->AdminVisitorEntryModel->bookParkingSlot($this->xssCleanInput('parking_ticket'), '1');
                    else
                        $this->AdminVisitorEntryModel->bookParkingSlot($this->xssCleanInput('parking_ticket'), '0');
                }
                
            }
            echo json_encode(array(
                'success' => 'true',
                'messages' => $this->ajaxErrorMessage(array('success' => 'Visitor Entry ' . ($edit ? lang('updated') : lang('created'))))
            ));
        }
    }

    /**
     * View Function to display subscribers list view page
     *
     * @return html/string
     */
    public function subscribersListView()
    {
        
        $this->checkAdminLogin();
        $pagedatas['subscribers'] = objToArr($this->AdminVisitorModel->subscriberList());
        $data['page'] = 'Subscribers Report';
        $data['menu'] = 'visitorlist';
        $this->load->view('admin/layout/header', $data);
        $this->load->view('admin/subscribers/list', $pagedatas);
    }

    /**
     * Function to get data for subscribers jquery datatable
     *
     * @return json
     */
    public function subscribersList()
    {
        $pagedata['subscriber']  = json_encode($this->AdminVisitorModel->subscribersList());
        $this->load->view('admin/subscribers/visitordata', $pagedata);
    }    

    /**
     * View Function to display filter entryListView search view page
     *
     * @return html/string
     */
    public function entryListView()
    {
        $this->checkAdminLogin();
        $pagedata['flats'] = objToArr($this->AdminVisitorModel->flatList());
        $data['page'] = 'Entry List Search';
        $data['menu'] = 'entry';
        $this->load->view('admin/layout/header', $data);
        $this->load->view('admin/subscribers/entrylist', $pagedata);
    }

    /**
     * Function to get data for entryList jquery datatable
     *
     * @return json
     */
    public function entryList()
    {
        echo json_encode($this->AdminVisitorEntryModel->visitentryList());
    } 

    public function entry($id = '')
    {
        $this->checkAdminLogin();
        $data['subscribers'] = objToArr($this->AdminVisitorModel->getVisitor('visitor_id',$id));
        //load the view
        $this->load->view('admin/subscribers/entry', $data, false);
    }

    public function flatList()
    {
        echo json_encode($this->AdminVisitorModel->flatList());
    }

    public function getFlatOwner($id = '')
    {
        echo json_encode($this->AdminVisitorModel->getFlatOwner('flats.flat_id',$id));
    }

    /**
     * Post Function to download candidates data in excel
     *
     * @return void
     */
    public function candidatesExcel()
    {
        $data = objToArr($this->AdminVisitorModel->getSubscribersForCSV($this->xssCleanInput('ids')));
        if(count($data) > 0)
        {
            // foreach($data as &$val)
            // {
            //     if($val['Status'] == '2')
            //     {
            //         $val['Status'] = 'Visited';
            //     } 
            //     else if($val['Status'] == '1')
            //     {
            //         $val['Status'] = 'Entered';
            //     } 
            //     else 
            //     {
            //         $val['Status'] = 'Not Visited';
            //     }
            // }
        }
        $data = sortForCSV($data);
        //print_r($data); exit;
        $excel = new SimpleExcel('csv');                    
        $excel->writer->setData($data);
        $excel->writer->saveFile('subscribers'); 
        exit;
    }

    /**
     * Post Function to download visit entry data in excel
     *
     * @return void
     */
    public function visitEntryExcel()
    {
        $data = objToArr($this->AdminVisitorEntryModel->getVisitorEntryForCSV($this->xssCleanInput('ids')));
        if(count($data) > 0)
        {
            foreach($data as &$val)
            {
                if($val['Parking Ticket'] == '')
                {
                    $val['Parking Ticket'] = 'No Parking option';
                }
                if($val['Exit Time'] == '0000-00-00 00:00:00')
                {
                    $val['Exit Time'] = 'Yet to Exit';
                }
            }
        }
        $data = sortForCSV($data);
        $excel = new SimpleExcel('csv');                    
        $excel->writer->setData($data);
        $excel->writer->saveFile('visitentries'); 
        exit;
    }

    /**
     * Function (for ajax) to process user change status request
     *
     * @param integer $user_id
     * @param string $status
     * @return void
     */
    public function changeStatus($user_id = null, $status = null)
    {
        $this->checkIfDemo();
        $this->AdminUserModel->changeStatus($user_id, $status);
    }

    /**
     * Private function to upload user image if any
     *
     * @param integer $edit
     * @return array
     */
    private function uploadImage($edit = false)
    {
        if ($_FILES['id_proof']['name'] != '') {
            $file = explode('.', $_FILES['id_proof']['name']);
            $filename = url_title(convert_accented_characters($_FILES['id_proof']['name']), 'dash', true);
            $filename .= '-' . strtotime(date('Y-m-d G:i:s'));
            $config['upload_path'] = ASSET_ROOT . '/images/subscribers/';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['file_name'] = $filename;
            $config['max_size'] = '5120';
            $this->load->library('upload', $config);
            if (!$this->upload->do_upload('id_proof')) {
                return array(
                    'success' => 'false',
                    'message' => "Only image file (gif, png or jpg) is allowed of max size 5MB"
                );
            } else {
                $data = $this->upload->data();
                return array('success' => 'true', 'message' => $data['file_name']);
            }
        }
        return array('success' => 'true', 'message' => '');
    }
    
}
