<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Version_109 extends CI_Migration{

	public function up() {
		
		//fix old CRMs
		$table_name = 'tbluser_auto_login';
		$column_name = 'key_id';

		$query = $this->db->query("DESCRIBE `$table_name` `$column_name`");

		if ($query->num_rows() > 0) {
		$column_info = $query->row();
		if ($column_info->Type == 'int(11)') {
			
			$fields = array(
			'key_id' => array(
				'type' => 'CHAR',
  				'constraint' => 32,
  				'null' => FALSE,
				),
			);
			$this->dbforge->modify_column('user_auto_login', $fields);
		}
		else {
			// Column is not of type INT
			// Do something else here
		}
		}
		else {
		// Column does not exist in table
		// Do something else here
		}


		/*
		$query = $this->db->query("SHOW INDEX FROM `$table_name` WHERE Key_name = 'PRIMARY' AND Column_name = '$primary_key_name'");
		if ($query->num_rows() == 1) {
			$this->db->query("ALTER TABLE `$table_name` CHANGE `$primary_key_name` `$primary_key_name` INT(11) NOT NULL");
			$this->db->query("ALTER TABLE `$table_name` DROP PRIMARY KEY");
		}
		*/

		//$this->db->query("ALTER TABLE `tbluser_auto_login` CHANGE `key_id` `key_id` INT(11) NOT NULL");
		//$this->db->query("ALTER TABLE `tbluser_auto_login` DROP PRIMARY KEY");

		$this->dbforge->add_column('leads', array(
			'date_opportunity' => array(
				'type' => 'DATETIME',
  				'null' => TRUE,
  				'default' => NULL,
				'after' => 'phonenumber',
			)
		));
		$this->dbforge->add_column('contacts', array(
			'id_position' => array(
				'type' => 'INT',
				'constraint' => 11,
  				'null' => TRUE,
  				'default' => NULL,
				'after' => 'title',
			)
		));


		$this->dbforge->add_column('staff', array(
			'identity_document' => array(
				'type' => 'VARCHAR',
				'constraint' => 25,
  				'null' => TRUE,
  				'default' => NULL,
				'after' => 'lastname',
			)
		));
		
	 }

	public function down()	{

		/*
		$fields = array(
			'key_id' => array(
				'type' => 'int',
				'constraint' => 11,
				'null' => false,
				),
		);
		$this->dbforge->modify_column('user_auto_login', $fields);
		$table_name = 'tbluser_auto_login';
		$primary_key_name = 'key_id';
		$query = $this->db->query("SHOW INDEX FROM `$table_name` WHERE Key_name = 'PRIMARY' AND Column_name = '$primary_key_name'");
		if ($query->num_rows() == 0) {
			$this->db->query(add_pk($table_name,$primary_key_name));
		} */
		//$this->db->query(add_pk('tbluser_auto_login','key_id'));
		$this->dbforge->drop_column('leads', "date_opportunity");
		$this->dbforge->drop_column('contacts', "id_position");
		$this->dbforge->drop_column('staff', "identity_document");

	}
}
