-- =====================================================================
-- Coquille CTEI — Migration 001 : Schéma de personnalisation marchand
-- =====================================================================
-- Cible : la BD MySQL LOCALE de la coquille (une par déploiement marchand).
-- Pas de lien avec le schéma marchand `eXXXXXX` côté webshowroom.net.
-- =====================================================================

SET NAMES utf8mb4;
SET time_zone = '+00:00';

-- ---------------------------------------------------------------------
-- coquille_config : config globale (1 ligne, key/value pour souplesse)
-- ---------------------------------------------------------------------
-- Rationale: au lieu d'une table à 50 colonnes figées qui demande une
-- migration à chaque ajout, on stocke en JSON par "section" — chaque
-- section est typée et versionnable indépendamment.
CREATE TABLE IF NOT EXISTS coquille_config (
  id              INT UNSIGNED NOT NULL AUTO_INCREMENT,
  section         VARCHAR(64)  NOT NULL,        -- ex: 'brand', 'hero', 'theme', 'contact', 'social', 'seo', 'integrations'
  data            JSON         NOT NULL,         -- contenu de la section (voir documentation par section ci-dessous)
  updated_at      TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  updated_by      VARCHAR(128) DEFAULT NULL,    -- email ou username admin
  PRIMARY KEY (id),
  UNIQUE KEY uq_section (section)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Sections attendues + structure JSON canonique:
--
-- section = 'brand'         (identité visuelle)
--   { "dealer_da": "da347652",        -- DA WSR utilisé pour interroger l'API
--     "logo_path": "/uploads/logo.png",
--     "logo_dark_path": "/uploads/logo-dark.png",
--     "favicon_path": "/uploads/favicon.ico",
--     "dealer_name_override": null,   -- override le NomConcess venant de l'API
--     "tagline": "Votre prochain véhicule, sans compromis." }
--
-- section = 'hero'          (section d'entête de la page d'accueil)
--   { "headline": "Bienvenue chez %DEALER_NAME%",
--     "subheadline": "Plus de %INVENTORY_COUNT% véhicules inspectés disponibles.",
--     "background_type": "image|video|gradient",
--     "background_image": "/uploads/hero.jpg",
--     "background_video": "/uploads/hero.mp4",
--     "background_gradient": ["#0f172a", "#1e293b"],
--     "primary_cta": { "label": "Voir l'inventaire", "href": "/inventaire" },
--     "secondary_cta": { "label": "Nous joindre", "href": "/contact" },
--     "scroll_indicator": true }
--
-- section = 'theme'         (couleurs, typo, radius — driven par CSS variables)
--   { "primary": "#dc2626",
--     "primary_contrast": "#ffffff",
--     "accent": "#f59e0b",
--     "neutral_50": "#fafafa", "neutral_900": "#0a0a0a",
--     "font_family_display": "Inter",
--     "font_family_body": "Inter",
--     "radius_base": "0.75rem",
--     "motion_intensity": "subtle|medium|strong",
--     "dark_mode": "auto|light|dark" }
--
-- section = 'contact'       (infos de contact affichées, peut surcharger l'API)
--   { "address": "...", "city": "...", "province": "QC", "postal": "...",
--     "phone": "...", "phone_alt": "...", "email": "...",
--     "hours": [ {"day":"Lundi","open":"09:00","close":"18:00"}, ... ],
--     "map_embed_url": "https://..." }
--
-- section = 'social'        (réseaux sociaux — URLs complètes)
--   { "facebook": "...", "instagram": "...", "tiktok": "...",
--     "youtube": "...", "x_twitter": "...", "linkedin": "..." }
--
-- section = 'seo'           (méta + Open Graph)
--   { "title_template": "%PAGE% — %DEALER_NAME%",
--     "default_description": "...",
--     "og_image": "/uploads/og.jpg",
--     "google_site_verification": "...",
--     "google_analytics_id": "G-XXXX",
--     "meta_pixel_id": "..." }
--
-- section = 'integrations'  (clés API externes)
--   { "coquille_api_base": "https://webshowroom.net/coquille-api/v1",
--     "coquille_api_key": "...",   -- chiffrée à terme; en clair pour MVP
--     "recaptcha_site_key": "...",
--     "recaptcha_secret_key": "...",
--     "smtp_host": "...", "smtp_port": 587, "smtp_user": "...", "smtp_pass": "...",
--     "lead_destination_email": "..." }
--
-- section = 'navigation'    (menus custom — header & footer)
--   { "header_items": [ {"label":"Inventaire","href":"/inventaire"}, ... ],
--     "footer_columns": [ {"title":"...","items":[{"label":"...","href":"..."}]} ] }
--
-- section = 'inventory_display'  (réglages d'affichage de l'inventaire)
--   { "default_sort": "price_asc|price_desc|year_desc|km_asc|newest",
--     "items_per_page": 24,
--     "show_price_when_zero": "as_text",   -- "Faites-nous une offre"
--     "show_finance_calc": true,
--     "show_carfax_badge": true,
--     "hide_categories": [],               -- liste de codes catégorie à exclure
--     "featured_vins": [] }                -- VINs épinglés en haut

-- ---------------------------------------------------------------------
-- coquille_sections_custom : sections libres sur la home (style "blocks")
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS coquille_sections_custom (
  id              INT UNSIGNED NOT NULL AUTO_INCREMENT,
  position        INT          NOT NULL DEFAULT 0,
  enabled         TINYINT(1)   NOT NULL DEFAULT 1,
  kind            VARCHAR(32)  NOT NULL,  -- 'rich_text' | 'image_text' | 'testimonials' | 'team' | 'cta_banner' | 'video' | 'gallery'
  data            JSON         NOT NULL,
  updated_at      TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_position (position)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- coquille_leads : leads capturés (formulaires de contact / demandes info)
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS coquille_leads (
  id              INT UNSIGNED NOT NULL AUTO_INCREMENT,
  created_at      TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP,
  source          VARCHAR(64)  NOT NULL,  -- 'contact_form' | 'vehicle_inquiry' | 'financing' | 'callback'
  vin             VARCHAR(32)  DEFAULT NULL,
  stock_number    VARCHAR(32)  DEFAULT NULL,
  name            VARCHAR(128) NOT NULL,
  email           VARCHAR(128) NOT NULL,
  phone           VARCHAR(32)  DEFAULT NULL,
  message         TEXT         DEFAULT NULL,
  payload         JSON         DEFAULT NULL,   -- champs extra (financement, échange, etc.)
  ip              VARCHAR(45)  DEFAULT NULL,
  user_agent      VARCHAR(255) DEFAULT NULL,
  status          ENUM('new','sent','read','converted','spam') NOT NULL DEFAULT 'new',
  forwarded_at    TIMESTAMP    NULL DEFAULT NULL,  -- quand on a forwardé vers le CRM/email WSR
  PRIMARY KEY (id),
  KEY idx_status (status),
  KEY idx_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- coquille_admin_users : utilisateurs admin (le marchand pour customiser)
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS coquille_admin_users (
  id              INT UNSIGNED NOT NULL AUTO_INCREMENT,
  email           VARCHAR(128) NOT NULL,
  password_hash   VARCHAR(255) NOT NULL,   -- password_hash() PHP
  full_name       VARCHAR(128) DEFAULT NULL,
  role            ENUM('owner','editor') NOT NULL DEFAULT 'editor',
  last_login_at   TIMESTAMP    NULL DEFAULT NULL,
  created_at      TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- coquille_api_cache : cache des réponses ADWS API côté coquille
-- ---------------------------------------------------------------------
-- Note: le cache "court" 5-15 min vit côté ADWS API (Redis ou fichier),
-- mais on garde aussi un cache de secours local en cas d'API down.
CREATE TABLE IF NOT EXISTS coquille_api_cache (
  cache_key       VARCHAR(255) NOT NULL,
  payload         LONGTEXT     NOT NULL,
  expires_at      TIMESTAMP    NOT NULL,
  fetched_at      TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (cache_key),
  KEY idx_expires (expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- =====================================================================
-- Seeds par défaut — déploiement "vide" mais fonctionnel
-- =====================================================================

INSERT INTO coquille_config (section, data) VALUES
  ('brand', JSON_OBJECT(
    'dealer_da', '',
    'logo_path', NULL,
    'logo_dark_path', NULL,
    'favicon_path', NULL,
    'dealer_name_override', NULL,
    'tagline', 'Votre prochain véhicule, sans compromis.'
  )),
  ('hero', JSON_OBJECT(
    'headline', 'Bienvenue chez %DEALER_NAME%',
    'subheadline', 'Plus de %INVENTORY_COUNT% véhicules inspectés disponibles dès aujourd''hui.',
    'background_type', 'gradient',
    'background_image', NULL,
    'background_video', NULL,
    'background_gradient', JSON_ARRAY('#0f172a', '#1e293b'),
    'primary_cta', JSON_OBJECT('label', 'Voir l''inventaire', 'href', '/inventaire'),
    'secondary_cta', JSON_OBJECT('label', 'Nous joindre', 'href', '/contact'),
    'scroll_indicator', TRUE
  )),
  ('theme', JSON_OBJECT(
    'primary', '#dc2626',
    'primary_contrast', '#ffffff',
    'accent', '#f59e0b',
    'neutral_50', '#fafafa',
    'neutral_900', '#0a0a0a',
    'font_family_display', 'Inter',
    'font_family_body', 'Inter',
    'radius_base', '0.75rem',
    'motion_intensity', 'medium',
    'dark_mode', 'auto'
  )),
  ('contact', JSON_OBJECT(
    -- Tous ces champs sont vides intentionnellement : la coquille tombe automatiquement
    -- sur les valeurs de `concess` du marchand (adresse, ville, telephone, courriel...)
    -- L'admin marchand voit ces valeurs pre-remplies et n'a besoin de saisir que pour OVERRIDE.
    'address', '', 'city', '', 'province', '', 'postal', '',
    'phone', '', 'phone_alt', '', 'email', '',
    'hours', JSON_ARRAY(
      JSON_OBJECT('day', 'Lundi',    'open', '09:00', 'close', '18:00', 'closed', FALSE),
      JSON_OBJECT('day', 'Mardi',    'open', '09:00', 'close', '18:00', 'closed', FALSE),
      JSON_OBJECT('day', 'Mercredi', 'open', '09:00', 'close', '18:00', 'closed', FALSE),
      JSON_OBJECT('day', 'Jeudi',    'open', '09:00', 'close', '20:00', 'closed', FALSE),
      JSON_OBJECT('day', 'Vendredi', 'open', '09:00', 'close', '18:00', 'closed', FALSE),
      JSON_OBJECT('day', 'Samedi',   'open', '09:00', 'close', '16:00', 'closed', FALSE),
      JSON_OBJECT('day', 'Dimanche', 'open', '',      'close', '',      'closed', TRUE)
    ),
    'map_embed_url', NULL  -- Si NULL, auto-genere depuis l'adresse WSR via maps.google.com
  )),
  ('social', JSON_OBJECT(
    'facebook', '', 'instagram', '', 'tiktok', '',
    'youtube', '', 'x_twitter', '', 'linkedin', ''
  )),
  ('seo', JSON_OBJECT(
    'title_template', '%PAGE% — %DEALER_NAME%',
    'default_description', '',
    'og_image', NULL,
    'google_site_verification', NULL,
    'google_analytics_id', NULL,
    'meta_pixel_id', NULL
  )),
  ('integrations', JSON_OBJECT(
    'coquille_api_base', 'http://coquille-api/v1',
    'coquille_api_key', '',
    'recaptcha_site_key', NULL,
    'recaptcha_secret_key', NULL,
    'smtp_host', NULL, 'smtp_port', 587, 'smtp_user', NULL, 'smtp_pass', NULL,
    'lead_destination_email', ''
  )),
  ('inventory_display', JSON_OBJECT(
    'default_sort', 'newest',
    'items_per_page', 24,
    'show_price_when_zero', 'as_text',
    'show_finance_calc', TRUE,
    'show_carfax_badge', TRUE,
    'hide_categories', JSON_ARRAY(),
    'featured_vins', JSON_ARRAY()
  ));
