-- =====================================================
-- Módulo de Pagos de Luz - Cámara
-- Fecha: 2026-02-14
-- Propósito: Crear tablas para gestión de pagos bimestrales de luz
-- =====================================================

-- Tabla de configuración bimestral de luz
CREATE TABLE IF NOT EXISTS electricity_bills (
    id INT AUTO_INCREMENT PRIMARY KEY,
    year INT NOT NULL,
    period VARCHAR(20) NOT NULL COMMENT 'Ene-Feb, Mar-Abr, May-Jun, Jul-Ago, Sep-Oct, Nov-Dic',
    total_amount DECIMAL(10,2) DEFAULT 0.00 COMMENT 'Monto total del recibo CFE',
    amount_per_house DECIMAL(10,2) DEFAULT 0.00 COMMENT 'Monto sugerido por casa',
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY unique_period (year, period),
    INDEX idx_year (year)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Configuración bimestral de pagos de luz';

-- Tabla de pagos de luz por casa
CREATE TABLE IF NOT EXISTS electricity_payments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    house_id INT NOT NULL,
    year INT NOT NULL,
    period VARCHAR(20) NOT NULL COMMENT 'Ene-Feb, Mar-Abr, May-Jun, Jul-Ago, Sep-Oct, Nov-Dic',
    amount DECIMAL(10,2) DEFAULT 0.00,
    payment_date DATETIME,
    notes TEXT,
    created_by INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (house_id) REFERENCES houses(id) ON DELETE CASCADE,
    FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
    UNIQUE KEY unique_payment (house_id, year, period)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Pagos de luz por casa';

-- Índices para optimización de queries
CREATE INDEX idx_electricity_payments_year_period ON electricity_payments(year, period);
CREATE INDEX idx_electricity_payments_house_year ON electricity_payments(house_id, year);

-- Verificar tablas creadas
SELECT 'Tablas creadas exitosamente:' as 'Status';
SHOW TABLES LIKE 'electricity%';

-- Verificar índices
SELECT 'Índices de electricity_payments:' as 'Verificación';
SHOW INDEX FROM electricity_payments WHERE Key_name LIKE 'idx_%';
