<?php

namespace App\Console\Commands;

use App\Components\Functions;
use App\Models\CollectSpend;
use App\Models\Hostel;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\StatisticLog;
use App\Models\StatisticMonth;
use Carbon\Carbon;
use Illuminate\Console\Command;

class ReTkkdAll extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tkkd:all';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
	public function handle() {

//		$hostels = Hostel::query()
//		                 ->where('owner_id', 11092)
//		                 ->get();
//		$hostelsArr = $hostels->pluck('id')->toArray();

        \DB::table('statistic_months')->truncate();
//		StatisticMonth::query()->whereIn('hostel_id', $hostelsArr)->delete();
		$this->line( 'Run money details' );
		$moneydetails = MoneyDetail::query()->cursor();

		$bar = $this->output->createProgressBar( MoneyDetail::query()->count() );
		$bar->start();
		foreach ( $moneydetails as $item ) {

			$moneyInfoId = $item->money_info_id;
			$moneyInfo   = MoneyInfo::find( $moneyInfoId );
			if ( ! $moneyInfo ) {
				continue;
			}
			$contract  = $moneyInfo->contract;
			$startDate = $item->start_date;
			$endDate   = $item->end_date;
			if ( $moneyInfo->type == MoneyInfo::VOUCHER_CONTRACT || $moneyInfo->type == MoneyInfo::VOUCHER_ROOM_PRICE ) {
				if ( ! $contract ) {
					continue;
				}

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

				$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,
					] );
				}
			}

			$bar->advance();

		}
		$bar->finish();

		// \DB::table('statistic_logs')->truncate();
		StatisticLog::query()
		            ->where(function($q) {
			            $q->orWhere( 'note', 'NOT LIKE', '%Thu tiền đặt cọc HĐ:%' );
			            $q->orWhereNull('note');
		            })
		            ->delete();
		$this->line( '----' );
		$this->line( 'Run collect spends' );
		$cps = CollectSpend::query()->cursor();
		$bar = $this->output->createProgressBar( CollectSpend::query()->count() );
		foreach ( $cps as $item ) {
			$moneyInfoId = $item->money_info_id;
			$moneyInfo   = MoneyInfo::find( $moneyInfoId );
			$note        = $item->name;
			if ( empty( $note ) ) {
				$note = $item->note;
			}
			if ( $item->type == CollectSpend::COLLECT ) {
				if ( ! $item->is_deposit ) {
					if ( $moneyInfo ) {
						$itemStats = StatisticMonth::query()->where( 'money_info_id', $moneyInfo->id )
						                           ->whereRaw( 'current_paid < amount' )
						                           ->get();
						$collect   = $item->amount;

						if ( $itemStats->count() > 0 ) {
							foreach ( $itemStats as $itemStat ) {
								if ( $collect > 0 ) {
									$paid = $itemStat->current_paid + $collect;
									if ( $paid > $itemStat->amount ) {
										$collect    = $paid - $itemStat->amount;
										$logCollect = $itemStat->amount - $itemStat->current_paid;
										$paid       = $itemStat->amount;
									} else {
										$logCollect = $collect;
										$collect    = 0;
									}
									if ( $logCollect > 0 ) {
										StatisticLog::create( [
											'amount'             => $logCollect,
											'month'              => $itemStat->month,
											'year'               => $itemStat->year,
											'type'               => CollectSpend::COLLECT,
											'hostel_id'          => $itemStat->hostel_id,
											'room_id'            => $itemStat->room_id,
											'collect_spend_id'   => $item->id,
											'statistic_month_id' => $itemStat->id,
											'contract_id'        => $moneyInfo->contract_id,
											'note'               => $note
										] );
									}

									$itemStat->current_paid = $paid;
									$itemStat->save();


								}
							}
						} else {
							StatisticLog::create( [
								'amount'           => $item->amount,
								'month'            => ! empty( $moneyInfo->date_action ) ? $moneyInfo->date_action->month : Carbon::now()->month,
								'year'             => ! empty( $moneyInfo->date_action ) ? $moneyInfo->date_action->year : Carbon::now()->year,
								'type'             => CollectSpend::COLLECT,
								'hostel_id'        => $item->hostel_id,
								'room_id'          => $item->room_id,
								'collect_spend_id' => $item->id,
								'contract_id'      => $moneyInfo->contract_id,
								'note'             => $note
							] );
						}
					} else {
						$itemStat = StatisticMonth::create( [
							'month'         => ! empty( $item->date_action ) ? $item->date_action->month : Carbon::now()->month,
							'year'          => ! empty( $item->date_action ) ? $item->date_action->year : Carbon::now()->year,
							'amount'        => $item->amount,
							'contract_id'   => $item->contract_id,
							'room_id'       => $item->room_id,
							'hostel_id'     => $item->hostel_id,
							'money_info_id' => $item->money_info_id,

						] );
						StatisticLog::create( [
							'amount'             => $item->amount,
							'month'              => ! empty( $item->date_action ) ? $item->date_action->month : Carbon::now()->month,
							'year'               => ! empty( $item->date_action ) ? $item->date_action->year : Carbon::now()->year,
							'type'               => CollectSpend::COLLECT,
							'hostel_id'          => $item->hostel_id,
							'room_id'            => $item->room_id,
							'collect_spend_id'   => $item->id,
							'statistic_month_id' => $itemStat->id,
							'contract_id'        => $item->contract_id,
							'note'               => $note
						] );
					}
				}
			} else {
				if ( ! $item->is_deposit ) {
					StatisticLog::create( [
						'amount'           => $item->amount,
						'month'            => ! empty( $item->date_action ) ? $item->date_action->month : Carbon::now()->month,
						'year'             => ! empty( $item->date_action ) ? $item->date_action->year : Carbon::now()->year,
						'type'             => CollectSpend::SPEND,
						'hostel_id'        => $item->hostel_id,
						'room_id'          => $item->room_id,
						'collect_spend_id' => $item->id,
						'contract_id'      => $item->contract_id,
						'owner_id'         => $item->owner_id,
						'note'             => $note
					] );
				}
			}
			$bar->advance();
		}
		$bar->finish();

		$items = StatisticLog::query()
		                     ->onlyTrashed()
		                     ->has( 'contract' )
		                     ->where( 'note', 'LIKE', '%Thu tiền đặt cọc HĐ:%' )
		                     ->get();

		foreach ( $items as $item ) {
			$statMonth = StatisticMonth::withTrashed()->find( $item->statistic_month_id );
			if ( $statMonth ) {
				$statMonth->restore();
			}

			$item->restore();
			//$this->line( 'Done with ' . $item->id );
		}
	}
}
