-- Storefront Row Builder Tables
-- Rows are visual layout containers on the storefront
-- Each row holds products and/or content blocks in a 4-slot grid

CREATE TABLE IF NOT EXISTS storefront_rows (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    store_id INT NOT NULL,
    row_type CHAR(1) NOT NULL DEFAULT 'A' COMMENT 'A=3+1, B=2+2, C=1+3',
    row_order INT NOT NULL DEFAULT 0,
    category_name VARCHAR(255) DEFAULT NULL COMMENT 'Encrypted display label',
    is_active TINYINT(1) DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_store_order (store_id, row_order),
    INDEX idx_active (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS row_items (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    row_id BIGINT NOT NULL,
    item_type ENUM('product','block') NOT NULL DEFAULT 'product',
    item_ref_id BIGINT DEFAULT NULL COMMENT 'FK to listings.id or listing_blocks.id',
    slot_width TINYINT NOT NULL DEFAULT 1 COMMENT '1-3 slots wide',
    item_order INT NOT NULL DEFAULT 0,
    product_title_enc TEXT DEFAULT NULL COMMENT 'Encrypted cached title',
    product_price_enc VARCHAR(255) DEFAULT NULL COMMENT 'Encrypted cached price',
    product_image_url VARCHAR(500) DEFAULT NULL,
    block_type VARCHAR(30) DEFAULT NULL COMMENT 'context,sale,countdown,raffle,referral,testimonial,stats,gallery',
    block_config_enc TEXT DEFAULT NULL COMMENT 'Encrypted JSON config',
    is_active TINYINT(1) DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_row_order (row_id, item_order),
    FOREIGN KEY (row_id) REFERENCES storefront_rows(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
