-- HouseHub — Schéma MySQL (Modèle pour une base famille)
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ─── Configuration du foyer ───────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_foyer_settings (
  id INT AUTO_INCREMENT PRIMARY KEY,
  currency VARCHAR(10) NOT NULL DEFAULT '€',
  zone_scolaire VARCHAR(5) NOT NULL DEFAULT 'C',
  csv_mapping TEXT DEFAULT NULL,
  cares_modes TEXT DEFAULT NULL,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT IGNORE INTO pf_foyer_settings (id, currency, zone_scolaire) VALUES (1, '€', 'C');

-- ────────────────────────────────────────────────────────────
-- Paramètres dynamiques des Modules (Key-Value)
-- ────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS `pf_settings` (
  `setting_key` varchar(50) NOT NULL,
  `setting_value` text DEFAULT NULL,
  `module` varchar(50) NOT NULL,
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`setting_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO `pf_settings` (`setting_key`, `setting_value`, `module`) VALUES 
('calendar_default_view', 'month', 'calendar'),
('calendar_first_day', '1', 'calendar'),
('calendar_working_hours', '08:00-19:00', 'calendar'),
('budget_start_day', '1', 'budget'),
('budget_default_tab', 'dépenses', 'budget'),
('travel_default_transport', 'car', 'voyage'),
('travel_default_fuel_price', '1.85', 'voyage'), 
('gifts_hide_purchased', '0', 'cadeaux'),
('gifts_default_sort', 'person', 'cadeaux'),
('gifts_budget_alert', '500', 'cadeaux');

-- ─── Utilisateurs (Legacy) ────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_users (
  id            INT AUTO_INCREMENT PRIMARY KEY,
  username      VARCHAR(100) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  display_name  VARCHAR(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ─── Personnes ────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS `pf_people` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `user_id` int(11) DEFAULT NULL,
  `role` varchar(50) DEFAULT NULL,
  `care_modes` varchar(255) DEFAULT NULL,
  `color` varchar(7) DEFAULT '#0891b2',
  `is_active` TINYINT(1) DEFAULT 1,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ─── Calendrier familial ──────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_events (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  event_date DATE NOT NULL,
  event_type VARCHAR(50) NOT NULL,
  person_id  INT NOT NULL,
  duration   DECIMAL(4,2) DEFAULT 1.0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_leaves (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  person_id  INT NOT NULL,
  leave_type VARCHAR(50) NOT NULL,
  leave_date DATE NOT NULL,
  duration   DECIMAL(4,2) DEFAULT 1.0,
  UNIQUE KEY uq_leave (person_id, leave_type, leave_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_leave_balances (
  id              INT AUTO_INCREMENT PRIMARY KEY,
  person_id       INT NOT NULL,
  leave_type      VARCHAR(50) NOT NULL,
  initial_balance DECIMAL(6,2) DEFAULT 0,
  balance_year    INT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_leave_snapshots (
  id                INT AUTO_INCREMENT PRIMARY KEY,
  person_id         INT NOT NULL,
  leave_type        VARCHAR(50) NOT NULL,
  snapshot_date     DATE NOT NULL,
  remaining_balance DECIMAL(6,2) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_person_leave_meta (
  id INT(11) AUTO_INCREMENT PRIMARY KEY,
  person_id INT(11) NOT NULL,
  leave_type VARCHAR(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  method VARCHAR(20) COLLATE utf8mb4_unicode_ci DEFAULT 'FIXED',
  allowance DECIMAL(5,2) DEFAULT 0.00,
  anniversary_date DATE DEFAULT NULL,
  INDEX (person_id),
  INDEX (leave_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─── Types de Congés (Référentiel) ─────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_leave_types (
  id INT(11) AUTO_INCREMENT PRIMARY KEY,
  code VARCHAR(20) COLLATE utf8mb4_general_ci NOT NULL,
  label VARCHAR(100) COLLATE utf8mb4_general_ci NOT NULL,
  default_allowance DECIMAL(5,2) DEFAULT 0.00,
  reset_month INT(11) DEFAULT 1,
  allow_carry_over TINYINT(1) DEFAULT 0,
  UNIQUE KEY code (code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

INSERT IGNORE INTO pf_leave_types (code, label, default_allowance, reset_month, allow_carry_over) VALUES
('CP', 'Congés Payés', 25.00, 6, 0);

CREATE TABLE IF NOT EXISTS pf_calendar_weeks (
  id              INT AUTO_INCREMENT PRIMARY KEY,
  year            INT NOT NULL,
  week_iso_year   INT NOT NULL,
  week_iso_number INT NOT NULL,
  week_label      VARCHAR(20),
  month           INT,
  month_name      VARCHAR(20),
  week_start_date DATE,
  mon_date DATE, tue_date DATE, wed_date DATE,
  thu_date DATE, fri_date DATE, sat_date DATE, sun_date DATE,
  UNIQUE KEY uq_week (year, week_iso_year, week_iso_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ─── Budget ───────────────────────────────────────────────────────────────────

-- NOUVEAU : Table des comptes bancaires
CREATE TABLE IF NOT EXISTS pf_bank_accounts (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  account_type ENUM('checking', 'savings') DEFAULT 'checking',
  owner_person_id INT DEFAULT NULL,
  is_default TINYINT(1) DEFAULT 0,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (owner_person_id) REFERENCES pf_people(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_budget_items (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  amount DECIMAL(10,2) DEFAULT 0,
  category VARCHAR(100),
  type VARCHAR(50),
  payment_day INT DEFAULT NULL,
  is_estimate TINYINT(1) DEFAULT 0,
  reg_month VARCHAR(7) DEFAULT NULL,
  mapping_keywords TEXT DEFAULT NULL,
  holiday_id INT DEFAULT NULL,
  is_checked TINYINT(1) DEFAULT 0,
  sort_order INT DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_expenses (
  id INT AUTO_INCREMENT PRIMARY KEY,
  date_exp DATE NOT NULL,
  gestion_month VARCHAR(10) NOT NULL,
  category VARCHAR(100),
  label VARCHAR(255),
  amount DECIMAL(10,2) DEFAULT 0,
  import_ref VARCHAR(255) DEFAULT NULL,
  budget_item_id INT DEFAULT NULL,
  holiday_id INT DEFAULT NULL,
  salary_id INT DEFAULT NULL -- 🔥 AJOUT : Lien vers le salaire configuré
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_alloc_categories (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  target DECIMAL(10,2) DEFAULT 0.00,
  transfer_dest VARCHAR(50) DEFAULT NULL,
  holiday_id INT DEFAULT NULL,
  sort_order INT DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_alloc_values (
  id INT AUTO_INCREMENT PRIMARY KEY,
  month_date VARCHAR(10) NOT NULL,
  cat_id INT NOT NULL,
  person_id INT NOT NULL,
  amount DECIMAL(10,2) DEFAULT 0.00,
  UNIQUE KEY uq_alloc_person (month_date, cat_id, person_id),
  FOREIGN KEY (person_id) REFERENCES pf_people(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_savings (
  id INT AUTO_INCREMENT PRIMARY KEY,
  owner VARCHAR(50) NOT NULL,
  month_date VARCHAR(10) NOT NULL,
  category VARCHAR(100) NOT NULL,
  amount DECIMAL(10,2) DEFAULT 0,
  holiday_id INT DEFAULT NULL,
  UNIQUE KEY uq_savings (owner, month_date, category)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_bank_snapshots (
  id INT AUTO_INCREMENT PRIMARY KEY,
  snapshot_date DATE NOT NULL,
  amount DECIMAL(12,2) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_salary_config (
  id INT AUTO_INCREMENT PRIMARY KEY,
  year INT NOT NULL,
  person VARCHAR(50) NOT NULL,
  salary DECIMAL(10,2) DEFAULT 0,
  mensualite DECIMAL(10,2) DEFAULT 0,
  frais_func DECIMAL(10,2) DEFAULT 0,
  eco_perso DECIMAL(10,2) DEFAULT 0,
  eco_family DECIMAL(10,2) DEFAULT 0,
  UNIQUE KEY uq_salary (year, person)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_import_rules (
  id INT AUTO_INCREMENT PRIMARY KEY,
  keyword VARCHAR(255) NOT NULL UNIQUE,
  category VARCHAR(100) NOT NULL,
  budget_item_id INT(11) NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `pf_advances` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `advance_date` date NOT NULL,
  `payer` varchar(50) NOT NULL,
  `description` varchar(255) NOT NULL,
  `amount` decimal(10,2) DEFAULT 0.00,
  `from_savings` tinyint(1) DEFAULT 0,
  `is_resolved` tinyint(1) DEFAULT 0,
  `created_at` datetime DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─── Budget Catégories (Dynamiques) ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_budget_categories (
  id INT AUTO_INCREMENT PRIMARY KEY,
  code VARCHAR(50) NOT NULL UNIQUE,
  label VARCHAR(100) NOT NULL,
  type VARCHAR(50) NOT NULL,
  color VARCHAR(20) DEFAULT '#ccc',
  icon VARCHAR(20) DEFAULT '?'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- Insertion des catégories de base pour toute nouvelle famille
INSERT IGNORE INTO pf_budget_categories (code, label, type, color, icon) VALUES
('INCOME', 'Revenus', 'Income', '#10b981', '💵'),
('FIXED', 'Charges Fixes', 'Expense', '#ef4444', '🏢');

-- ─── Notes / Memo ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_notes (
  id           INT AUTO_INCREMENT PRIMARY KEY,
  note_type    VARCHAR(100) NOT NULL,
  reference_id VARCHAR(100) NOT NULL,
  content      TEXT,
  UNIQUE KEY uq_note (note_type, reference_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_memo_notes (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  title      VARCHAR(255) NOT NULL,
  content    LONGTEXT DEFAULT '',
  tags       VARCHAR(1000) DEFAULT '',
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FULLTEXT KEY ft_notes (title, content, tags)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_memo_attachments (
  id            INT AUTO_INCREMENT PRIMARY KEY,
  note_id       INT NOT NULL,
  type          ENUM('image','file','url') NOT NULL DEFAULT 'file',
  filename      VARCHAR(255) DEFAULT NULL,
  original_name VARCHAR(255) DEFAULT NULL,
  url           TEXT DEFAULT NULL,
  label         VARCHAR(255) DEFAULT NULL,
  size          INT DEFAULT 0,
  created_at    DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (note_id) REFERENCES pf_memo_notes(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ─── Voyages / Holidays ───────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_holidays (
  id           INT AUTO_INCREMENT PRIMARY KEY,
  title        VARCHAR(255) NOT NULL,
  period_hint  VARCHAR(100) DEFAULT NULL,
  start_date   DATE DEFAULT NULL,
  end_date     DATE DEFAULT NULL,
  status       VARCHAR(50) DEFAULT 'draft',
  budget_food  DECIMAL(10,2) DEFAULT 0,
  budget_extra DECIMAL(10,2) DEFAULT 0,
  notes        TEXT DEFAULT NULL,
  vehicle_id   INT DEFAULT NULL,
  return_step_id INT DEFAULT NULL, -- 🔥 NOUVEAU : Point de bascule du retour
  FOREIGN KEY (vehicle_id) REFERENCES pf_vehicles(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_holidays_items (
  id              INT AUTO_INCREMENT PRIMARY KEY,
  holiday_id      INT NOT NULL,
  category        VARCHAR(100),
  name            VARCHAR(255),
  amount          DECIMAL(10,2) DEFAULT 0,
  is_paid         TINYINT(1) DEFAULT 0,
  location_name   VARCHAR(255) DEFAULT NULL,
  lat             DECIMAL(10,7) DEFAULT NULL,
  lng             DECIMAL(10,7) DEFAULT NULL,
  sort_order      INT DEFAULT 0,
  notes           TEXT DEFAULT NULL,
  item_date       DATE DEFAULT NULL,
  item_time       TIME DEFAULT NULL,
  step_type       VARCHAR(20) DEFAULT 'stop', 
  step_start_date DATE DEFAULT NULL,
  step_end_date   DATE DEFAULT NULL,
  duration        INT DEFAULT NULL,
  expense_context VARCHAR(20) DEFAULT NULL,   
  FOREIGN KEY (holiday_id) REFERENCES pf_holidays(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_holidays_items (
  id              INT AUTO_INCREMENT PRIMARY KEY,
  holiday_id      INT NOT NULL,
  category        VARCHAR(100),
  name            VARCHAR(255),
  amount          DECIMAL(10,2) DEFAULT 0,
  is_paid         TINYINT(1) DEFAULT 0,
  location_name   VARCHAR(255) DEFAULT NULL,
  lat             DECIMAL(10,7) DEFAULT NULL,
  lng             DECIMAL(10,7) DEFAULT NULL,
  sort_order      INT DEFAULT 0,
  notes           TEXT DEFAULT NULL,
  item_date       DATE DEFAULT NULL,
  item_time       TIME DEFAULT NULL,
  step_start_date DATE DEFAULT NULL,
  step_end_date   DATE DEFAULT NULL,
  duration        INT DEFAULT NULL,
  is_return       TINYINT(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_holidays_ideas (
  id           INT AUTO_INCREMENT PRIMARY KEY,
  title        VARCHAR(255) NOT NULL,
  period_hint  VARCHAR(100) DEFAULT NULL,
  start_date   DATE DEFAULT NULL,
  end_date     DATE DEFAULT NULL,
  status       VARCHAR(50) DEFAULT 'idea',
  budget_food  DECIMAL(10,2) DEFAULT 0,
  budget_extra DECIMAL(10,2) DEFAULT 0,
  notes        TEXT DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `pf_holidays_attachments` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `holiday_id` INT NOT NULL,
  `item_id` INT DEFAULT NULL,
  `file_name` VARCHAR(255) NOT NULL,
  `file_path` VARCHAR(255) NOT NULL,
  `uploaded_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_holiday_attachment` FOREIGN KEY (`holiday_id`) REFERENCES `pf_holidays`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS pf_geocode_cache (
  q_hash       CHAR(64) PRIMARY KEY,
  q            VARCHAR(255),
  lat          DECIMAL(10,7),
  lng          DECIMAL(10,7),
  display_name TEXT,
  updated_at   DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ─── Cadeaux ──────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_gifts (
  id INT(11) AUTO_INCREMENT PRIMARY KEY,
  year INT(11) NOT NULL,
  adult_name VARCHAR(100) NOT NULL,
  payer_name VARCHAR(100) DEFAULT NULL,
  child_name VARCHAR(100) NOT NULL,
  occasion VARCHAR(50) NOT NULL,
  gift_description TEXT NOT NULL,
  product_link VARCHAR(500) DEFAULT NULL,
  amount DECIMAL(8,2) DEFAULT 0.00
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE IF NOT EXISTS pf_gift_occasions (
  id INT(11) AUTO_INCREMENT PRIMARY KEY,
  code VARCHAR(50) NOT NULL UNIQUE,
  name VARCHAR(100) NOT NULL,
  icon VARCHAR(20) DEFAULT '🎁',
  month_date VARCHAR(5) DEFAULT NULL,
  is_active TINYINT(1) DEFAULT 1,
  sort_order INT DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

INSERT IGNORE INTO pf_gift_occasions (code, name, icon, month_date, is_active, sort_order) VALUES
('XMAS', 'Noël', '🎄', '12-25', 1, 1),
('BIRTHDAY', 'Anniversaire', '🎂', NULL, 1, 2),
('OTHER', 'Autre', '🎁', NULL, 1, 99);

-- Table des règles (Qui offre à Qui)
CREATE TABLE IF NOT EXISTS pf_gift_rules (
  id INT(11) AUTO_INCREMENT PRIMARY KEY,
  adult_person_id INT(11) NOT NULL,
  child_person_id INT(11) NOT NULL,
  occasion_id INT(11) NOT NULL,
  INDEX (adult_person_id),
  INDEX (child_person_id),
  INDEX (occasion_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ─── Garage Manager ───────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_vehicles (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  brand VARCHAR(100) NOT NULL,
  model VARCHAR(100) NOT NULL,
  year INT DEFAULT NULL,
  license_plate VARCHAR(50) DEFAULT NULL,
  vin VARCHAR(100) DEFAULT NULL,
  fuel_type VARCHAR(50) DEFAULT 'Essence',
  consumption decimal(4,2) DEFAULT NULL COMMENT 'Consommation L/100km',
  color VARCHAR(50) DEFAULT NULL,
  purchase_date DATE DEFAULT NULL,
  purchase_price DECIMAL(10,2) DEFAULT NULL,
  current_km INT DEFAULT 0,
  photo VARCHAR(255) DEFAULT NULL,
  notes TEXT DEFAULT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_maintenances (
  id INT AUTO_INCREMENT PRIMARY KEY,
  vehicle_id INT NOT NULL,
  type VARCHAR(100) NOT NULL,
  description TEXT DEFAULT NULL,
  date DATE NOT NULL,
  km INT DEFAULT NULL,
  cost DECIMAL(10,2) DEFAULT 0,
  mechanic VARCHAR(100) DEFAULT NULL,
  garage_name VARCHAR(100) DEFAULT NULL,
  next_km INT DEFAULT NULL,
  next_date DATE DEFAULT NULL,
  invoice_photo VARCHAR(255) DEFAULT NULL,
  notes TEXT DEFAULT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (vehicle_id) REFERENCES pf_vehicles(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_parts (
  id INT AUTO_INCREMENT PRIMARY KEY,
  vehicle_id INT DEFAULT NULL,
  maintenance_id INT DEFAULT NULL,
  brand VARCHAR(100) DEFAULT NULL,
  reference VARCHAR(100) DEFAULT NULL,
  name VARCHAR(255) NOT NULL,
  category VARCHAR(100) DEFAULT 'Autre',
  price DECIMAL(10,2) DEFAULT 0,
  quantity INT DEFAULT 1,
  unit VARCHAR(50) DEFAULT 'pièce',
  supplier VARCHAR(100) DEFAULT NULL,
  purchase_date DATE DEFAULT NULL,
  photo VARCHAR(255) DEFAULT NULL,
  notes TEXT DEFAULT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (vehicle_id) REFERENCES pf_vehicles(id) ON DELETE SET NULL,
  FOREIGN KEY (maintenance_id) REFERENCES pf_maintenances(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_garage_documents (
  id INT AUTO_INCREMENT PRIMARY KEY,
  vehicle_id INT NOT NULL,
  maintenance_id INT DEFAULT NULL,
  label VARCHAR(255) DEFAULT NULL,
  filename VARCHAR(255) NOT NULL,
  original_name VARCHAR(255) DEFAULT NULL,
  mime VARCHAR(120) DEFAULT NULL,
  size INT DEFAULT 0,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  KEY idx_gd_vehicle (vehicle_id),
  KEY idx_gd_maint (maintenance_id),
  FOREIGN KEY (vehicle_id) REFERENCES pf_vehicles(id) ON DELETE CASCADE,
  FOREIGN KEY (maintenance_id) REFERENCES pf_maintenances(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ─── Todo ─────────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_todo_lists (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  name       VARCHAR(255) NOT NULL,
  color      VARCHAR(20) DEFAULT '#3b82f6',
  icon       VARCHAR(10) DEFAULT '📋',
  position   INT DEFAULT 0,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_todos (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  list_id    INT DEFAULT NULL,
  title      VARCHAR(500) NOT NULL,
  notes      TEXT DEFAULT NULL,
  due_date   DATE DEFAULT NULL,
  due_time   TIME DEFAULT NULL,
  notified   TINYINT(1) DEFAULT 0,
  notified_date DATE DEFAULT NULL,
  priority   ENUM('none','low','medium','high') DEFAULT 'none',
  done       TINYINT(1) DEFAULT 0,
  done_at    DATETIME DEFAULT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (list_id) REFERENCES pf_todo_lists(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ─── Module Liste (Courses partagées) ─────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_lists (
  id        INT AUTO_INCREMENT PRIMARY KEY,
  name      VARCHAR(255) NOT NULL DEFAULT 'Ma liste',
  color     VARCHAR(20) DEFAULT NULL,
  list_type VARCHAR(50) DEFAULT NULL,
  position  INT NOT NULL DEFAULT 0,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT IGNORE INTO pf_lists (id, name, position) VALUES (1, 'Ma liste', 0);

CREATE TABLE IF NOT EXISTS pf_grocery_items (
  id          INT AUTO_INCREMENT PRIMARY KEY,
  list_id     INT NOT NULL DEFAULT 1,
  category_id INT DEFAULT NULL,
  label       VARCHAR(500) NOT NULL,
  in_cart     TINYINT(1) NOT NULL DEFAULT 0,
  position    INT NOT NULL DEFAULT 0,
  created_at  DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at  DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_items_list (list_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_grocery_history (
  id INT AUTO_INCREMENT PRIMARY KEY,
  label_hash CHAR(64) NOT NULL,
  label_display VARCHAR(500) NOT NULL,
  last_used_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_grocery_hist_hash (label_hash),
  KEY idx_hist_last (last_used_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_list_categories (
  id       INT AUTO_INCREMENT PRIMARY KEY,
  icon     VARCHAR(10) NOT NULL DEFAULT '🏷️',
  name     VARCHAR(100) NOT NULL,
  position INT NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_item_category_rules (
  id          INT AUTO_INCREMENT PRIMARY KEY,
  keyword     VARCHAR(255) NOT NULL,
  category_id INT NOT NULL,
  UNIQUE KEY uq_keyword (keyword)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ─── Calendar iOS ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_calendar_events (
  id                 INT AUTO_INCREMENT PRIMARY KEY,
  family_id          INT NOT NULL,
  created_by_user_id INT NOT NULL,
  title              VARCHAR(255) NOT NULL,
  description        TEXT DEFAULT NULL,
  location           VARCHAR(255) DEFAULT NULL,
  start_at           DATETIME NOT NULL,
  end_at             DATETIME NOT NULL,
  is_all_day         TINYINT(1) DEFAULT 0,
  timezone           VARCHAR(64) DEFAULT 'Europe/Paris',
  rrule              VARCHAR(500) DEFAULT NULL,
  status             VARCHAR(50) DEFAULT 'confirmed',
  external_uid       VARCHAR(255) DEFAULT NULL,
  sync_state         VARCHAR(30) DEFAULT 'pending_push',
  deleted_at         DATETIME DEFAULT NULL,
  created_at         DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at         DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_external_uid (external_uid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_calendar_event_links (
  id                INT AUTO_INCREMENT PRIMARY KEY,
  calendar_event_id INT NOT NULL,
  external_uid      VARCHAR(255) NOT NULL,
  external_etag     VARCHAR(255) DEFAULT NULL,
  calendar_url      VARCHAR(1024) DEFAULT NULL,
  external_href     VARCHAR(2048) DEFAULT NULL,
  created_at        DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at        DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_calendar_event (calendar_event_id),
  UNIQUE KEY uq_external_link (external_uid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ─── PrintVault ───────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_pv_models (
  id            INT AUTO_INCREMENT PRIMARY KEY,
  name          VARCHAR(255) NOT NULL,
  description   TEXT DEFAULT '',
  category      VARCHAR(100) DEFAULT 'Non classé',
  tags          VARCHAR(500) DEFAULT '',
  file_type     VARCHAR(20) NOT NULL,
  filename      VARCHAR(255) NOT NULL,
  original_name VARCHAR(255) NOT NULL,
  file_size     INT DEFAULT 0,
  dim_x         DECIMAL(10,3) DEFAULT 0,
  dim_y         DECIMAL(10,3) DEFAULT 0,
  dim_z         DECIMAL(10,3) DEFAULT 0,
  volume        DECIMAL(10,3) DEFAULT 0,
  gcode_time    VARCHAR(50) DEFAULT '',
  gcode_filament VARCHAR(50) DEFAULT '',
  gcode_nozzle  VARCHAR(20) DEFAULT '',
  gcode_bed     VARCHAR(20) DEFAULT '',
  thumb         VARCHAR(255) DEFAULT '',
  created_at    DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at    DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS pf_pv_categories (
  id    INT AUTO_INCREMENT PRIMARY KEY,
  name  VARCHAR(100) NOT NULL UNIQUE,
  color VARCHAR(20) DEFAULT '#8b5cf6'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT IGNORE INTO pf_pv_categories (name, color) VALUES
  ('Non classé','#64748b'),('Déco','#ec4899'),('Fonctionnel','#3b82f6'),
  ('Mécanique','#f59e0b'),('Jouets','#10b981'),('Outils','#ef4444'),
  ('Architecture','#8b5cf6'),('Art','#06b6d4');

-- ─── Planka ───────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pf_planka_config (
  id               INT NOT NULL DEFAULT 1,
  project_id       VARCHAR(32),
  admin_token      TEXT,
  token_expires_at DATETIME,
  active_board_id  VARCHAR(32),
  updated_at       DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

SET FOREIGN_KEY_CHECKS = 1;