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

class Migration_Create_user_logins_table extends CI_Migration {

    public function up() {
        // User logins table for tracking login history
        $this->dbforge->add_field(array(
            'id' => array(
                'type' => 'INT',
                'constraint' => 11,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ),
            'user_id' => array(
                'type' => 'INT',
                'constraint' => 11,
                'unsigned' => TRUE
            ),
            'login_time' => array(
                'type' => 'DATETIME',
                'default' => 'CURRENT_TIMESTAMP'
            ),
            'ip_address' => array(
                'type' => 'VARCHAR',
                'constraint' => '45',
                'null' => TRUE
            ),
            'user_agent' => array(
                'type' => 'TEXT',
                'null' => TRUE
            ),
            'session_id' => array(
                'type' => 'VARCHAR',
                'constraint' => '255',
                'null' => TRUE
            )
        ));
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->add_key('user_id');
        $this->dbforge->create_table('user_logins');
        
        // Add foreign key
        $this->db->query('ALTER TABLE `user_logins` ADD CONSTRAINT `fk_user_logins_user` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE');
        
        // Add indexes for performance
        $this->db->query('CREATE INDEX idx_user_login_time ON user_logins(user_id, login_time DESC)');
    }

    public function down() {
        $this->dbforge->drop_table('user_logins');
    }
}
