-- Alış faturası tabloları (mevcut mobilyaci veritabanına uygulayın)
-- mysql -u root -p mobilyaci < database/migrations/20260511_purchase_invoices.sql

SET NAMES utf8mb4;

CREATE TABLE IF NOT EXISTS purchase_invoices (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    branch_id BIGINT UNSIGNED NOT NULL,
    warehouse_id BIGINT UNSIGNED NOT NULL,
    supplier_name VARCHAR(191) NOT NULL,
    supplier_tax_id VARCHAR(32) NULL,
    document_no VARCHAR(64) NOT NULL,
    document_date DATE NOT NULL,
    currency CHAR(3) NOT NULL DEFAULT 'TRY',
    subtotal DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
    tax_total DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
    grand_total DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
    notes TEXT NULL,
    created_by BIGINT UNSIGNED NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_pi_branch_date (branch_id, document_date),
    KEY idx_pi_wh (warehouse_id),
    CONSTRAINT fk_pi_branch FOREIGN KEY (branch_id) REFERENCES branches(id),
    CONSTRAINT fk_pi_wh FOREIGN KEY (warehouse_id) REFERENCES warehouses(id),
    CONSTRAINT fk_pi_user FOREIGN KEY (created_by) REFERENCES users(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS purchase_invoice_lines (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    purchase_invoice_id BIGINT UNSIGNED NOT NULL,
    product_id BIGINT UNSIGNED NOT NULL,
    quantity DECIMAL(14,3) NOT NULL,
    unit_cost_net DECIMAL(14,4) NOT NULL COMMENT 'KDV hariç birim maliyet',
    vat_rate DECIMAL(5,2) NOT NULL DEFAULT 20.00,
    line_subtotal DECIMAL(14,4) NOT NULL,
    line_tax DECIMAL(14,4) NOT NULL,
    line_total DECIMAL(14,4) NOT NULL,
    KEY idx_pil_invoice (purchase_invoice_id),
    KEY idx_pil_product (product_id),
    CONSTRAINT fk_pil_invoice FOREIGN KEY (purchase_invoice_id) REFERENCES purchase_invoices(id) ON DELETE CASCADE,
    CONSTRAINT fk_pil_product FOREIGN KEY (product_id) REFERENCES products(id)
) ENGINE=InnoDB;
