-- RekodGuru Beta Email License MVP
-- Selamat dijalankan selepas 002. Tiada lesen atau aktivasi lama dipadam.
SET NAMES utf8mb4;
START TRANSACTION;

SET @sql=IF((SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='licenses' AND COLUMN_NAME='source')=0,
 'ALTER TABLE licenses ADD COLUMN source VARCHAR(40) NOT NULL DEFAULT ''LEGACY'' AFTER max_devices, ADD KEY idx_license_source(source)', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql=IF((SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='license_requests' AND COLUMN_NAME='ip_address')=0,
 'ALTER TABLE license_requests ADD COLUMN ip_address VARCHAR(45) NULL, ADD COLUMN user_agent VARCHAR(500) NULL, ADD COLUMN status VARCHAR(30) NOT NULL DEFAULT ''processed''', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

UPDATE licenses l
JOIN plans p ON p.id=l.plan_id
SET l.source='BETA_FREE'
WHERE p.code='beta' AND (l.source IS NULL OR l.source='LEGACY');

INSERT INTO system_settings(setting_key,setting_value,updated_by) VALUES
('beta_portal_enabled','true','migration-003'),
('beta_license_expiry_days','90','migration-003'),
('beta_max_devices','2','migration-003')
ON DUPLICATE KEY UPDATE setting_key=VALUES(setting_key);

COMMIT;

