-- ─── Companies ────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS companies (
    id                              CHAR(36) NOT NULL DEFAULT (UUID()),
    tenant_id                       CHAR(36) NOT NULL,
    name                            VARCHAR(255) NOT NULL,
    name_en                         VARCHAR(255) NULL,
    tax_identification_number       VARCHAR(20) NOT NULL,
    commercial_registration_number  VARCHAR(50) NULL,
    address                         TEXT NULL,
    city                            VARCHAR(100) NULL,
    contact_email                   VARCHAR(255) NULL,
    contact_phone                   VARCHAR(20) NULL,
    jofotara_client_id_encrypted    TEXT NULL,
    jofotara_secret_key_encrypted   TEXT NULL,
    jofotara_income_source_sequence VARCHAR(50) NULL,
    certificate_path                VARCHAR(255) NULL,
    certificate_password_encrypted  TEXT NULL,
    is_jofotara_linked              TINYINT(1) NOT NULL DEFAULT 0,
    is_active                       TINYINT(1) NOT NULL DEFAULT 1,
    created_at                      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at                      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    deleted_at                      DATETIME NULL,
    PRIMARY KEY (id),
    INDEX idx_companies_tenant (tenant_id),
    INDEX idx_companies_tin (tax_identification_number),
    CONSTRAINT fk_companies_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─── Subscriptions ────────────────────────────────────────
CREATE TABLE IF NOT EXISTS subscriptions (
    id                       CHAR(36) NOT NULL DEFAULT (UUID()),
    tenant_id                CHAR(36) NOT NULL,
    plan                     ENUM('free','basic','office','pro','enterprise') NOT NULL DEFAULT 'basic',
    max_companies            INT NOT NULL DEFAULT 3,
    max_invoices_per_month   INT NOT NULL DEFAULT 50,
    max_users                INT NOT NULL DEFAULT 2,
    price_jod                DECIMAL(10,2) NOT NULL DEFAULT 0.00,
    invoices_used_this_month INT NOT NULL DEFAULT 0,
    status                   ENUM('active','past_due','cancelled','trial') NOT NULL DEFAULT 'active',
    current_period_start     DATETIME NULL,
    current_period_end       DATETIME NULL,
    created_at               DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at               DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uq_sub_tenant (tenant_id),
    CONSTRAINT fk_sub_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
