-- P5-5395: move invoices to a new table

DROP TABLE IF EXISTS invoices;

CREATE TABLE invoices
(
    id serial primary key,
    inserted timestamp with time zone NOT NULL DEFAULT now(),
    order_id INTEGER,
    invoice_date DATE,
    invoice_sent INTEGER NOT NULL DEFAULT 0
);

create index invoices_inserted on invoices(inserted desc nulls last);
create index invoices_sent on invoices(invoice_sent);

ALTER TABLE invoices
    ADD CONSTRAINT order_fk
    FOREIGN KEY (order_id)
    REFERENCES "order-orders"(orderid) MATCH SIMPLE;


INSERT INTO invoices (order_id, inserted)
    select orderid, inserted from "order-orders_fields" where fieldid = 173;


UPDATE invoices SET invoice_date = (
    SELECT value::date from "order-orders_fields" WHERE orderid = invoices.order_id and fieldid = 166 and value != ''
);

UPDATE invoices SET invoice_sent = 1 WHERE EXISTS (
    SELECT 1 FROM "order-orders_fields" invoice_sent WHERE invoice_sent.orderid = invoices.order_id AND fieldid = 205 AND value = 'true'
);
