-- =====================================================================
--  Migration factures & paiements fournisseurs (Phase 2)
--  Date: 2025-08-26 (suite)
-- =====================================================================
CREATE TABLE IF NOT EXISTS invoices (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    id_copro INT NOT NULL,
    supplier_id BIGINT NULL,
    ref VARCHAR(80) NULL,
    date_invoice DATE NOT NULL,
    date_due DATE NULL,
    description VARCHAR(255) NOT NULL,
    total_ht_cents BIGINT NOT NULL DEFAULT 0,
    total_tva_cents BIGINT NOT NULL DEFAULT 0,
    total_ttc_cents BIGINT NOT NULL DEFAULT 0,
    paid_amount_cents BIGINT NOT NULL DEFAULT 0,
    status ENUM('draft','posted','partially_paid','paid','cancelled') NOT NULL DEFAULT 'draft',
    journal_entry_id BIGINT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_inv_copro (id_copro),
    INDEX idx_inv_supplier (supplier_id),
    INDEX idx_inv_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS invoice_lines (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    invoice_id BIGINT NOT NULL,
    id_copro INT NOT NULL,
    account_code VARCHAR(32) NOT NULL,
    label VARCHAR(255) NOT NULL,
    amount_ht_cents BIGINT NOT NULL DEFAULT 0,
    tva_rate DECIMAL(5,2) NULL,
    tva_cents BIGINT NOT NULL DEFAULT 0,
    total_cents BIGINT NOT NULL DEFAULT 0,
    INDEX idx_inv_lines_invoice (invoice_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS invoice_payments (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    invoice_id BIGINT NOT NULL,
    id_copro INT NOT NULL,
    bank_row_id BIGINT NULL,
    amount_cents BIGINT NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_invpay_invoice (invoice_id),
    INDEX idx_invpay_bank (bank_row_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
