CREATE TABLE grant_years (
  year INTEGER PRIMARY KEY CHECK(year BETWEEN 2000 AND 2200),
  members_count INTEGER NOT NULL DEFAULT 0,
  volunteers_count INTEGER NOT NULL DEFAULT 0,
  employees_count INTEGER NOT NULL DEFAULT 0,
  employees_fte REAL NOT NULL DEFAULT 0,
  last_ag_date TEXT,
  annual_report TEXT,
  completed_actions TEXT,
  planned_actions TEXT,
  beneficiaries TEXT,
  officers_notes TEXT,
  in_kind_support TEXT,
  treasury_amount REAL NOT NULL DEFAULT 0,
  actual_expenses REAL NOT NULL DEFAULT 0,
  actual_income REAL NOT NULL DEFAULT 0,
  forecast_expenses REAL NOT NULL DEFAULT 0,
  forecast_income REAL NOT NULL DEFAULT 0,
  voluntary_contributions REAL NOT NULL DEFAULT 0,
  updated_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
  updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE grant_applications (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  year INTEGER NOT NULL REFERENCES grant_years(year) ON DELETE CASCADE,
  organization_name TEXT NOT NULL,
  deadline TEXT,
  requested_amount REAL NOT NULL DEFAULT 0,
  previous_amount REAL NOT NULL DEFAULT 0,
  awarded_amount REAL,
  status TEXT NOT NULL DEFAULT 'draft' CHECK(status IN ('draft','ready','submitted','awarded','refused','withdrawn')),
  notes TEXT,
  created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
  updated_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX idx_grant_applications_year ON grant_applications(year, deadline);

CREATE TABLE grant_documents (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  year INTEGER REFERENCES grant_years(year) ON DELETE SET NULL,
  category TEXT NOT NULL,
  title TEXT NOT NULL,
  stored_name TEXT NOT NULL UNIQUE,
  original_name TEXT NOT NULL,
  mime_type TEXT NOT NULL,
  size_bytes INTEGER NOT NULL,
  valid_until TEXT,
  notes TEXT,
  uploaded_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX idx_grant_documents_year ON grant_documents(year, category);
