<?php

class Profit extends \Eloquent
{
    /**
     * Fillable
     * @var array
     */
    protected $fillable = [
        'id',
        'created_at',
        'updated_at',
        'user_id',
        'amount',
        'invoice_id',
        'sup_invoice_id',
        'type',
        'rate',
        'description',
        'debt_id',
        'installment_id',
        'mortgage_id',
        'receipt_id'
    ];

    /**
     * The result set of reports
     */
    private static $profits = [];

    /**
     * Get Sale Today
     * @return double total
     */
    public static function getSaleToday()
    {
        $total = Profit::type('income')->whereBetween('created_at', [\Invoice::getToday(), \Invoice::getEndToday()])->sum('amount');
        return $total;
    }

    /**
     * Get Sale So Far
     * @return double total
     */
    public static function getSaleSoFar()
    {
        $total = Profit::type('income')->sum('amount');
        return $total;
    }

    public static function getTotalExpense()
    {
        return Profit::type('expense')->sum('amount');
    }

    public static function monthly($month)
    {
        $start = new \Carbon\Carbon($month);
        $start->startOfMonth();
        $end = new \Carbon\Carbon($month);
        $end->endOfMonth();
        $total = self::where('type', 'expense')->whereBetween('created_at', [$start, $end])->sum('amount');
        return round($total, 2);
    }

    public static function scopeType($query, $type)
    {
        return $query->whereType($type);
    }

    /**
     * Generate Report
     * @param  string $type  Income or Expense
     * @param  object $start Carbon object
     * @param  object $end   Carbon object
     * @return array         Array of objects
     */
    public static function reports($type, $start = null, $end = null)
    {
        self::$profits = self::join('users as u', 'profits.user_id', '=', 'u.id')
                            ->select(DB::raw(
                                "concat(u.first_name, ' ', u.last_name)
								as full_name,
								profits.id,
								profits.amount,
								profits.type,
								profits.description,
								profits.created_at,
								profits.invoice_id
								"
                            ));
        if ($type !== 'all') {
            self::$profits->whereType($type);
        }
        if (isset($start) && isset($end)) {
            self::$profits->whereBetween('profits.created_at', [$start, $end]);
        }
        return self::$profits->get();
    }

    public static function addExpense($installment)
    {
        $success = false;
        $expense = self::where('installment_id', $installment->id)
                        ->where('type', 'expense')->first();
        if ($expense) {
            $expense->amount = $installment->getCurrentExpense();
            $expense->created_at = $installment->in_date;
            $expense->updated_at = $installment->in_date;
            $expense->save();
            $success = true;
        } else {
            $expense = new self;
            $expense->amount = $installment->getCurrentExpense();
            $expense->user_id = Auth::user()->id;
            $expense->type = 'expense';
            $expense->description = 'ប្រាក់កចំណាលលើ ផលិតផល';
            $expense->installment_id = $installment->id;
            $expense->created_at = $installment->in_date;
            $expense->updated_at = $installment->in_date;
            $expense->save();
            $success = true;
        }
        return $success;
    }

    public static function addPrincipal($data)
    {
        $p = new self;
        $p->amount = $data['amount'];
        $p->type = 'principal';
        $p->user_id = Auth::user()->id;
        $p->description = 'ប្រាក់ដើមទទួលបានពីការបង់ប្រាក់';
        $p->receipt_id = $data['receipt_id'];
        $p->created_at = $data['payment_date'];
        $p->updated_at = $data['payment_date'];
        $p->save();
    }

    public static function addIncome($data)
    {
        $income = new Profit;
        $income->amount = $data['late_amount'] > 0 ? $data['payment_amount'] + $data['late_amount'] : $data['payment_amount'];
        $income->user_id = Auth::user()->id;
        $income->type = 'income';
        $income->description = $data['desc'];
        $income->receipt_id = $data['r_id'];
        $income->created_at = $data['payment_date'];
        $income->updated_at = $data['payment_date'];
        $income->save();
    }

    public static function updateIncome($data, $id)
    {
        $income = self::where('type', 'income')
            ->where('receipt_id', $id)
            ->first();
        $income->amount = $data['late_amount'] > 0 ? $data['payment_amount'] + $data['late_amount'] : $data['payment_amount'];
        $income->user_id = Auth::user()->id;
        $income->type = 'income';
        $income->description = $data['desc'];
        $income->created_at = $data['payment_date'];
        $income->updated_at = $data['payment_date'];
        $income->save();
    }
}
