Calcul between two rows SQL with conditions

I have an SQL database containing invoice data. It includes columns for “sum” and “invoice_id,” where the total amount is stored (for sum), and if it’s a down payment (invoice_id contained the other invoice id). What I need to do is calculate the sum minus the down payment, if there is one. For example, these two lines represent one project: invoice id 1567 is the down payment, and invoice id 1551 is the final invoice. Here’s an image for referenceenter image description here. The total of both sums needs to be 2902.75 for my PHP function without altering the data in this row.

For now my PHP function to calculate the sum is :

$result = Invoice::find_by_sql("
     SELECT 
         sum(invoices."sum") as "summary" 
     FROM 
         invoices 
     WHERE 
         estimate != 1 
     AND due_date < CURDATE() 
 ");

So for the exemple of above with the tow lines, I got 4063,65.

PS: I use Codeingniter in PHP framwork for my app : The full php function

/**
    ** Get sum of late
    ** return object
    **/
    public static function latePayments($option="")
    {
        if ($option == "all")
        {
            $result = Invoice::find_by_sql("
                SELECT 
                    sum(invoices.`sum`) as `summary` 
                FROM 
                    invoices 
                WHERE 
                    estimate != 1 
                    AND due_date < CURDATE() 
            ");
        }
        else
        {
            $result = Invoice::find_by_sql("
                SELECT 
                    sum(invoices.`sum`) as `summary`
                FROM 
                    invoices 
                WHERE 
                    (status = 'Open' OR status = 'Sent' OR status = 'PartiallyPaid') 
                    AND estimate != 1 
                    AND due_date < CURDATE() 
            ");
        }
        return $result[0]->summary;
    }
}

Edit 1 : The link for the sql file of the two lines : File