<?php

/*
 * Copyright (c) 2019 Earworks.
 * Codeigniter Project Template Modification
 * Please contact our email for more information :
 *  contact@earworks.co.id
 */
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description of Testdrive
 *
 * @author Andhy Taslin <andhy@earworks.co.id>
 * @since 1.0
 */
class Testdrive extends Base_Controller {

    public function index() {
        $this->load->template = 'main2';
        // LOGIN AKSES
        if (!$this->is_login) {
            redirect(parent::BACKOFFICE_LOGIN);
        }

        // LOAD MODEL, LIBRARY DAN HELPER
        $this->load->model(array('register_model', 'vehicle_model', 'testdrive_model'));
        $this->load->helper('form');
        $this->load->library('form_validation');
        // SET VALIDATION RULES FOR REGISTER FORM
        $this->form_validation->set_rules('visitorname', 'lang:visitorname', 'trim|required');
        $this->form_validation->set_rules('companyname', 'lang:companyname', 'trim|required');
        $this->form_validation->set_rules('vehicleid', 'lang:vehicleid', 'trim|required');

        if ($this->form_validation->run() === false) {
            // LOAD REGISTER FORM AND SEND REQUIRED DATA
            $this->load->view('testdrive/index', array(
                'register' => $this->register_model->dropdown(),
                'vehicle' => $this->vehicle_model->dropdown(array('testtype' => 3))
            ));
        } else {
            $register = $this->register_model->detail(array(
                'company' => $this->input->post('companyname', true),
                'name' => $this->input->post('visitorname', true)
            ));
            $vehicle = $this->vehicle_model->detail(array('id' => $this->input->post('vehicleid')));
            if (!$register || !$vehicle) {
                redirect('backoffice/testdrive/index');
            }
            $this->testdrive_model->insert(array(
                'registerid' => $register['id'],
                'vehicleid' =>$vehicle['id'],
                'status' => 2
            ));
            $this->register_model->update(array(
                'testdrive' => $vehicle['name'],
                'id' => $register['id']
            ));
            redirect('backoffice/testdrive/index');
        }
    }

}
