-- ============================================================================
-- EasyStream Settings System - Complete Installation
-- Combines all settings migrations into a single installation script
-- Run this once to set up the complete settings management system
-- ============================================================================

-- ============================================================================
-- PART 1: Admin Settings
-- Adds all configurable settings to db_settings table
-- ============================================================================

-- Insert missing module settings
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('live_module', '1', 'frontend: enable/disable live streaming module'),
    ('short_module', '1', 'frontend: enable/disable shorts module'),
    ('image_module', '1', 'frontend: enable/disable images module'),
    ('audio_module', '1', 'frontend: enable/disable audio module'),
    ('document_module', '1', 'frontend: enable/disable documents module'),
    ('blog_module', '1', 'frontend: enable/disable blog module'),
    ('token_system_enabled', '1', 'frontend: enable/disable token economy system')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert branding settings
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('branding_primary_color', '#1a73e8', 'branding: primary color for UI elements'),
    ('branding_secondary_color', '#34a853', 'branding: secondary color for UI elements'),
    ('branding_logo_url', '', 'branding: URL to site logo'),
    ('branding_favicon_url', '', 'branding: URL to site favicon'),
    ('branding_footer_text', '', 'branding: custom footer text')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert PayPal settings (additional fields)
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('paypal_client_id', '', 'payment: PayPal client ID for API'),
    ('paypal_secret', '', 'payment: PayPal secret key for API')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert Stripe settings
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('stripe_enabled', '0', 'payment: enable/disable Stripe payment gateway'),
    ('stripe_publishable_key', '', 'payment: Stripe publishable key'),
    ('stripe_secret_key', '', 'payment: Stripe secret key'),
    ('stripe_webhook_secret', '', 'payment: Stripe webhook secret for event validation')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert creator payout settings
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('creator_payout_enabled', '0', 'monetization: enable/disable creator payout system'),
    ('creator_payout_percentage', '70', 'monetization: percentage of revenue that goes to creators'),
    ('minimum_payout_amount', '50.00', 'monetization: minimum balance required for payout'),
    ('payout_schedule', 'monthly', 'monetization: payout frequency (weekly, monthly, quarterly, manual)'),
    ('payout_method', 'paypal', 'monetization: default payout method (paypal, stripe, bank_transfer)')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert token settings (additional)
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('token_name', 'Tokens', 'token: display name for tokens'),
    ('token_symbol', 'TKN', 'token: short symbol for tokens'),
    ('token_color', '#FFD700', 'token: color for token UI elements'),
    ('token_icon_url', '', 'token: URL to custom token icon')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert security/privacy settings (update existing)
UPDATE `db_settings` SET `cfg_info` = 'security: minimum age required for signup' WHERE `cfg_name` = 'signup_min_age';
UPDATE `db_settings` SET `cfg_info` = 'security: maximum age allowed for signup' WHERE `cfg_name` = 'signup_max_age';
UPDATE `db_settings` SET `cfg_info` = 'security: minimum password length' WHERE `cfg_name` = 'signup_min_password';
UPDATE `db_settings` SET `cfg_info` = 'security: maximum password length' WHERE `cfg_name` = 'signup_max_password';
UPDATE `db_settings` SET `cfg_info` = 'security: minimum username length' WHERE `cfg_name` = 'signup_min_username';
UPDATE `db_settings` SET `cfg_info` = 'security: maximum username length' WHERE `cfg_name` = 'signup_max_username';
UPDATE `db_settings` SET `cfg_info` = 'security: username format (strict/relaxed)' WHERE `cfg_name` = 'username_format';
UPDATE `db_settings` SET `cfg_info` = 'security: enable/disable remember me feature' WHERE `cfg_name` = 'login_remember';

-- Insert SEO settings (update existing)
UPDATE `db_settings` SET `cfg_info` = 'seo: site title for browser tabs and search' WHERE `cfg_name` = 'head_title';
UPDATE `db_settings` SET `cfg_info` = 'seo: meta description for search engines' WHERE `cfg_name` = 'metaname_description';
UPDATE `db_settings` SET `cfg_info` = 'seo: meta keywords for search engines' WHERE `cfg_name` = 'metaname_keywords';
UPDATE `db_settings` SET `cfg_info` = 'seo: website short name' WHERE `cfg_name` = 'website_shortname';

-- Insert email settings (update existing descriptions)
UPDATE `db_settings` SET `cfg_info` = 'email: mailer type (smtp/mail)' WHERE `cfg_name` = 'mail_type';
UPDATE `db_settings` SET `cfg_info` = 'email: from email address' WHERE `cfg_name` = 'backend_email';
UPDATE `db_settings` SET `cfg_info` = 'email: from name in emails' WHERE `cfg_name` = 'backend_email_fromname';
UPDATE `db_settings` SET `cfg_info` = 'email: SMTP server hostname' WHERE `cfg_name` = 'mail_smtp_host';
UPDATE `db_settings` SET `cfg_info` = 'email: SMTP server port' WHERE `cfg_name` = 'mail_smtp_port';
UPDATE `db_settings` SET `cfg_info` = 'email: SMTP username' WHERE `cfg_name` = 'mail_smtp_username';
UPDATE `db_settings` SET `cfg_info` = 'email: SMTP password' WHERE `cfg_name` = 'mail_smtp_password';
UPDATE `db_settings` SET `cfg_info` = 'email: SMTP authentication enabled' WHERE `cfg_name` = 'mail_smtp_auth';
UPDATE `db_settings` SET `cfg_info` = 'email: SMTP encryption (tls/ssl)' WHERE `cfg_name` = 'mail_smtp_prefix';

-- Insert additional system settings
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('cookie_domain', '.localhost', 'system: cookie domain for authentication'),
    ('cookie_validation', '0', 'system: enable/disable cookie validation (beta)'),
    ('main_url', 'http://localhost:8083', 'system: main website URL'),
    ('debug_mode', '0', 'system: enable/disable debug mode'),
    ('site_maintenance', '0', 'system: enable/disable maintenance mode'),
    ('site_maintenance_message', 'Site is under maintenance. Please check back later.', 'system: maintenance mode message')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert content moderation settings
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('video_approval_required', '0', 'moderation: require admin approval for videos'),
    ('live_approval_required', '0', 'moderation: require admin approval for live streams'),
    ('blog_approval_required', '0', 'moderation: require admin approval for blogs'),
    ('auto_approve_verified_users', '1', 'moderation: auto-approve content from verified users'),
    ('enable_content_reporting', '1', 'moderation: allow users to report content')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert social media integration settings
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('fb_app_id', '', 'social: Facebook app ID for login'),
    ('fb_app_secret', '', 'social: Facebook app secret'),
    ('google_client_id', '', 'social: Google OAuth client ID'),
    ('google_client_secret', '', 'social: Google OAuth client secret'),
    ('twitter_api_key', '', 'social: Twitter API key'),
    ('twitter_api_secret', '', 'social: Twitter API secret')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert file upload settings
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('max_video_size_mb', '500', 'upload: maximum video file size in MB'),
    ('max_image_size_mb', '10', 'upload: maximum image file size in MB'),
    ('max_audio_size_mb', '50', 'upload: maximum audio file size in MB'),
    ('max_document_size_mb', '20', 'upload: maximum document file size in MB'),
    ('allowed_video_formats', 'mp4,mov,avi,mkv,webm', 'upload: allowed video file formats'),
    ('allowed_image_formats', 'jpg,jpeg,png,gif,webp', 'upload: allowed image file formats'),
    ('allowed_audio_formats', 'mp3,wav,ogg,m4a', 'upload: allowed audio file formats'),
    ('allowed_document_formats', 'pdf,doc,docx,txt', 'upload: allowed document file formats')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert analytics settings
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('google_analytics_id', '', 'analytics: Google Analytics tracking ID'),
    ('enable_analytics', '1', 'analytics: enable/disable analytics tracking'),
    ('track_user_activity', '1', 'analytics: track user activity logs')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Insert notification settings
INSERT INTO `db_settings` (`cfg_name`, `cfg_data`, `cfg_info`)
VALUES
    ('email_notifications_enabled', '1', 'notifications: enable/disable email notifications'),
    ('notify_new_user_signup', '1', 'notifications: notify admin of new user signups'),
    ('notify_new_content_upload', '0', 'notifications: notify admin of new content uploads'),
    ('notify_content_flagged', '1', 'notifications: notify admin when content is flagged')
ON DUPLICATE KEY UPDATE cfg_info = VALUES(cfg_info);

-- Create index on cfg_name for faster lookups
CREATE INDEX IF NOT EXISTS idx_cfg_name ON db_settings(cfg_name);

-- ============================================================================
-- PART 2: Settings Audit Trail
-- Adds history tracking for all settings changes
-- ============================================================================

-- Create settings history table
CREATE TABLE IF NOT EXISTS `db_settings_history` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `cfg_name` varchar(50) NOT NULL,
  `old_value` text DEFAULT NULL,
  `new_value` text NOT NULL,
  `changed_by` int(10) UNSIGNED DEFAULT NULL,
  `changed_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ip_address` varchar(45) NOT NULL,
  `user_agent` varchar(255) NOT NULL,
  `change_reason` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_cfg_name` (`cfg_name`),
  KEY `idx_changed_at` (`changed_at`),
  KEY `idx_changed_by` (`changed_by`),
  FOREIGN KEY (`changed_by`) REFERENCES `db_accountuser`(`usr_id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;

-- Add composite index for faster history queries
CREATE INDEX IF NOT EXISTS `idx_cfg_name_date` ON `db_settings_history` (`cfg_name`, `changed_at` DESC);

-- ============================================================================
-- Installation Complete
-- ============================================================================

SELECT 'Settings system installation completed successfully!' AS message;
SELECT COUNT(*) AS total_settings FROM db_settings;
SELECT 'Settings audit trail table created' AS audit_status;
