-- Tạo bảng access_log để lưu nhật ký truy cập
CREATE TABLE IF NOT EXISTS `access_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `status` enum('success','failed') NOT NULL,
  `ip` varchar(45) DEFAULT NULL,
  `user_agent` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_username` (`username`),
  KEY `idx_status` (`status`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Tạo bảng change_requests để lưu yêu cầu thay đổi thông tin
CREATE TABLE IF NOT EXISTS `change_requests` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `request_type` enum('user_info','permission','object_info') NOT NULL,
  `description` text NOT NULL,
  `changes` json DEFAULT NULL,
  `status` enum('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `approved_by` int(11) DEFAULT NULL,
  `approved_at` timestamp NULL DEFAULT NULL,
  `rejected_by` int(11) DEFAULT NULL,
  `rejected_at` timestamp NULL DEFAULT NULL,
  `rejection_reason` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_status` (`status`),
  KEY `idx_request_type` (`request_type`),
  KEY `idx_created_at` (`created_at`),
  FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE,
  FOREIGN KEY (`approved_by`) REFERENCES `user` (`id`) ON DELETE SET NULL,
  FOREIGN KEY (`rejected_by`) REFERENCES `user` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Cập nhật bảng log để có đầy đủ các trường cần thiết
ALTER TABLE `log` 
ADD COLUMN IF NOT EXISTS `userid` int(11) DEFAULT NULL AFTER `id`,
ADD COLUMN IF NOT EXISTS `username` varchar(50) DEFAULT NULL AFTER `userid`,
ADD COLUMN IF NOT EXISTS `action` varchar(50) DEFAULT NULL AFTER `username`,
ADD COLUMN IF NOT EXISTS `object_type` varchar(50) DEFAULT NULL AFTER `action`,
ADD COLUMN IF NOT EXISTS `object_id` int(11) DEFAULT NULL AFTER `object_type`,
ADD COLUMN IF NOT EXISTS `detail` text AFTER `object_id`,
ADD COLUMN IF NOT EXISTS `ip` varchar(45) DEFAULT NULL AFTER `detail`,
ADD COLUMN IF NOT EXISTS `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `ip`;

-- Thêm index cho bảng log
ALTER TABLE `log` 
ADD INDEX IF NOT EXISTS `idx_userid` (`userid`),
ADD INDEX IF NOT EXISTS `idx_action` (`action`),
ADD INDEX IF NOT EXISTS `idx_object_type` (`object_type`),
ADD INDEX IF NOT EXISTS `idx_created_at` (`created_at`);

-- Thêm foreign key cho bảng log
ALTER TABLE `log` 
ADD CONSTRAINT IF NOT EXISTS `fk_log_user` FOREIGN KEY (`userid`) REFERENCES `user` (`id`) ON DELETE SET NULL; 