<?php

namespace App\Modules\Invoices;

use App\Modules\Bookings\Task;

abstract class AbstractInvoiceObserver
{
    /**
     * Checks to see if the invoice should be marked as paid.
     *
     * @param  App\Modules\Invoices\InvoiceTransaction $model
     *
     * @return null
     */
    protected function checkPaid($model, $save = false)
    {
        // Automatically update the paid value
        $model->paid = $model->isPaid();

        if ($save) {
            $model->save();
        }
    }

    /**
     * Updates any related task with the paid status of the invoice.
     *
     * @param  App\Modules\Invoices\InvoiceTransaction $model
     *
     * @return int | The number of rows affected
     */
    protected function touchTasks($model)
    {
        $rows = 0;

        // Update any task that points to this invoice number
        if ($model->id) {
            // Automatically calculate the payment date
            // We will consider the last payment as the payment date
            // so we will pull the latest transaction if any
            // or if there are no transactions but the price is 0 then we will use the current time
            if ($model->paid) {
                $last_transaction = $model->transactions()->orderBy('payment_date', 'desc')->first();
                $paid_at = ($last_transaction) ? $last_transaction->payment_date : date('Y-m-d H:i:s');
            } else {
                // If this is marked as not paid then the paid_at should be null
                $paid_at = null;
            }

            $rows = Task::query()->where('invoice_number', '=', $model->id)->whereNotNull('invoice_number')->update(['paid' => $model->paid, 'paid_at' => $paid_at]);
        }

        return $rows;
    }

    /**
     * Calculates the total price of the invoice.
     *
     * @param  App\Modules\Invoices\InvoiceItem $model
     *
     * @return null
     */
    protected function calculateTotalPrice($invoice, $save = false)
    {
        $invoice->total_price = $invoice->getTotalPrice();
        if ($save) {
            $invoice->save();
        }
    }
}
