<?php

namespace App\Models;

use App\Components\Functions;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\Traits\LogsActivity;

/**
 * MoneyDetail
 *
 * @mixin \Eloquent
 */
class MoneyDetail extends Model
{
    //

    use SoftDeletes;
    use LogsActivity;

    protected static $logAttributes = ['*'];

    protected $fillable = [
        'renter_id',
        'hostel_id',
        'room_id',
        'name',
        'value',
        'money_info_id',
        'user_id',
        'created_at',
        'updated_at',
        'deleted_at',
        'qty',
        'is_electric',
        'hostel_fee_id',
        'amount',
        'is_water',
        'note',
        'start_date',
        'end_date',
        'type',
        'contract_status',
        'sum_amount'
    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];


    public function hostel()
    {
        return $this->belongsTo('App\Models\Hostel');
    }

    public function hostelFee()
    {
        return $this->belongsTo(HostelFee::class, 'hostel_fee_id', 'id');
    }

    public function room()
    {
        return $this->belongsTo('App\Models\Room');
    }

    public function moneyInfo()
    {
        return $this->belongsTo(MoneyInfo::class);
    }

    public static function boot()
    {
        parent::boot();

        static::creating(function ($item) {
            $hostelFee = $item->hostelFee;
            if ($hostelFee) {
                if (in_array($hostelFee->type, [
                    HostelFee::ELECTRIC,
                    HostelFee::ELECTRIC_BY_CLOCK,
                    HostelFee::ELECTRIC_BY_PEOPLE,
                    HostelFee::ELECTRIC_DYNAMIC
                ])) {
                    $item->is_electric = true;
                } else if (in_array($hostelFee->type, [
                    HostelFee::WATER,
                    HostelFee::WATER_BY_CLOCK,
                    HostelFee::WATER_BY_PEOPLE,
                    HostelFee::WATER_DYNAMIC
                ])) {

                    $item->is_water = true;
                }
                //dd(1);
            }
        });
        static::updated(function ($item) {
            $moneyInfoId = $item->money_info_id;
            $moneyInfo = MoneyInfo::find($moneyInfoId);
            $contract = $moneyInfo->contract;
            $startDate = $item->start_date;
            $endDate = $item->end_date;
            if (!$moneyInfo) {
                return 0;
            }
            if ($moneyInfo->type == MoneyInfo::VOUCHER_CONTRACT || $moneyInfo->type == MoneyInfo::VOUCHER_ROOM_PRICE) {
                if (!$contract) {
                    return 0;
                }

                if (empty($startDate) || empty($endDate)) {
                    return 0;
                }

                StatisticMonth::query()
                    ->where('money_info_id', $moneyInfoId)
                    ->delete();

                $startDateCarbon = Carbon::createFromFormat('Y-m-d', $startDate);
                $endDateCarbon = Carbon::createFromFormat('Y-m-d', $endDate);
                $dayCollect = $contract->day_collect;
                $cost = $contract->room_price;
                if (!empty($item->value)) {
                    $cost = $item->value;
                }
                $items = Functions::statFromMoneyInfo($startDateCarbon->copy(), $endDateCarbon->copy(), $cost, $dayCollect);
                foreach ($items as $itemMonth) {
                    StatisticMonth::create([
                        'month' => $itemMonth['month'],
                        'year' => $itemMonth['year'],
                        'start_date' => $itemMonth['from'],
                        'end_date' => $itemMonth['to'],
                        'amount' => $itemMonth['money'],
                        'contract_id' => $contract->id,
                        'room_id' => !empty($contract->room) ? $contract->room->id : null,
                        'hostel_id' => !empty($contract->hostel) ? $contract->hostel->id : null,
                        'money_info_id' => $moneyInfo->id,
                    ]);
                }

                //update lại cái ngày thu tiền gần nhất
                $contractId = $moneyInfo->contract_id;
                $contract = Contract::find($contractId);
                if (!$contract) {
                    return 0;
                }

                $moneyInfo = MoneyInfo::query()->where('contract_id', $contractId)
                    ->whereIn('type', [
                        MoneyInfo::VOUCHER_CONTRACT,
                        MoneyInfo::VOUCHER_ROOM_PRICE
                    ])
                    ->orderBy('id', 'desc')
                    ->first();

                if (!$moneyInfo) {
                    return 0;
                }

                $moneyDetail = MoneyDetail::query()->where('money_info_id', $moneyInfo->id)
                    ->orderBy('id', 'desc')
                    ->first();
                if (!$moneyDetail) {
                    return 0;
                }

                $endDate = $moneyDetail->end_date;
                $lastInvoice = Carbon::createFromFormat('Y-m-d', $endDate);
                Contract::query()
                    ->where('id', $contractId)
                    ->update([
                        'last_invoice_at' => $lastInvoice->toDateString()
                    ]);

            }
        });

        static::created(function ($item) {
            $moneyInfoId = $item->money_info_id;
            $moneyInfo = MoneyInfo::find($moneyInfoId);
            if (!$moneyInfo) {
                return;
            }
            $contract = $moneyInfo->contract;
            $startDate = $item->start_date;
            $endDate = $item->end_date;


            $hostelFeeId = $item->hostel_fee_id;
            $hostelFeeItem = HostelFee::find($hostelFeeId);
            if ($hostelFeeItem) {
                if (in_array($hostelFeeItem->type, [
                    HostelFee::ELECTRIC_BY_CLOCK,
                    HostelFee::ELECTRIC_BY_PEOPLE,
                    HostelFee::WATER_BY_CLOCK,
                    HostelFee::WATER_BY_PEOPLE
                ])) {
                    $value = $hostelFeeItem->fee;
                    $item->value = $value;
                    $item->save();
                } else {
                    if (in_array($hostelFeeItem->type, [
                        HostelFee::ELECTRIC,
                        HostelFee::WATER
                    ])) {

                        $electricPrice = 0;
                        $waterPrice = 0;

                        $hostelFee = HostelFee::query()->where('type', HostelFee::ELECTRIC)
                            ->where('hostel_id', $item->moneyInfo->hostel_id)
                            ->first();

                        $hostelFeeWater = HostelFee::query()->where('type', HostelFee::WATER)
                            ->where('hostel_id', $item->moneyInfo->hostel_id)
                            ->first();

                        if ($hostelFee) {
                            $electric = ElectricQuota::query()->where('hostel_id', $item->room->hostel->id)
                                ->where('fee_id', $hostelFee->id)
                                ->first();

                            if (!$electric) {
                                $electric = ElectricQuota::query()->where('hostel_id', $item->room->hostel->id)->first();
                            }

                        } else {
                            $electric = ElectricQuota::query()->where('hostel_id', $item->room->hostel->id)->first();
                        }

                        if ($hostelFeeWater) {
                            $water = WaterQuota::query()->where('hostel_id', $item->room->hostel->id)
                                ->where('fee_id', $hostelFeeWater->id)
                                ->first();
                            if (!$water) {
                                $water = WaterQuota::query()->where('hostel_id', $item->room->hostel->id)->first();
                            }
                        } else {
                            $water = WaterQuota::query()->where('hostel_id', $item->room->hostel->id)->first();

                        }

                        if ($electric) {
                            $electricPrice = $electric->price_quota_1;
                        }

                        if ($water) {
                            $waterPrice = $water->price_quota_1;
                        }

                        if ($item->is_electric) {
                            $value = $electricPrice;
                        } else {
                            $value = $waterPrice;
                        }
                        $item->value = $value;
                        $item->save();
                    }
                }
            }


            if ($moneyInfo->type == MoneyInfo::VOUCHER_CONTRACT || $moneyInfo->type == MoneyInfo::VOUCHER_ROOM_PRICE) {
                if (!$contract) {
                    return;
                }

                if (empty($startDate) || empty($endDate)) {
                    return;
                }

                $startDateCarbon = Carbon::createFromFormat('Y-m-d', $startDate);
                $endDateCarbon = Carbon::createFromFormat('Y-m-d', $endDate);
                $dayCollect = $contract->day_collect;
                $cost = $contract->room_price;
                $items = Functions::statFromMoneyInfo($startDateCarbon->copy(), $endDateCarbon->copy(), $cost, $dayCollect);
                foreach ($items as $itemMonth) {
                    StatisticMonth::create([
                        'month' => $itemMonth['month'],
                        'year' => $itemMonth['year'],
                        'start_date' => $itemMonth['from'],
                        'end_date' => $itemMonth['to'],
                        'amount' => $itemMonth['money'],
                        'contract_id' => $contract->id,
                        'room_id' => !empty($contract->room) ? $contract->room->id : null,
                        'hostel_id' => !empty($contract->hostel) ? $contract->hostel->id : null,
                        'money_info_id' => $moneyInfo->id,
                    ]);
                }
            }

            if (in_array($moneyInfo->type, [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])) {
                if ($item->sum_amount == (($item->value * $item->qty) - 1)) {
                    MoneyDetail::query()
                        ->where('id', $item->id)
                        ->update([
                            'sum_amount' => $item->value * $item->qty
                        ]);
                    $newAmount = $moneyInfo->amount + 1;
                    $newRemain = $moneyInfo->remain + 1;
                    MoneyInfo::query()
                        ->where('id', $moneyInfo->id)
                        ->update([
                            'amount' => $newAmount,
                            'remain' => $newRemain
                        ]);
                }
            }

        });


    }

    public function getNameAttribute()
    {
        try {
            $name = $this->attributes['name'];
            $startDate = $this->attributes['start_date'];
            $endDate = $this->attributes['end_date'];
            $eng = null;
            if ($this->moneyInfo) {
                $moneyInfo = $this->moneyInfo;
                if (in_array($moneyInfo->type, [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])) {
                    $startDate = Carbon::createFromFormat('Y-m-d', $startDate);
                    $endDate = Carbon::createFromFormat('Y-m-d', $endDate);
                    $eng = 'Room rent (from ' . $startDate->copy()->format('d/m/Y') . ' to ' . $endDate->copy()->format('d/m/Y') . ')';
                    $name .= PHP_EOL . $eng;
                }
            }
        } catch (\Exception $exception) {
            return $name;
        }

        return $name;
    }


    public function getStartEndAttribute()
    {
        $qty = $this->attributes['qty'];

        $data = json_decode($qty, true);

        if (is_array($data)) {
            return [
                'start' => $data['start'],
                'end' => $data['end']
            ];
        }

        return null;
    }

    public function getStartIndexAttribute()
    {
        $qty = $this->attributes['qty'];

        $data = json_decode($qty, true);

        if (is_array($data)) {
            return $data['start'];

        }

        return 0;
    }

    public function getEndIndexAttribute()
    {
        $qty = $this->attributes['qty'];

        $data = json_decode($qty, true);

        if (is_array($data)) {
            return $data['end'];

        }

        return 0;
    }

    public function getQtyTextAttribute()
    {
        $qty = $this->attributes['qty'];

        $data = json_decode($qty, true);

        if (is_array($data)) {
            if ($this->attributes['is_electric']) {
                $type = 'electric';
            } else {
                $type = 'water';
            }
            $data['type2'] = $type;

            return view('admin.money.form', $data)->render();
        }

        return view('admin.money.single_form', ['qty' => $qty])->render();
    }

    public function getQtyText2Attribute()
    {
        $qty = $this->attributes['qty'];

        $data = json_decode($qty, true);

        if (is_array($data)) {
            return $data['end'] - $data['start'];
        }

        if (!empty($this->attributes['start_date']) && !empty($this->attributes['end_date'])) {
            $startDate = Carbon::createFromFormat('Y-m-d', $this->attributes['start_date']);
            $endDate = Carbon::createFromFormat('Y-m-d', $this->attributes['end_date']);
            if ($this->moneyInfo) {
                $moneyInfo = $this->moneyInfo;
                if (!in_array($moneyInfo->type, [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])) {
                    return $qty;
                }

                if ($moneyInfo->contract) {
                    $contract = $moneyInfo->contract;

                    $check = Functions::checkFullPeriod($startDate->copy(), $endDate->copy(), $contract->day_collect);



                    if ($check) {
                        if ($qty < 1) {
                            if ($this->attributes['amount'] == $this->attributes['value']) {
                                return 1;
                            }
                        }
                        if (!empty($this->attributes['value'])) {

                            if (is_int($this->attributes['sum_amount'] / $this->attributes['value'])) {

                                return $this->attributes['sum_amount'] / $this->attributes['value'];
                            }


                            if (is_int($this->attributes['amount'] / $this->attributes['value'])) {
                                if(!empty($this->attributes['amount'] / $this->attributes['value'])) {
                                    return $this->attributes['amount'] / $this->attributes['value'];
                                }
                                return $qty;
                            }
                            return $qty;
                        }
//						if ( ! is_int( $qty ) ) {
//							return Functions::calculateDayInRange( $startDate->copy(), $endDate->copy(), $contract->day_collect );
//						}
                    }
                }
                return $qty;
            }
            //	$period = Functions::checkFullPeriod($startDate, $endDate);
            return $qty;
        }


        return $qty;
    }
}
