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

class Migration_Create_chat extends CI_Migration
{
	public function up()
	{
		if (!$this->db->table_exists('chat_messages')) {
			$this->db->query("CREATE TABLE `chat_messages` (
				`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
				`sender_id` INT NOT NULL,
				`receiver_id` INT NOT NULL,
				`message` TEXT NOT NULL,
				`attachment_path` VARCHAR(255) NULL,
				`attachment_name` VARCHAR(255) NULL,
				`attachment_mime` VARCHAR(100) NULL,
				`attachment_size` INT UNSIGNED NULL,
				`attachment_type` ENUM('image','file') NULL,
				`created_at` DATETIME NOT NULL,
				`delivered_at` DATETIME NULL,
				`read_at` DATETIME NULL,
				PRIMARY KEY (`id`),
				KEY `idx_chat_sender_receiver_id` (`sender_id`,`receiver_id`,`id`),
				KEY `idx_chat_receiver_read` (`receiver_id`,`read_at`,`id`)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
		}

		if (!$this->db->table_exists('chat_typing')) {
			$this->db->query("CREATE TABLE `chat_typing` (
				`user_id` INT NOT NULL,
				`receiver_id` INT NOT NULL,
				`expires_at` DATETIME NOT NULL,
				PRIMARY KEY (`user_id`,`receiver_id`),
				KEY `idx_chat_typing_receiver` (`receiver_id`,`expires_at`)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
		}
		if ($this->db->table_exists('info') && !$this->db->field_exists('chat_aktif', 'info')) {
			$this->dbforge->add_column('info', array('chat_aktif'=>array('type'=>'TINYINT','constraint'=>1,'null'=>FALSE,'default'=>1)));
		}
		if ($this->db->table_exists('info') && !$this->db->field_exists('chat_suara', 'info')) {
			$this->dbforge->add_column('info', array('chat_suara'=>array('type'=>'VARCHAR','constraint'=>20,'null'=>FALSE,'default'=>'classic')));
		}
	}

	public function down()
	{
		$this->dbforge->drop_table('chat_typing', TRUE);
		$this->dbforge->drop_table('chat_messages', TRUE);
	}
}
