-- Create referrals table
CREATE TABLE IF NOT EXISTS `referrals` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `referrerId` INT NOT NULL,
  `referrerType` ENUM('customer', 'supplier') NOT NULL,
  `referredCustomerId` INT NOT NULL,
  `referralCode` VARCHAR(50) NOT NULL UNIQUE,
  `status` ENUM('pending', 'active', 'completed', 'cancelled') DEFAULT 'pending',
  `totalEarnings` DECIMAL(10, 2) DEFAULT 0,
  `totalOrders` INT DEFAULT 0,
  `totalOrderValue` DECIMAL(10, 2) DEFAULT 0,
  `commissionRate` DECIMAL(5, 2) DEFAULT 0,
  `firstOrderCompleted` BOOLEAN DEFAULT FALSE,
  `firstOrderRewardPaid` BOOLEAN DEFAULT FALSE,
  `createdAt` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updatedAt` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `idx_referrer` (`referrerId`),
  INDEX `idx_referred_customer` (`referredCustomerId`),
  INDEX `idx_referral_code` (`referralCode`),
  FOREIGN KEY (`referrerId`) REFERENCES `users`(`id`) ON DELETE CASCADE,
  FOREIGN KEY (`referredCustomerId`) REFERENCES `users`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create referral_rewards table
CREATE TABLE IF NOT EXISTS `referral_rewards` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `referralId` INT NOT NULL,
  `orderId` INT NULL,
  `rewardType` ENUM('first_order', 'commission', 'bonus') NOT NULL,
  `orderAmount` DECIMAL(10, 2) NOT NULL,
  `commissionRate` DECIMAL(5, 2) NOT NULL,
  `rewardAmount` DECIMAL(10, 2) NOT NULL,
  `status` ENUM('pending', 'paid', 'cancelled') DEFAULT 'pending',
  `paidAt` DATETIME NULL,
  `paidToWallet` BOOLEAN DEFAULT FALSE,
  `notes` TEXT NULL,
  `createdAt` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updatedAt` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `idx_referral` (`referralId`),
  INDEX `idx_order` (`orderId`),
  INDEX `idx_status` (`status`),
  FOREIGN KEY (`referralId`) REFERENCES `referrals`(`id`) ON DELETE CASCADE,
  FOREIGN KEY (`orderId`) REFERENCES `orders`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Add referralCode column to users table (to store user's referral code)
-- Check if column exists first to avoid errors
SET @column_exists = (
  SELECT COUNT(*) 
  FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE TABLE_SCHEMA = DATABASE() 
  AND TABLE_NAME = 'users' 
  AND COLUMN_NAME = 'referralCode'
);

SET @sql = IF(@column_exists = 0,
  'ALTER TABLE `users` ADD COLUMN `referralCode` VARCHAR(50) NULL UNIQUE AFTER `contactNumber`, ADD INDEX `idx_referral_code` (`referralCode`)',
  'SELECT "referralCode column already exists" AS message'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Add referredByCode column to users table (to track who referred this user)
SET @column_exists = (
  SELECT COUNT(*) 
  FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE TABLE_SCHEMA = DATABASE() 
  AND TABLE_NAME = 'users' 
  AND COLUMN_NAME = 'referredByCode'
);

SET @sql = IF(@column_exists = 0,
  'ALTER TABLE `users` ADD COLUMN `referredByCode` VARCHAR(50) NULL AFTER `referralCode`, ADD INDEX `idx_referred_by_code` (`referredByCode`)',
  'SELECT "referredByCode column already exists" AS message'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

