-- Phoenix P3.2.2 - Commandes fournisseurs
-- Crée le socle des commandes fournisseurs et de leurs lignes.
-- Version corrigée : préparation validation, réception et commentaires internes.

CREATE TABLE IF NOT EXISTS commandes_fournisseurs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    fournisseur_id INT NOT NULL,
    utilisateur_id INT NULL,
    numero VARCHAR(30) NOT NULL UNIQUE,
    date_commande DATE NOT NULL,
    date_livraison_prevue DATE NULL,
    reference_fournisseur VARCHAR(100) NULL,
    statut VARCHAR(30) DEFAULT 'brouillon',
    date_validation DATETIME NULL,
    total_ht DECIMAL(12,2) DEFAULT 0,
    total_tva DECIMAL(12,2) DEFAULT 0,
    total_ttc DECIMAL(12,2) DEFAULT 0,
    observations TEXT NULL,
    commentaire_interne TEXT NULL,
    est_receptionnee TINYINT(1) DEFAULT 0,
    actif TINYINT(1) DEFAULT 1,
    date_creation DATETIME DEFAULT CURRENT_TIMESTAMP,
    date_modification DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_cf_fournisseur (fournisseur_id),
    INDEX idx_cf_date (date_commande),
    INDEX idx_cf_statut (statut),
    INDEX idx_cf_validation (date_validation),
    INDEX idx_cf_reception (est_receptionnee),
    CONSTRAINT fk_cf_fournisseur FOREIGN KEY (fournisseur_id) REFERENCES fournisseurs(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS commandes_fournisseurs_lignes (
    id INT AUTO_INCREMENT PRIMARY KEY,
    commande_id INT NOT NULL,
    article_id INT NULL,
    reference VARCHAR(100) NULL,
    designation VARCHAR(255) NOT NULL,
    quantite DECIMAL(12,3) DEFAULT 0,
    quantite_recue DECIMAL(12,3) DEFAULT 0,
    prix_achat_ht DECIMAL(12,2) DEFAULT 0,
    taux_tva DECIMAL(6,2) DEFAULT 20,
    total_ht DECIMAL(12,2) DEFAULT 0,
    total_tva DECIMAL(12,2) DEFAULT 0,
    total_ttc DECIMAL(12,2) DEFAULT 0,
    ordre INT DEFAULT 0,
    INDEX idx_cfl_commande (commande_id),
    INDEX idx_cfl_article (article_id),
    CONSTRAINT fk_cfl_commande FOREIGN KEY (commande_id) REFERENCES commandes_fournisseurs(id) ON DELETE CASCADE,
    CONSTRAINT fk_cfl_article FOREIGN KEY (article_id) REFERENCES articles(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
