<?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_model
 *
 * @author Fajar Dwi Rianto <fajar@earworks.co.id>
 * @since 1.0
 */
class Testdrive_model extends CI_Model {

    const TABLE = 'testdrive';

    public function check($input = array()) {
        $this->db->from(self::TABLE);
        if (isset($input['id']) && !empty($input['id'])) {
            $this->db->where('id', $input['id']);
        }
        if (isset($input['registerid']) && !empty($input['registerid'])) {
            $this->db->where('registerid', $input['registerid']);
        }
        if (isset($input['vehicleid']) && !empty($input['vehicleid'])) {
            $this->db->where('vehicleid', $input['vehicleid']);
        }
        return $this->db->count_all_results();
    }

    public function get($input = array()) {
        $select = array(
            'testdrive.id', 'testdrive.status', 'register.id as registerid', 'vehicle.id as vehicleid',
            'register.name', 'register.company', 'vehicle.name',
        );
        $this->db->select(implode(', ', $select));
        $this->db->from(self::TABLE);
        $this->db->join('register', 'testdrive.registerid = register.id', 'left');
        $this->db->join('vehicle', 'testdrive.vehicleid = vehicle.id', 'left');
        if (isset($input['registerid']) && !empty($input['registerid'])) {
            $this->db->where('register.id', $input['registerid']);
        }
        if (isset($input['vehicleid']) && !empty($input['vehicleid'])) {
            $this->db->where('vehicle.id', $input['vehicleid']);
        }
        $query = $this->db->get();
        return $query->result_array();
    }

    public function insert($input = array(), $return_id = false) {
        $user = $this->session->userdata(CI_NAME . 'log');
        $insert = array();
        if (isset($input['registerid']) && !empty($input['registerid'])) {
            $insert['registerid'] = $input['registerid'];
        }
        if (isset($input['vehicleid']) && !empty($input['vehicleid'])) {
            $insert['vehicleid'] = $input['vehicleid'];
        }
        if (isset($input['status']) && !empty($input['status'])) {
            $insert['status'] = $input['status'];
        }
        $insert['created'] = time();
        $insert['modified'] = time();
        $insert['createdby'] = $user['userid'];
        $insert['modifiedby'] = $user['userid'];
        $res = $this->db->insert(self::TABLE, $insert);
        return ($return_id === true) ? $this->db->insert_id() : $res;
    }

}
