CREATE EXTENSION IF NOT EXISTS pgcrypto;

DROP VIEW IF EXISTS public.v_funnel_orders;

CREATE OR REPLACE VIEW public.v_funnel_orders AS
 SELECT orders.id AS order_id,
    orders.inserted AS order_date,
    orders.delivered,
    orders.newsletter,
    orders.credit_invoice,
    orders.canceled,
    orders.delivered_date,
    orders.country_code,
    orders.language,
    orders.delivery_country_code,
    orders.delivery_method,
    orders.delivery_price,
    orders.delivery_vat as vat,
    orders.customer_type,
    orders.payment_type,
    orders.currency,
    orders.exchange_rate,
    orders.exchange_rate_eur,
    orders.invoice_id,
    orders.contract_customer_id,
    orders.vat_number,
    orders.cancels_order_id,
    orders.cancelled_by_order_id,
    orders.order_sum,
    orders.order_sum / orders.exchange_rate AS order_sum_sek,
    orders.market,
    orders.locale,
    encode(digest(billing_address.first_name, 'sha256'), 'hex') as billing_address_first_name,
    encode(digest(billing_address.last_name, 'sha256'), 'hex') as billing_address_last_name,
    encode(digest(billing_address.email, 'sha256'), 'hex') as email,
    encode(digest(billing_address.phone, 'sha256'), 'hex') as phone,
    encode(digest(billing_address.address1, 'sha256'), 'hex') as billing_address_address1,
    encode(digest(billing_address.address2, 'sha256'), 'hex') as billing_address_address2,
    billing_address.company_name AS billing_address_company_name,
    billing_address.country_code AS billing_address_country_code,
    billing_address.city AS billing_address_city,
    billing_address.zipcode AS billing_address_zipcode,
    billing_address.state AS billing_address_state,
    encode(digest(delivery_address.first_name, 'sha256'), 'hex') as delivery_address_first_name,
    encode(digest(delivery_address.last_name, 'sha256'), 'hex') as delivery_address_last_name,
    encode(digest(delivery_address.address1, 'sha256'), 'hex') as delivery_address_address1,
    encode(digest(delivery_address.address2, 'sha256'), 'hex') as delivery_address_address2,
    delivery_address.company_name AS delivery_address_company_name,
    delivery_address.country_code AS delivery_address_country_code,
    delivery_address.city AS delivery_address_city,
    delivery_address.zipcode AS delivery_address_zipcode,
    delivery_address.state AS delivery_address_state
   FROM orders
     JOIN addresses billing_address ON billing_address.id = orders.billing_address_id
     LEFT JOIN addresses delivery_address ON delivery_address.id = orders.delivery_address_id
  WHERE orders.paid = 1;
