<?php

namespace App\Http\Controllers\Backend;

use App\Components\Functions;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\Notification;
use App\Models\RenterRoom;
use App\Models\Room;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Yajra\Datatables\Datatables;

class ElectricWaterController extends AdminController
{
    //
    public function getElectricWaterByAttributeView()
    {
        $hostels = Hostel::orderBy('id', 'desc');

        if(auth('backend')->check())
        {
            if(auth('backend')->user()->type == User::OWNER)
            {
                $hostels = Hostel::where('owner_id', auth('backend')->user()->id)->get();
            }
        }

        return view('admin.electric-water.index', compact('hostels'));
    }

    public function getElectricWaterByAttribute(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $dateAction = $request->input('date_action');

        $items = ElectricWater::query()
            ->with('contract')
            ->orderBy('id', 'desc');

        if(auth('backend')->check())
        {
            if(auth('backend')->user()->type == User::OWNER)
            {
                $hostels = Hostel::where('owner_id', auth('backend')->user()->id)->pluck('id')->toArray();
                $items = $items->whereIn('hostel_id', $hostels);
            }
        }

        if(!empty($hostelId))
        {
            $items = $items->where('hostel_id', $hostelId);
        }

        if(!empty($roomId))
        {
            $items = $items->where('room_id', $roomId);
        }

        if(!empty($dateAction))
        {
            $startDateAction = Carbon::createFromFormat('d/m/Y', '01/'.$dateAction)->startOfMonth()->toDateString();
            $endDateAction = Carbon::createFromFormat('d/m/Y', '01/'.$dateAction)->endOfMonth()->toDateString();
            $items = $items->whereBetween('date_action', [$startDateAction, $endDateAction]);
        }

        return Datatables::of($items)->addColumn('hostel', function ($item) {
            if ($item->hostel) {
                return $item->hostel->name;
            }
        })->addColumn('room', function ($item) {
            if ($item->room) {
                return $item->room->name;
            }
        })->editColumn('date_action', function ($item) {
            return $item->date_action->format('m/Y');
        })->editColumn('contract_id', function ($item) {
            return optional($item->contract)->name;
        })->addColumn('action', function ($item) {

        })->make(true);
    }

    public function store(Request $request)
    {
        $data = $request->all();

        $hostelId = $data['hostel_id'];
        $roomId = $data['room_id'];
        $dateAction = $data['date_action'];

        $infoRoom = Room::find($roomId);

        if (!$infoRoom) {
            return response([
                'status' => 0,
                'message' => 'Phòng không hợp lệ'
            ]);
        }

        if (empty($hostelId) || empty($roomId)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống nhà trọ / phòng trọ'
            ]);
        }
        if (empty($data['date_action'])) {
            $data['date_action'] = Carbon::now()->toDateTimeString();
            $startDateAction = Carbon::now()->startOfMonth()->toDateTimeString();
            $endDateAction = Carbon::now()->endOfMonth()->toDateTimeString();
        } else {
            $startDateAction = Carbon::createFromFormat('d/m/Y', '01/'.$data['date_action'])->startOfMonth()->toDateTimeString();
            $endDateAction = Carbon::createFromFormat('d/m/Y', '01/'.$data['date_action'])->endOfMonth()->toDateTimeString();
            $data['date_action'] = Carbon::createFromFormat('d/m/Y', '01/'.$data['date_action'])->toDateTimeString();
        }


        $check = ElectricWater::query()
            ->where('room_id', $roomId)
            ->where('date_action', '>=', $startDateAction)
            ->where('date_action', '<=', $endDateAction)
            ->first();

        if ($check) {
            $startElectric = $check->start_electric;
            $startWater = $check->start_water;
        } else {

            $lastInfo = ElectricWater::where('hostel_id', $hostelId)->where('room_id', $roomId)->latest()->first();


            if (!$lastInfo) {

                $startElectric = $infoRoom->start_electric;
                $startWater = $infoRoom->start_water;
            } else {

                $startElectric = $lastInfo->end_electric;
                $startWater = $lastInfo->end_water;
            }
        }


        if ($data['end_electric'] < $startElectric) {
            return response([
                'status' => 0,
                'message' => 'Số điện cuối không được nhỏ hơn số đầu'
            ]);
        }
        if ($data['end_water'] < $startWater) {
            return response([
                'status' => 0,
                'message' => 'Số nước cuối không được nhỏ hơn số đầu'
            ]);
        }

        $data['start_electric'] = $startElectric;
        $data['start_water'] = $startWater;
        $data['delta_electric'] = $data['end_electric'] - $startElectric;
        $data['delta_water'] = $data['end_water'] - $startWater;


        if ($check) {
            $check->update($data);
            $check->save();

            //Cập nhật sang bên phiếu thu chi
            $voucher = MoneyInfo::where('date_action', '>=', $startDateAction)->where('date_action', '<=', $endDateAction)->first();

            if ($voucher) {
                $moneyDetailElectric = MoneyDetail::where('money_info_id', $voucher->id)
                    ->where('is_electric', true)
                    ->first();
                if ($moneyDetailElectric) {
                    $moneyDetailElectric->qty = json_encode([
                        'start' => $startElectric,
                        'end' => $data['end_electric'],
                        'item_id' => $check->id
                    ]);

                    $moneyDetailElectric->amount = ($data['end_electric'] - $startElectric) * $moneyDetailElectric->value;

                    $moneyDetailElectric->save();
                }

                $moneyDetailWater = MoneyDetail::where('money_info_id', $voucher->id)
                    ->where('is_water', true)
                    ->first();

                if ($moneyDetailWater) {
                    $moneyDetailWater->qty = json_encode([
                        'start' => $startWater,
                        'end' => $data['end_water'],
                        'item_id' => $check->id
                    ]);

                    $moneyDetailWater->amount = ($data['end_water'] - $startWater) * $moneyDetailWater->value;

                    $moneyDetailWater->save();
                }

                $amount = MoneyDetail::where('money_info_id', $voucher->id)->sum('amount');

                $voucher->amount = $amount;
                $voucher->remain = $amount - $voucher->pay;
                $voucher->save();
            }

        } else {
            ElectricWater::create($data);
        }


        if($infoRoom)
        {
            $infoRoom->current_electric = $data['end_electric'];
            $infoRoom->current_water = $data['end_water'];
            $infoRoom->save();
        }

        $renters = RenterRoom::where('room_id', $data['room_id'])->get();

        foreach ($renters as $renter) {
            Notification::create( [
                'image' => auth('backend')->user()->image,
                'to_user'   => $renter->user_id,
                'hostel_id' => $data['hostel_id'],
                'room_id'   => $data['room_id'],
                'title'     => 'Thông báo từ itro.vn',
                'user_id'   => $this->user->id,
                'content'   => 'Tình hình sử dụng điện, nước tháng '.$dateAction.'. Phòng '.$infoRoom->name.' dùng '.$data['delta_electric'].' kwh điện và '.$data['delta_water'].' m3 nước. Chỉ số cuối là '.$data['end_electric'].' kwh và '.$data['end_water'].' m3',
            ] );

        }

        if ($request->ajax()) {
            return response([
                'status' => 1,
                'message' => 'Thành công'
            ]);
        }
    }

    public function getInfo(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $dateAction = $request->input('date_action');


        $endElectric = -1;
        $endWater = -1;

        if (empty($dateAction)) {
            $startDateAction = Carbon::now()->startOfMonth()->toDateTimeString();
            $endDateAction = Carbon::now()->endOfMonth()->toDateTimeString();
        } else {
            $startDateAction = Carbon::createFromFormat('d/m/Y', '01/'.$dateAction)->startOfMonth()->toDateTimeString();
            $endDateAction = Carbon::createFromFormat('d/m/Y', '01/'.$dateAction)->endOfMonth()->toDateTimeString();
        }

        $lastInfo = ElectricWater::where('hostel_id', $hostelId)->where('room_id', $roomId)
            ->where('date_action', '>=', $startDateAction)->where('date_action', '<=', $endDateAction)
            ->first();

        if ($lastInfo) {
            $startElectric = $lastInfo->start_electric;
            $startWater = $lastInfo->start_water;

            $endElectric = $lastInfo->end_electric;
            $endWater = $lastInfo->end_water;

        } else {

            $lastInfo = ElectricWater::where('hostel_id', $hostelId)->where('room_id', $roomId)->orderBy('id', 'desc')->first();


            if (!$lastInfo) {
                $infoRoom = Room::find($roomId);
                $startElectric = $infoRoom->start_electric;
                $startWater = $infoRoom->start_water;
            } else {
                //dd($lastInfo->start_electric);
                $startElectric = $lastInfo->end_electric;
                $startWater = $lastInfo->end_water;
            }
        }


        return view('admin.electric-water.info', compact('startElectric', 'startWater', 'endElectric', 'endWater'))->render();
    }


}
