-- Tabella delle tipologie di firma
CREATE TABLE IF NOT EXISTS `#__circolari_firmetipi` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `nome` VARCHAR(100) NOT NULL,
  `descrizione` TEXT DEFAULT NULL,
  `bottoni_firma` TEXT DEFAULT NULL,
  `state` TINYINT(1) DEFAULT 1,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT COLLATE=utf8mb4_unicode_ci;

-- Tabella principale circolari
CREATE TABLE IF NOT EXISTS `#__circolari` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `state` TINYINT(1) NULL DEFAULT 1,
  `ordering` INT(11) NULL DEFAULT 0,
  `checked_out` INT(11) UNSIGNED DEFAULT NULL,
  `checked_out_time` DATETIME NULL DEFAULT NULL,
  `created_by` INT(11) UNSIGNED NULL DEFAULT 0,
  `modified_by` INT(11) UNSIGNED NULL DEFAULT 0,
  `title` VARCHAR(255) NULL DEFAULT "",
  `description` TEXT NULL,
  `attachment` VARCHAR(255) NULL DEFAULT "",
  `image` VARCHAR(255) NULL DEFAULT "",
  `tipologia_firma_id` INT(11) UNSIGNED DEFAULT NULL,
  `firma_obbligatoria` TINYINT(1) DEFAULT 0,
  `scadenza` DATE DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_state` (`state`),
  KEY `idx_checked_out` (`checked_out`),
  KEY `idx_created_by` (`created_by`),
  KEY `idx_modified_by` (`modified_by`),
  KEY `idx_tipologia_firma_id` (`tipologia_firma_id`),
  CONSTRAINT `fk_tipologia_firma`
    FOREIGN KEY (`tipologia_firma_id`)
    REFERENCES `#__circolari_firmetipi` (`id`)
    ON DELETE SET NULL
    ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT COLLATE=utf8mb4_unicode_ci;

-- Tabella firme
CREATE TABLE IF NOT EXISTS `#__circolari_firme` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `circolare_id` INT(11) UNSIGNED NOT NULL,
  `user_id` INT(11) UNSIGNED NOT NULL,
  `firma` ENUM('presa_visione','aderisco','non_aderisco','non_in_servizio') NOT NULL,
  `data_firma` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `firma_unica` (`circolare_id`, `user_id`)
) ENGINE=InnoDB DEFAULT COLLATE=utf8mb4_unicode_ci;
