-- ======================================================
-- INSTALAÇÃO COMPLETA — SISTEMA DE RIFA + LEILÃO + MLM
-- Versão Consolidada v2.0
-- Execute este arquivo no phpMyAdmin ou linha de comando:
--   mysql -u usuario -p nome_banco < instalar_completo.sql
-- ======================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ════════════════════════════════════════════════════════
-- MÓDULO 1: CARTEIRA (WALLET)
-- ════════════════════════════════════════════════════════

CREATE TABLE IF NOT EXISTS `wallet` (
  `id`                   INT           NOT NULL AUTO_INCREMENT,
  `customer_id`          INT           NOT NULL,
  `balance_available`    DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `balance_pending`      DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `balance_total_earned` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `updated_at`           DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP
                         ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_customer` (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `wallet_transactions` (
  `id`             INT          NOT NULL AUTO_INCREMENT,
  `customer_id`    INT          NOT NULL,
  `type`           ENUM(
                     'deposit','yield','binary_bonus','unilevel_bonus',
                     'auction_prize','raffle_prize','bid_cost',
                     'investment','withdrawal','upgrade','adjustment'
                   ) NOT NULL,
  `amount`         DECIMAL(12,2) NOT NULL,
  `balance_before` DECIMAL(12,2) DEFAULT NULL,
  `balance_after`  DECIMAL(12,2) DEFAULT NULL,
  `description`    VARCHAR(500)  DEFAULT NULL,
  `reference_id`   INT           DEFAULT NULL,
  `reference_type` VARCHAR(50)   DEFAULT NULL,
  `created_at`     DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_customer`   (`customer_id`),
  KEY `idx_type`       (`type`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ════════════════════════════════════════════════════════
-- MÓDULO 2: DEPÓSITOS PIX
-- ════════════════════════════════════════════════════════

CREATE TABLE IF NOT EXISTS `deposits` (
  `id`               INT           NOT NULL AUTO_INCREMENT,
  `customer_id`      INT           NOT NULL,
  `amount`           DECIMAL(12,2) NOT NULL,
  `status`           TINYINT       NOT NULL DEFAULT 1
                     COMMENT '1=pendente 2=confirmado 3=cancelado/expirado',
  `payment_method`   VARCHAR(100)  DEFAULT NULL,
  `pix_code`         TEXT          DEFAULT NULL,
  `pix_qrcode`       TEXT          DEFAULT NULL,
  `id_mp`            VARCHAR(255)  DEFAULT NULL
                     COMMENT 'ID externo do gateway (OpenPix, MP, etc)',
  `txid`             VARCHAR(255)  DEFAULT NULL,
  `order_expiration` INT           NOT NULL DEFAULT 30
                     COMMENT 'Minutos para expirar',
  `confirmed_at`     DATETIME      DEFAULT NULL,
  `created_at`       DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_customer`   (`customer_id`),
  KEY `idx_status`     (`status`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ════════════════════════════════════════════════════════
-- MÓDULO 3: SAQUES
-- ════════════════════════════════════════════════════════

CREATE TABLE IF NOT EXISTS `withdrawals` (
  `id`           INT           NOT NULL AUTO_INCREMENT,
  `customer_id`  INT           NOT NULL,
  `amount`       DECIMAL(12,2) NOT NULL,
  `fee`          DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `amount_net`   DECIMAL(12,2) GENERATED ALWAYS AS (`amount` - `fee`) STORED,
  `status`       TINYINT       NOT NULL DEFAULT 1
                 COMMENT '1=pendente 2=aprovado 3=recusado',
  `pix_key`      VARCHAR(255)  DEFAULT NULL,
  `pix_key_type` VARCHAR(50)   DEFAULT NULL
                 COMMENT 'cpf | telefone | email | aleatorio | cnpj',
  `admin_note`   TEXT          DEFAULT NULL,
  `approved_at`  DATETIME      DEFAULT NULL,
  `created_at`   DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_customer`   (`customer_id`),
  KEY `idx_status`     (`status`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ════════════════════════════════════════════════════════
-- MÓDULO 4: INVESTIMENTOS
-- ════════════════════════════════════════════════════════

CREATE TABLE IF NOT EXISTS `investment_plans` (
  `id`               INT          NOT NULL AUTO_INCREMENT,
  `name`             VARCHAR(100) NOT NULL,
  `description`      VARCHAR(255) DEFAULT NULL,
  `min_amount`       DECIMAL(12,2) NOT NULL,
  `max_amount`       DECIMAL(12,2) NOT NULL DEFAULT 0.00
                     COMMENT '0 = ilimitado',
  `daily_rate`       DECIMAL(6,3) NOT NULL
                     COMMENT 'Percentual diário. Ex: 3.00 = 3%',
  `cap_percent`      DECIMAL(6,2) NOT NULL DEFAULT 200.00
                     COMMENT 'Teto do ganho em %. Ex: 200 = dobra o capital',
  `icon`             VARCHAR(20)  NOT NULL DEFAULT '💎',
  `color`            VARCHAR(20)  NOT NULL DEFAULT '#6c5ce7',
  `sort_order`       INT          NOT NULL DEFAULT 0,
  `is_active`        TINYINT      NOT NULL DEFAULT 1,
  `featured`         TINYINT      NOT NULL DEFAULT 0,
  `allow_multiple`   TINYINT      NOT NULL DEFAULT 0
                     COMMENT '1 = usuário pode ter mais de uma instância deste plano',
  `created_at`       DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Planos padrão (ajuste conforme necessário)
INSERT IGNORE INTO `investment_plans`
  (`name`,`description`,`min_amount`,`max_amount`,`daily_rate`,`cap_percent`,`icon`,`color`,`sort_order`,`featured`)
VALUES
  ('Plano Bronze',  'Ideal para iniciantes',   50.00,   499.00, 1.50, 200.00, '🥉', '#cd7f32', 1, 0),
  ('Plano Prata',   'Ótimo custo-benefício',  500.00,  1499.00, 2.00, 200.00, '🥈', '#9b9b9b', 2, 1),
  ('Plano Ouro',    'Alto rendimento',        1500.00, 4999.00, 2.50, 200.00, '🥇', '#e2b53e', 3, 0),
  ('Plano Diamante','Máximo retorno',         5000.00,     0.00, 3.00, 200.00, '💎', '#00cec9', 4, 0);

CREATE TABLE IF NOT EXISTS `investments` (
  `id`              INT           NOT NULL AUTO_INCREMENT,
  `customer_id`     INT           NOT NULL,
  `plan_id`         INT           NOT NULL,
  `amount_invested` DECIMAL(12,2) NOT NULL,
  `amount_earned`   DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `cap_percent`     DECIMAL(6,2)  NOT NULL DEFAULT 200.00,
  `cap_limit`       DECIMAL(12,2) NOT NULL
                    COMMENT 'Valor absoluto do teto = amount_invested * cap_percent / 100',
  `daily_rate`      DECIMAL(6,3)  NOT NULL,
  `status`          TINYINT       NOT NULL DEFAULT 1
                    COMMENT '1=ativo 2=concluído 3=cancelado',
  `last_yield_at`   DATETIME      DEFAULT NULL,
  `ended_at`        DATETIME      DEFAULT NULL,
  `created_at`      DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_customer` (`customer_id`),
  KEY `idx_plan`     (`plan_id`),
  KEY `idx_status`   (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `investment_yields` (
  `id`            INT           NOT NULL AUTO_INCREMENT,
  `investment_id` INT           NOT NULL,
  `customer_id`   INT           NOT NULL,
  `amount`        DECIMAL(12,2) NOT NULL,
  `day_number`    INT           NOT NULL DEFAULT 1,
  `created_at`    DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_investment` (`investment_id`),
  KEY `idx_customer`   (`customer_id`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ════════════════════════════════════════════════════════
-- MÓDULO 5: REDE MLM — BINÁRIO + UNILEVEL
-- ════════════════════════════════════════════════════════

CREATE TABLE IF NOT EXISTS `binary_tree` (
  `id`                  INT           NOT NULL AUTO_INCREMENT,
  `customer_id`         INT           NOT NULL,
  `sponsor_id`          INT           DEFAULT NULL
                        COMMENT 'Quem indicou (upline direto)',
  `parent_id`           INT           DEFAULT NULL
                        COMMENT 'Pai na árvore binária (pode ser diferente do sponsor)',
  `side`                ENUM('left','right') DEFAULT NULL,
  `left_id`             INT           DEFAULT NULL,
  `right_id`            INT           DEFAULT NULL,
  `left_volume`         DECIMAL(14,2) NOT NULL DEFAULT 0.00,
  `right_volume`        DECIMAL(14,2) NOT NULL DEFAULT 0.00,
  `total_binary_earned` DECIMAL(14,2) NOT NULL DEFAULT 0.00,
  `created_at`          DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_customer` (`customer_id`),
  KEY `idx_sponsor` (`sponsor_id`),
  KEY `idx_parent`  (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `binary_bonuses` (
  `id`                INT           NOT NULL AUTO_INCREMENT,
  `customer_id`       INT           NOT NULL,
  `weak_side_volume`  DECIMAL(12,2) NOT NULL,
  `bonus_rate`        DECIMAL(5,2)  NOT NULL,
  `amount`            DECIMAL(12,2) NOT NULL,
  `left_volume_used`  DECIMAL(12,2) NOT NULL,
  `right_volume_used` DECIMAL(12,2) NOT NULL,
  `created_at`        DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_customer`   (`customer_id`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `unilevel_rates` (
  `level` TINYINT       NOT NULL,
  `rate`  DECIMAL(5,2)  NOT NULL,
  PRIMARY KEY (`level`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Taxas padrão — ajuste pelo painel Admin > Rede MLM
INSERT IGNORE INTO `unilevel_rates` (`level`,`rate`) VALUES
  (1, 10.00),
  (2,  5.00),
  (3,  3.00),
  (4,  2.00),
  (5,  1.00),
  (6,  1.00),
  (7,  0.50),
  (8,  0.50),
  (9,  0.50),
  (10, 0.50);

CREATE TABLE IF NOT EXISTS `unilevel_commissions` (
  `id`                 INT           NOT NULL AUTO_INCREMENT,
  `beneficiary_id`     INT           NOT NULL,
  `origin_customer_id` INT           NOT NULL,
  `investment_id`      INT           DEFAULT NULL,
  `level`              TINYINT       NOT NULL,
  `rate`               DECIMAL(5,2)  NOT NULL,
  `base_amount`        DECIMAL(12,2) NOT NULL,
  `commission_amount`  DECIMAL(12,2) NOT NULL,
  `created_at`         DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_beneficiary`   (`beneficiary_id`),
  KEY `idx_origin`        (`origin_customer_id`),
  KEY `idx_investment`    (`investment_id`),
  KEY `idx_created_at`    (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ════════════════════════════════════════════════════════
-- MÓDULO 6: LEILÃO DE CENTAVOS
-- ════════════════════════════════════════════════════════

CREATE TABLE IF NOT EXISTS `auction_list` (
  `id`              INT           NOT NULL AUTO_INCREMENT,
  `name`            VARCHAR(255)  NOT NULL,
  `description`     TEXT          DEFAULT NULL,
  `image_path`      VARCHAR(500)  DEFAULT NULL,
  `slug`            VARCHAR(255)  DEFAULT NULL
                    COMMENT 'URL amigável gerada automaticamente',
  `real_value`      DECIMAL(10,2) NOT NULL DEFAULT 0.00
                    COMMENT 'Valor de mercado do produto',
  `start_price`     DECIMAL(10,4) NOT NULL DEFAULT 0.0100,
  `current_price`   DECIMAL(10,4) NOT NULL DEFAULT 0.0100,
  `bid_increment`   DECIMAL(10,4) NOT NULL DEFAULT 0.0100,
  `bid_credit_cost` INT           NOT NULL DEFAULT 1
                    COMMENT 'Créditos de lance consumidos por bid',
  `timer_seconds`   INT           NOT NULL DEFAULT 30
                    COMMENT 'Segundos que o timer reinicia a cada lance',
  `timer_reset_at`  DATETIME      DEFAULT NULL,
  `phase`           TINYINT       NOT NULL DEFAULT 1
                    COMMENT '1=crescimento (timer nunca zera) | 2=real (pode zerar e encerrar)',
  `phase2_trigger`  DECIMAL(10,2) DEFAULT NULL
                    COMMENT 'Receita (R$) para mudar para Fase 2. NULL=sempre Fase 2',
  `total_bids`      INT           NOT NULL DEFAULT 0,
  `total_revenue`   DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `last_bidder_id`  INT           DEFAULT NULL,
  `winner_id`       INT           DEFAULT NULL,
  `status`          TINYINT       NOT NULL DEFAULT 1
                    COMMENT '1=em breve | 2=ativo | 3=encerrado',
  `featured`        TINYINT       NOT NULL DEFAULT 0,
  `created_at`      DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_slug` (`slug`),
  KEY `idx_status`  (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `auction_bids` (
  `id`           INT           NOT NULL AUTO_INCREMENT,
  `auction_id`   INT           NOT NULL,
  `customer_id`  INT           DEFAULT NULL
                 COMMENT 'NULL = lance simulado (prova social)',
  `price_at_bid` DECIMAL(10,4) NOT NULL,
  `is_simulated` TINYINT       NOT NULL DEFAULT 0,
  `created_at`   DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_auction`    (`auction_id`),
  KEY `idx_customer`   (`customer_id`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `bid_credits` (
  `id`          INT      NOT NULL AUTO_INCREMENT,
  `customer_id` INT      NOT NULL,
  `credits`     INT      NOT NULL DEFAULT 0,
  `updated_at`  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
                ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_customer` (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `bid_packages` (
  `id`          INT           NOT NULL AUTO_INCREMENT,
  `name`        VARCHAR(100)  NOT NULL,
  `credits`     INT           NOT NULL,
  `price`       DECIMAL(10,2) NOT NULL,
  `is_featured` TINYINT       NOT NULL DEFAULT 0,
  `is_active`   TINYINT       NOT NULL DEFAULT 1,
  `sort_order`  INT           NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT IGNORE INTO `bid_packages` (`name`,`credits`,`price`,`is_featured`,`sort_order`) VALUES
  ('Starter',   10,   4.90, 0, 1),
  ('Popular',   30,  12.90, 1, 2),
  ('Pro',      100,  39.90, 0, 3),
  ('Ultra',    300,  99.90, 0, 4),
  ('Elite',   1000, 299.90, 0, 5);

CREATE TABLE IF NOT EXISTS `bid_package_orders` (
  `id`             INT           NOT NULL AUTO_INCREMENT,
  `customer_id`    INT           NOT NULL,
  `package_id`     INT           DEFAULT NULL,
  `credits_qty`    INT           NOT NULL,
  `amount`         DECIMAL(10,2) NOT NULL,
  `status`         TINYINT       NOT NULL DEFAULT 1
                   COMMENT '1=pendente 2=pago 3=cancelado',
  `payment_method` VARCHAR(100)  DEFAULT NULL,
  `pix_code`       TEXT          DEFAULT NULL,
  `pix_qrcode`     TEXT          DEFAULT NULL,
  `id_mp`          VARCHAR(255)  DEFAULT NULL,
  `txid`           VARCHAR(255)  DEFAULT NULL,
  `created_at`     DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_customer`   (`customer_id`),
  KEY `idx_status`     (`status`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ════════════════════════════════════════════════════════
-- MÓDULO 7: PROVA SOCIAL + FILA DE NOTIFICAÇÕES
-- ════════════════════════════════════════════════════════

CREATE TABLE IF NOT EXISTS `social_proof_names` (
  `id`   INT          NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `city` VARCHAR(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT IGNORE INTO `social_proof_names` (`name`,`city`) VALUES
  ('Carlos S.','São Paulo'),   ('Ana L.','Rio de Janeiro'),
  ('Marcos F.','Belo Horizonte'),('Juliana R.','Curitiba'),
  ('Pedro M.','Salvador'),     ('Fernanda C.','Fortaleza'),
  ('Lucas O.','Manaus'),       ('Camila T.','Recife'),
  ('Rafael B.','Porto Alegre'),('Beatriz N.','Goiânia'),
  ('Thiago A.','Brasília'),    ('Larissa M.','Florianópolis'),
  ('Diego V.','Belém'),        ('Isabela C.','Campo Grande'),
  ('Rodrigo L.','Natal'),      ('Priscila S.','Teresina'),
  ('Gustavo P.','São Luís'),   ('Vanessa F.','Maceió'),
  ('Henrique D.','João Pessoa'),('Aline K.','Macapá'),
  ('Bruno T.','Vitória'),      ('Mariana O.','Cuiabá'),
  ('Felipe A.','Porto Velho'), ('Cintia B.','Macapá'),
  ('Samuel R.','Palmas'),      ('Elaine F.','Rio Branco');

CREATE TABLE IF NOT EXISTS `notification_queue` (
  `id`            INT          NOT NULL AUTO_INCREMENT,
  `customer_id`   INT          NOT NULL,
  `phone`         VARCHAR(20)  DEFAULT NULL,
  `event_type`    VARCHAR(50)  NOT NULL,
  `message`       TEXT         NOT NULL,
  `status`        TINYINT      NOT NULL DEFAULT 0
                  COMMENT '0=pendente 1=enviado 2=erro',
  `scheduled_for` DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `sent_at`       DATETIME     DEFAULT NULL,
  `created_at`    DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_status`       (`status`),
  KEY `idx_scheduled`    (`scheduled_for`),
  KEY `idx_customer`     (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ════════════════════════════════════════════════════════
-- CONFIGURAÇÕES NOVAS — Adicionadas ao system_info existente
-- (Apenas as que não existem — INSERT IGNORE é seguro)
-- ════════════════════════════════════════════════════════

INSERT IGNORE INTO `system_info` (`meta_field`, `meta_value`) VALUES
  -- Carteira / Financeiro
  ('withdrawal_min_amount',       '20.00'),
  ('withdrawal_fee_percent',      '5.00'),
  ('withdrawal_fee_fixed',        '0.00'),
  ('deposit_min_amount',          '10.00'),
  ('deposit_expiration_minutes',  '30'),

  -- Binário
  ('binary_bonus_rate',           '10.00'),
  ('binary_flush_mode',           'weekly'),
  ('mlm_require_active_plan',     '0'),

  -- Bônus de boas-vindas
  ('welcome_bonus_amount',        '0.00'),

  -- Cron Secret (CHANGE THIS!)
  ('cron_secret',                 'MUDE_ESTA_CHAVE_SECRETA_AGORA'),

  -- Módulos ativos
  ('investment_active',           '1'),
  ('auction_active',              '1'),
  ('mlm_active',                  '1'),

  -- WhatsApp (preencher após configurar Evolution / Z-API / etc)
  ('wpp_api_url',                 ''),
  ('wpp_api_key',                 ''),
  ('wpp_instance',                '');

-- ════════════════════════════════════════════════════════
-- TRIGGER: Criar wallet + bid_credits + binary_tree
--          automaticamente para cada novo cliente
-- ════════════════════════════════════════════════════════

DROP TRIGGER IF EXISTS `after_customer_insert`;

DELIMITER $$
CREATE TRIGGER `after_customer_insert`
AFTER INSERT ON `customer_list`
FOR EACH ROW
BEGIN
  INSERT IGNORE INTO `wallet`      (`customer_id`) VALUES (NEW.id);
  INSERT IGNORE INTO `bid_credits` (`customer_id`, `credits`) VALUES (NEW.id, 0);
  INSERT IGNORE INTO `binary_tree` (`customer_id`) VALUES (NEW.id);
END$$
DELIMITER ;

-- ════════════════════════════════════════════════════════
-- ÍNDICES ADICIONAIS DE PERFORMANCE
-- ════════════════════════════════════════════════════════

-- Acelera busca de yields do dia (cron)
ALTER TABLE `investments`
  ADD INDEX IF NOT EXISTS `idx_status_yield` (`status`, `last_yield_at`);

-- Acelera busca de leilões ativos em Fase 2 (cron)
ALTER TABLE `auction_list`
  ADD INDEX IF NOT EXISTS `idx_status_phase` (`status`, `phase`);

SET FOREIGN_KEY_CHECKS = 1;

-- ════════════════════════════════════════════════════════
-- FIM
-- ════════════════════════════════════════════════════════
-- ✅ Próximos passos:
--  1. Execute este SQL no seu banco
--  2. Configure as chaves no Admin > system_info
--  3. Configure os crons:
--       * * * * *  curl "https://seusite.com/admin/cron-auctions.php?secret=CHAVE"
--       0 3 * * *  curl "https://seusite.com/admin/cron-mlm.php?secret=CHAVE"
-- ════════════════════════════════════════════════════════
