-- Rainforest Pay Integration Database Tables for EasyStream
-- Run this SQL to create the necessary tables for Rainforest Pay integration

-- Donations table
CREATE TABLE IF NOT EXISTS `donations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `streamer_id` int(11) NOT NULL,
  `donor_id` int(11) DEFAULT NULL,
  `amount` decimal(10,2) NOT NULL,
  `platform_fee` decimal(10,2) NOT NULL DEFAULT 0.00,
  `streamer_amount` decimal(10,2) NOT NULL,
  `donor_name` varchar(255) DEFAULT NULL,
  `message` text DEFAULT NULL,
  `payment_method` varchar(50) NOT NULL DEFAULT 'card',
  `rainforest_payment_id` varchar(255) NOT NULL,
  `status` enum('pending','completed','failed','cancelled','refunded') NOT NULL DEFAULT 'pending',
  `rainforest_data` json DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `completed_at` timestamp NULL DEFAULT NULL,
  `failed_at` timestamp NULL DEFAULT NULL,
  `failure_reason` text DEFAULT NULL,
  `payout_id` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_streamer_id` (`streamer_id`),
  KEY `idx_donor_id` (`donor_id`),
  KEY `idx_rainforest_payment_id` (`rainforest_payment_id`),
  KEY `idx_status` (`status`),
  KEY `idx_created_at` (`created_at`),
  KEY `idx_payout_id` (`payout_id`),
  FOREIGN KEY (`streamer_id`) REFERENCES `db_accountuser` (`usr_id`) ON DELETE CASCADE,
  FOREIGN KEY (`donor_id`) REFERENCES `db_accountuser` (`usr_id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Payouts table
CREATE TABLE IF NOT EXISTS `payouts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `streamer_id` int(11) NOT NULL,
  `amount` decimal(10,2) NOT NULL,
  `fee` decimal(10,2) NOT NULL DEFAULT 0.00,
  `rainforest_payout_id` varchar(255) NOT NULL,
  `status` enum('pending','completed','failed','cancelled') NOT NULL DEFAULT 'pending',
  `rainforest_data` json DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `completed_at` timestamp NULL DEFAULT NULL,
  `failed_at` timestamp NULL DEFAULT NULL,
  `failure_reason` text DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_streamer_id` (`streamer_id`),
  KEY `idx_rainforest_payout_id` (`rainforest_payout_id`),
  KEY `idx_status` (`status`),
  KEY `idx_created_at` (`created_at`),
  FOREIGN KEY (`streamer_id`) REFERENCES `db_accountuser` (`usr_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Streamer payout settings table
CREATE TABLE IF NOT EXISTS `streamer_payout_settings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `streamer_id` int(11) NOT NULL,
  `payout_method` enum('bank_transfer','mobile_money','wallet','crypto') NOT NULL,
  `payout_details` json NOT NULL,
  `is_verified` tinyint(1) NOT NULL DEFAULT 0,
  `auto_payout` tinyint(1) NOT NULL DEFAULT 0,
  `payout_threshold` decimal(10,2) NOT NULL DEFAULT 10.00,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_streamer_id` (`streamer_id`),
  FOREIGN KEY (`streamer_id`) REFERENCES `db_accountuser` (`usr_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Donation goals table (optional feature)
CREATE TABLE IF NOT EXISTS `donation_goals` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `streamer_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `target_amount` decimal(10,2) NOT NULL,
  `current_amount` decimal(10,2) NOT NULL DEFAULT 0.00,
  `is_active` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `completed_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_streamer_id` (`streamer_id`),
  KEY `idx_is_active` (`is_active`),
  FOREIGN KEY (`streamer_id`) REFERENCES `db_accountuser` (`usr_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Transaction logs table for audit trail
CREATE TABLE IF NOT EXISTS `rainforest_transaction_logs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `transaction_type` enum('donation','payout','webhook','refund') NOT NULL,
  `transaction_id` varchar(255) NOT NULL,
  `streamer_id` int(11) DEFAULT NULL,
  `amount` decimal(10,2) DEFAULT NULL,
  `status` varchar(50) NOT NULL,
  `request_data` json DEFAULT NULL,
  `response_data` json DEFAULT NULL,
  `ip_address` varchar(45) DEFAULT NULL,
  `user_agent` text DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_transaction_type` (`transaction_type`),
  KEY `idx_transaction_id` (`transaction_id`),
  KEY `idx_streamer_id` (`streamer_id`),
  KEY `idx_created_at` (`created_at`),
  FOREIGN KEY (`streamer_id`) REFERENCES `db_accountuser` (`usr_id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Add donation balance column to existing user table
ALTER TABLE `db_accountuser` 
ADD COLUMN `donation_balance` decimal(10,2) NOT NULL DEFAULT 0.00 AFTER `usr_affiliate`,
ADD COLUMN `total_donations_received` decimal(10,2) NOT NULL DEFAULT 0.00 AFTER `donation_balance`,
ADD COLUMN `total_donations_count` int(11) NOT NULL DEFAULT 0 AFTER `total_donations_received`,
ADD COLUMN `rainforest_customer_id` varchar(255) DEFAULT NULL AFTER `total_donations_count`,
ADD INDEX `idx_donation_balance` (`donation_balance`),
ADD INDEX `idx_rainforest_customer_id` (`rainforest_customer_id`);

-- Create indexes for better performance
CREATE INDEX `idx_donations_streamer_status` ON `donations` (`streamer_id`, `status`);
CREATE INDEX `idx_donations_completed_at` ON `donations` (`completed_at`);
CREATE INDEX `idx_payouts_streamer_status` ON `payouts` (`streamer_id`, `status`);

-- Insert default donation goals (optional)
INSERT INTO `donation_goals` (`streamer_id`, `title`, `description`, `target_amount`) 
SELECT `usr_id`, 'Support My Content', 'Help me create better content for you!', 100.00 
FROM `db_accountuser` 
WHERE `usr_id` IN (1, 2, 3) -- Replace with actual streamer IDs
ON DUPLICATE KEY UPDATE `id` = `id`;

-- Create views for easy reporting
CREATE OR REPLACE VIEW `donation_summary` AS
SELECT 
    d.streamer_id,
    u.usr_user as streamer_username,
    u.usr_dname as streamer_display_name,
    COUNT(d.id) as total_donations,
    SUM(d.amount) as total_amount,
    SUM(d.streamer_amount) as total_earned,
    SUM(d.platform_fee) as total_fees,
    AVG(d.amount) as average_donation,
    MAX(d.amount) as largest_donation,
    MIN(d.created_at) as first_donation,
    MAX(d.completed_at) as latest_donation
FROM `donations` d
JOIN `db_accountuser` u ON d.streamer_id = u.usr_id
WHERE d.status = 'completed'
GROUP BY d.streamer_id;

CREATE OR REPLACE VIEW `monthly_donation_stats` AS
SELECT 
    d.streamer_id,
    u.usr_user as streamer_username,
    YEAR(d.completed_at) as year,
    MONTH(d.completed_at) as month,
    COUNT(d.id) as donations_count,
    SUM(d.amount) as total_amount,
    SUM(d.streamer_amount) as streamer_earnings,
    SUM(d.platform_fee) as platform_fees
FROM `donations` d
JOIN `db_accountuser` u ON d.streamer_id = u.usr_id
WHERE d.status = 'completed'
GROUP BY d.streamer_id, YEAR(d.completed_at), MONTH(d.completed_at)
ORDER BY year DESC, month DESC;

-- Insert sample configuration data
INSERT INTO `db_settings` (`setting_key`, `setting_value`, `setting_description`) VALUES
('rainforest_pay_enabled', '1', 'Enable Rainforest Pay integration'),
('rainforest_pay_environment', 'sandbox', 'Rainforest Pay environment (sandbox/production)'),
('rainforest_pay_min_donation', '1.00', 'Minimum donation amount'),
('rainforest_pay_max_donation', '10000.00', 'Maximum donation amount'),
('rainforest_pay_platform_fee', '2.5', 'Platform fee percentage'),
('rainforest_pay_platform_fee_fixed', '0.30', 'Fixed platform fee amount')
ON DUPLICATE KEY UPDATE `setting_value` = VALUES(`setting_value`);

-- Create triggers for automatic balance updates
DELIMITER $$

CREATE TRIGGER `update_streamer_balance_after_donation` 
AFTER UPDATE ON `donations`
FOR EACH ROW
BEGIN
    IF NEW.status = 'completed' AND OLD.status != 'completed' THEN
        UPDATE `db_accountuser` 
        SET 
            `donation_balance` = `donation_balance` + NEW.streamer_amount,
            `total_donations_received` = `total_donations_received` + NEW.amount,
            `total_donations_count` = `total_donations_count` + 1
        WHERE `usr_id` = NEW.streamer_id;
    END IF;
END$$

CREATE TRIGGER `update_streamer_balance_after_payout` 
AFTER UPDATE ON `payouts`
FOR EACH ROW
BEGIN
    IF NEW.status = 'completed' AND OLD.status != 'completed' THEN
        UPDATE `db_accountuser` 
        SET `donation_balance` = `donation_balance` - (NEW.amount + NEW.fee)
        WHERE `usr_id` = NEW.streamer_id;
    END IF;
END$$

DELIMITER ;

-- Grant necessary permissions (adjust as needed)
-- GRANT SELECT, INSERT, UPDATE ON `donations` TO 'easystream_user'@'localhost';
-- GRANT SELECT, INSERT, UPDATE ON `payouts` TO 'easystream_user'@'localhost';
-- GRANT SELECT, INSERT, UPDATE ON `streamer_payout_settings` TO 'easystream_user'@'localhost';

COMMIT;