-- ============================================================
-- Superprofe v2.2.0 · Migración incremental
-- Ejecutar después de migration_v2.sql (o desde setup.php)
-- ============================================================
USE superprofe;

-- Registro de estados en casos de convivencia
CREATE TABLE IF NOT EXISTS convivencia_state_history (
  id INT AUTO_INCREMENT PRIMARY KEY,
  case_id INT NOT NULL,
  state VARCHAR(30) NOT NULL,
  notes TEXT,
  changed_by INT,
  changed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (case_id) REFERENCES convivencia_cases(id) ON DELETE CASCADE
) ENGINE=InnoDB;

-- Implicados en un registro de comportamiento
CREATE TABLE IF NOT EXISTS behavior_related (
  id INT AUTO_INCREMENT PRIMARY KEY,
  behavior_id INT NOT NULL,
  related_type ENUM('student','user','guardian') NOT NULL,
  related_id INT NOT NULL,
  related_name VARCHAR(150),
  FOREIGN KEY (behavior_id) REFERENCES behavior_records(id) ON DELETE CASCADE
) ENGINE=InnoDB;

-- created_by en evaluations (para saber quién es el dueño)
ALTER TABLE evaluations ADD COLUMN created_by INT DEFAULT NULL;

-- Locks de mes para evaluaciones
CREATE TABLE IF NOT EXISTS evaluation_locks (
  id INT AUTO_INCREMENT PRIMARY KEY,
  school_id INT NOT NULL,
  `year_month` CHAR(7) NOT NULL,
  locked TINYINT(1) DEFAULT 1,
  locked_by INT,
  locked_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uq_lock (school_id, `year_month`),
  FOREIGN KEY (school_id) REFERENCES schools(id) ON DELETE CASCADE
) ENGINE=InnoDB;

-- Entregas de inventario (histórico de salidas)
CREATE TABLE IF NOT EXISTS inventory_deliveries (
  id INT AUTO_INCREMENT PRIMARY KEY,
  item_id INT NOT NULL,
  delivered_to_user_id INT NOT NULL,
  quantity INT NOT NULL,
  reason VARCHAR(255),
  delivered_by INT,
  delivered_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (item_id) REFERENCES inventory_items(id) ON DELETE CASCADE,
  FOREIGN KEY (delivered_to_user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

-- Semillas de nuevas listas maestras
INSERT INTO master_lists (list_code, value, sort_order) VALUES
 ('comportamiento_cat','Participación',1),('comportamiento_cat','Disciplina',2),
 ('comportamiento_cat','Salud',3),('comportamiento_cat','Responsabilidad',4),
 ('comportamiento_cat','Convivencia',5),('comportamiento_cat','Rendimiento',6),
 ('convivencia_cat','Conflicto entre pares',1),('convivencia_cat','Bullying',2),
 ('convivencia_cat','Falta grave',3),('convivencia_cat','Situación familiar',4),
 ('convivencia_cat','Consumo',5),('convivencia_cat','Otro',6),
 ('inventario_cat','Papelería',1),('inventario_cat','Equipos',2),
 ('inventario_cat','Aseo',3),('inventario_cat','Deportes',4),
 ('inventario_cat','Laboratorio',5),('inventario_cat','Otros',6);

INSERT INTO schema_version (v) VALUES (3);
