DROP VIEW IF EXISTS payment_admin_bill_view;
CREATE VIEW payment_admin_bill_view (
id,
user_id,
role_user,
author_name,
payment_transferwise_email,
payment_transferwise_currency_code,
project_id,
project_name,
total_gross_amount,
payment_id,
payment_status,
job_position,
bills_status,
project_status,
estimated_payment_date
) AS
SELECT  pb.id                                                                                 AS id,
        us.id                                                                                 AS user_id,
        us.role_id                                                                            AS role_user,
        CONCAT(us.first_name_user, ' ', us.last_name_user)                                    AS author_name,
        us.payment_transferwise_email_user                                                    AS payment_transferwise_email,
        us.payment_transferwise_currency_code_user                                            AS payment_transferwise_currency_code,
        p.id                                                                                  AS project_id,
        p.name                                                                                AS project_name,
        ROUND(IFNULL(odb.total_gross_amount, 0), 2)                                           AS total_gross_amount,
        pp.id                                                                                 AS payment_id,
        pp.status                                                                             AS payment_status,
        pb.invoice_type                                                                       AS job_position,
        pb.status                                                                             AS bills_status,
        p.status                                                                              AS project_status,
        pb.estimated_payment_date                                                             AS estimated_payment_date
FROM offer_participant_bills AS pb
        INNER JOIN projects AS p ON pb.project_id = p.id
        INNER JOIN user as us ON pb.user_id = us.id
        INNER JOIN (SELECT SUM(price) AS total_gross_amount, offer_participant_bills_id 
        FROM offer_deliveries_offer_bills 
        GROUP BY offer_participant_bills_id
        ) AS odb ON pb.id = odb.offer_participant_bills_id
        LEFT JOIN offer_participant_payments AS pp ON pp.offer_id = pb.id AND pp.user_id = us.id
WHERE (pp.status IS NULL OR pp.status <> 1) 
GROUP BY pb.id
HAVING (total_gross_amount > 0)