<?php

namespace App\Http\Controllers\Api\v1;

use App\Components\Functions;
use App\Events\LogAction;
use App\Models\CollectSpend;
use App\Models\Contract;
use App\Models\ContractFee;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\HostelFee;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\Notification;
use App\Models\Renter;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\TypeSpend;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use MongoDB\BSON\Type;

class ElectricWaterController extends BaseController
{
    //
    public function getItems(Request $request)
    {
        $items = ElectricWater::orderBy('id', 'desc');
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $startDateI = $request->input('start_date');
        $endDateI = $request->input('end_date');

        $userId = $this->user->id;

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

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

            $items = $items->select(\DB::raw('MONTH(date_action) as month, YEAR(date_action) as year'))->groupBy(\DB::raw('month, year'));
        } else {

            $hostels = Hostel::where('owner_id', $userId)->pluck('id')->toArray();

            $items = $items->select(\DB::raw('MONTH(date_action) as month, YEAR(date_action) as year'))
                ->whereIn('hostel_id', $hostels)->groupBy(\DB::raw('month, year'));
        }

        if (!empty($startDateI) && !empty($endDateI)) {
            $startDateP = Carbon::createFromFormat('d/m/Y', '01/'.$startDateI)->startOfMonth()->toDateTimeString();
            $endDateP = Carbon::createFromFormat('d/m/Y', '01/'.$endDateI)->endOfMonth()->toDateTimeString();


            $items = $items->whereBetween('date_action', [$startDateP, $endDateP]);
        }

        $items = $items->get();

        $retVal = [];

        foreach ($items as $item) {
            $month = $item->month;
            $year = $item->year;
            $startDate = Carbon::createFromFormat('d/m/Y', '01/'.$item->month . '/' . $item->year)->startOfMonth()->toDateTimeString();
            $endDate = Carbon::createFromFormat('d/m/Y', '01/'.$item->month . '/' . $item->year)->endOfMonth()->toDateTimeString();

            if (!empty($hostelId)) {
                $histories = ElectricWater::where('hostel_id', $hostelId);

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

                $histories = $histories->whereBetween('date_action', [$startDate, $endDate])->get();
            } else {

                $hostels = Hostel::where('owner_id', $userId)->pluck('id')->toArray();

                $histories = ElectricWater::whereIn('hostel_id', $hostels)->whereBetween('date_action', [
                    $startDate,
                    $endDate
                ])
                    ->get();
            }

            foreach ($histories as $history) {
                $history->room_name = $history->room->name;
                unset($history->room);
            }

            $itemVal = [
                'time' => 'Tháng ' . $month . '/' . $year,
                'histories' => $histories
            ];

            $retVal[] = $itemVal;

        }

        return response([
            'status' => 1,
            'data' => $retVal
        ]);

    }

    /**
     * @api {post} /items Lấy danh sách chốt điện nước
     * @apiName items
     * @apiGroup ElectricWater
     * @apiDescription Lấy danh sách chốt điện nước.
     * @apiParam {String} hostel_id
     * @apiParam {String} room_id
     * @apiParam {String} month Dạng m/Y
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getItems2(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $month = $request->input('month');


        $items = ElectricWater::query()
            ->has('room')
            ->with([
                'hostel',
                'room'
            ])
            ->when(!empty($hostelId), function ($q) use ($hostelId) {
                $q->where('hostel_id', $hostelId);
            }, function ($q) {
                if ($this->user->type == User::STAFF) {
                    $hostelArrs = Functions::getHostelArrStaffApi($this->user);
                } else {
                    $hostelArrs = Hostel::query()
                        ->where('owner_id', $this->user->id)
                        ->pluck('id')
                        ->toArray();

                }
                $q->whereIn('hostel_id', $hostelArrs);
            });

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

//        if ($this->user->type == User::STAFF) {
//            $items = $items->where('user_id', $this->user->id);
//        }
        if (!empty($month)) {
            $startDate = Carbon::createFromFormat('d/m/Y', '01/' . $month)->startOfMonth()->toDateTimeString();
            $endDate = Carbon::createFromFormat('d/m/Y', '01/' . $month)->endOfMonth()->toDateTimeString();

            $items = $items->whereBetween('date_action', [$startDate, $endDate]);
        }

        $items = $items->get();

        $returnArr = [];

        foreach ($items as $item) {

            $name = null;

            if ($item->user) {
                if (!empty(trim($item->user->name))) {
                    $name = $item->user->name;
                } else {
                    $name = $item->user->first_name . ' ' . $item->user->last_name;
                }
            }

            $returnArr[] = [
                'id' => $item->id,
                'contract_name' => optional($item->contract)->name,
                'contract_id' => optional($item->contract)->id,
                'hostel_id' => ($item->hostel) ? $item->hostel->id : null,
                'room_id' => ($item->room) ? $item->room->id : null,
                'room_name' => ($item->room) ? $item->room->name : null,
                'hostel_name' => ($item->hostel) ? $item->hostel->name : null,
                'month' => !empty($item->date_action) ? $item->date_action->format('m/Y') : null,
                'start_electric' => $item->start_electric,
                'end_electric' => $item->end_electric,
                'start_water' => $item->start_water,
                'end_water' => $item->end_water,
                'delta_electric' => $item->delta_electric,
                'delta_water' => $item->delta_water,
                'user' => $name,
                'date_execution' => !empty($item->date_execution) ? $item->date_execution->format('d/m/Y') : null,
                'start_electric_image' => !empty($item->start_electric_image) ? '/files/' . $item->start_electric_image : null,
                'end_electric_image' => !empty($item->end_electric_image) ? '/files/' . $item->end_electric_image : null,
                'start_water_image' => !empty($item->start_water_image) ? '/files/' . $item->start_water_image : null,
                'end_water_image' => !empty($item->end_water_image) ? '/files/' . $item->end_water_image : null,
                'created_at' => $item->created_at
            ];
        }

        return response([
            'status' => 1,
            'data' => $returnArr
        ]);
    }

    /**
     * @api {post} /items-for-renter Lấy danh sách chốt điện nước cho người thuê
     * @apiName items-for-renter
     * @apiGroup ElectricWater
     * @apiDescription Lấy danh sách chốt điện nước cho người thuê
     * @apiParam {String} hostel_id
     * @apiParam {String} room_id
     * @apiParam {String} start_date Dạng m/Y
     * * @apiParam {String} end_date Dạng m/Y
     * * * @apiParam {String} contract_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getItemsForRenter(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $contractId = $request->input('contract_id');


        $items = ElectricWater::query()
            ->has('room')
            ->with([
                'hostel',
                'room',
                'user'
            ])
            ->when(!empty($hostelId), function ($q) use ($hostelId) {
                $q->where('hostel_id', $hostelId);
            }, function ($q) {
                if ($this->user->type == User::STAFF) {
                    $hostelArrs = Functions::getHostelArrStaffApi($this->user);
                } else {
                    $hostelArrs = Hostel::query()
                        ->where('owner_id', $this->user->id)
                        ->pluck('id')
                        ->toArray();

                }
                $q->whereIn('hostel_id', $hostelArrs);
            });

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

//        if ($this->user->type == User::STAFF) {
//            $items = $items->where('user_id', $this->user->id);
//        }
        if (!empty($startDate)) {
            $startDate = Carbon::createFromFormat('d/m/Y', '01/' . $startDate)->startOfMonth()->startOfDay()->toDateTimeString();
            $items = $items->where('date_action', '>=', $startDate);
        }
        if (!empty($endDate)) {
            $endDate = Carbon::createFromFormat('d/m/Y', '01/' . $endDate)->endOfMonth()->endOfDay()->toDateTimeString();
            $items = $items->where('date_action', '<=', $endDate);
        }

        $items = $items->where('contract_id', $contractId)
            ->orderBy('date_action', 'desc')
            ->get();


        $returnArr = [];

        foreach ($items as $item) {

            $name = null;

            if ($item->user) {
                if (!empty(trim($item->user->name))) {
                    $name = $item->user->name;
                } else {
                    $name = $item->user->first_name . ' ' . $item->user->last_name;
                }
            }

            $returnArr[] = [
                'id' => $item->id,
                'contract_name' => optional($item->contract)->name,
                'contract_id' => optional($item->contract)->id,
                'hostel_id' => ($item->hostel) ? $item->hostel->id : null,
                'room_id' => ($item->room) ? $item->room->id : null,
                'room_name' => ($item->room) ? $item->room->name : null,
                'hostel_name' => ($item->hostel) ? $item->hostel->name : null,
                'month' => !empty($item->date_action) ? $item->date_action->format('m/Y') : null,
                'start_electric' => $item->start_electric,
                'end_electric' => $item->end_electric,
                'start_water' => $item->start_water,
                'end_water' => $item->end_water,
                'delta_electric' => $item->delta_electric,
                'delta_water' => $item->delta_water,
                'user' => $name,
                'date_execution' => !empty($item->date_execution) ? $item->date_execution->format('d/m/Y') : null,
                'start_electric_image' => !empty($item->start_electric_image) ? '/files/' . $item->start_electric_image : null,
                'end_electric_image' => !empty($item->end_electric_image) ? '/files/' . $item->end_electric_image : null,
                'start_water_image' => !empty($item->start_water_image) ? '/files/' . $item->start_water_image : null,
                'end_water_image' => !empty($item->end_water_image) ? '/files/' . $item->end_water_image : null,
            ];
        }

        return response([
            'status' => 1,
            'data' => $returnArr
        ]);
    }

    /**
     * @api {post} /detail Lấy chi tiet chốt điện nước
     * @apiName detail
     * @apiGroup ElectricWater
     * @apiDescription Lấy chi tiet chốt điện nước
     * @apiParam {String} id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function detail(Request $request)
    {
        $id = $request->input('id');
        $item = ElectricWater::find($id);
        $name = null;
        if ($item->user) {
            if (!empty(trim($item->user->name))) {
                $name = $item->user->name;
            } else {
                $name = $item->user->first_name . ' ' . $item->user->last_name;
            }
        }
        $retVal = [
            'id' => $item->id,
            'contract_name' => optional($item->contract)->name,
            'contract_id' => optional($item->contract)->id,
            'hostel_id' => ($item->hostel) ? $item->hostel->id : null,
            'room_id' => ($item->room) ? $item->room->id : null,
            'room_name' => ($item->room) ? $item->room->name : null,
            'hostel_name' => ($item->hostel) ? $item->hostel->name : null,
            'month' => !empty($item->date_action) ? $item->date_action->format('m/Y') : null,
            'start_electric' => $item->start_electric,
            'end_electric' => $item->end_electric,
            'start_water' => $item->start_water,
            'end_water' => $item->end_water,
            'delta_electric' => $item->delta_electric,
            'delta_water' => $item->delta_water,
            'user' => $name,
            'date_execution' => !empty($item->date_execution) ? $item->date_execution->format('d/m/Y') : null,
            'start_electric_image' => !empty($item->start_electric_image) ? '/files/' . $item->start_electric_image : null,
            'end_electric_image' => !empty($item->end_electric_image) ? '/files/' . $item->end_electric_image : null,
            'start_water_image' => !empty($item->start_water_image) ? '/files/' . $item->start_water_image : null,
            'end_water_image' => !empty($item->end_water_image) ? '/files/' . $item->end_water_image : null,
        ];
        return response([
            'status' => 1,
            'data' => $retVal
        ]);
    }

    /**
     * @api {get} /item-month Lấy thông tin điện nước theo tháng
     * @apiName item-month
     * @apiGroup electric-water
     * @apiDescription Api Lấy thông tin điện nước theo tháng
     * @apiParam {String} month Dạng m/Y
     * @apiParam {String} room_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function getItemMonth(Request $request)
    {

        $roomId = $request->input('room_id');
        $month = $request->input('month');
        $contractId = $request->input('contract_id');

        if (empty($roomId)) {
            return response([
                'status' => 0,
                'message' => 'Không được để trống phòng trọ'
            ]);
        }

        $room = Room::find($roomId);
        if (empty($month)) {
            return response([
                'status' => 0,
                'message' => 'Không được để trống tháng'
            ]);
        }

        $item = ElectricWater::query()
            ->where('room_id', $roomId);

        $month = '01/' . $month;

        if (!empty($month)) {
            $startDateAction = Carbon::createFromFormat('d/m/Y', $month)->startOfMonth()->toDateTimeString();
            $endDateAction = Carbon::createFromFormat('d/m/Y', $month)->endOfMonth()->toDateTimeString();
            $item = $item->whereBetween('date_action', [$startDateAction, $endDateAction]);
        }

        if ($contractId) {
            $item = $item->where('contract_id', $contractId);
        }

        $item = $item->first();

        if ($item) {
            $item->room_name = $item->room->name;
            unset($item->room);
        } else {

            $startDateAction = Carbon::createFromFormat('d/m/Y', $month)->startOfMonth()->toDateTimeString();
            $endDateAction = Carbon::createFromFormat('d/m/Y', $month)->endOfMonth()->toDateTimeString();

            $contract = Contract::find($contractId);
            $dateContract = $contract->date_contract;

            $itemBefore = ElectricWater::query()->where('room_id', $roomId)
                ->where('date_action', '<=', $startDateAction)
                ->whereDate('date_action', '>=', $dateContract->copy()->startOfMonth()->startOfDay())
                ->where('contract_id', $contractId)
                // ->whereYear('date_action', '>=', $dateContract->copy()->startOfDay())
                ->orderBy('date_action', 'desc')->first();

            if ($itemBefore) {
                $itemBefore->room_name = $itemBefore->room->name;
                $itemBefore->start_electric = $itemBefore->end_electric;
                $itemBefore->start_water = $itemBefore->end_water;
                $itemBefore->delta_electric = 0;
                $itemBefore->delta_water = 0;
                unset($itemBefore->room);

                return response([
                    'status' => 1,
                    'data' => $itemBefore
                ]);
            } else {

                $item = new \stdClass();
                $item->room_name = $room->name;
                $contractFees = ContractFee::query()->with('fee')->where('contract_id', $contractId)->get();

                $item->start_electric = 0;
                $item->end_electric = 0;
                $item->start_water = 0;
                $item->end_water = 0;
                foreach ($contractFees as $contractFee) {
                    $feeItem = $contractFee->fee;
                    if ($feeItem) {
                        if (in_array($feeItem->type, [
                            HostelFee::ELECTRIC,
                            HostelFee::ELECTRIC_BY_CLOCK
                        ])) {
                            $item->start_electric = $contractFee->qty;
                            $item->end_electric = $contractFee->qty;
                        } else if (in_array($feeItem->type, [
                            HostelFee::WATER,
                            HostelFee::WATER_BY_CLOCK
                        ])) {
                            $item->start_water = $contractFee->qty;
                            $item->end_water = $contractFee->qty;
                        }
                    }
                }

                $item->delta_electric = 0;
                $item->delta_water = 0;

                return response([
                    'status' => 1,
                    'data' => $item
                ]);

            }

        }

        return response([
            'status' => 1,
            'data' => $item
        ]);
    }

    /**
     * @api {get} /item-hostel Lấy thông tin điện nước theo nhà trọ
     * @apiName item-hostel
     * @apiGroup electric-water
     * @apiDescription Api Lấy thông tin điện nước theo nhà trọ
     * @apiParam {String} month Dạng m/Y
     * @apiParam {String} hostel_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getItemHostel(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $month = $request->input('month');

        $ownerId = $this->user->id;
        if ($this->user->type == User::STAFF) {
            $ownerId = $this->user->staff_owner_id;
        }

        if (empty($hostelId)) {
            $hostels = Hostel::query()->where('owner_id', $ownerId)->get();
        } else {
            $hostels = Hostel::query()->where('id', $hostelId)->get();
        }
        $hostelArr = $hostels->pluck('id')->toArray();
        $rooms = Room::query()->whereIn('hostel_id', $hostelArr)->with('hostel')->get();
        $retVal = [];
        $month = '01/' . $month;
        foreach ($rooms as $room) {

            $itemArr = [];
            $itemArr['room_id'] = $room->id;
            $itemArr['room_name'] = $room->name;
            $item = ElectricWater::query()->where('room_id', $room->id);


            if (!empty($month)) {
                $startDateAction = Carbon::createFromFormat('d/m/Y', $month)->startOfMonth()->toDateTimeString();
                $endDateAction = Carbon::createFromFormat('d/m/Y', $month)->endOfMonth()->toDateTimeString();
                $item = $item->whereBetween('date_action', [$startDateAction, $endDateAction]);
            }

            $item = $item->first();

            if ($item) {
                $item->room_name = $item->room->name;
                unset($item->room);
            } else {

                $startDateAction = Carbon::createFromFormat('d/m/Y', $month)->subMonth()->startOfMonth()->toDateTimeString();
                $endDateAction = Carbon::createFromFormat('d/m/Y', $month)->subMonth()->endOfMonth()->toDateTimeString();
                $itemBefore = ElectricWater::query()->where('room_id', $room->id)->latest('id')->first();

                if ($itemBefore) {
                    $itemBefore->room_name = $itemBefore->room->name;
                    $itemBefore->start_electric = $itemBefore->end_electric;
                    $itemBefore->start_water = $itemBefore->end_water;
                    $itemBefore->delta_electric = 0;
                    $itemBefore->delta_water = 0;
                    unset($itemBefore->room);
                    $item = clone $itemBefore;
                } else {
                    $item = new \stdClass();
                    $item->room_name = $room->name;
                    $contract = Contract::query()->where('room_id', $room->id)->where('status', '<>', Contract::LIQUIDATED)->first();
                    if (!$contract) {
                        continue;
                    }
                    $contractId = $contract->id;
                    $contractFees = ContractFee::query()->where('contract_id', $contractId)->get();

                    $item->start_electric = 0;
                    $item->end_electric = 0;
                    $item->start_water = 0;
                    $item->end_water = 0;
                    foreach ($contractFees as $contractFee) {
                        $feeId = $contractFee->fee_id;
                        $feeItem = HostelFee::find($feeId);
                        if ($feeItem) {
                            if ($feeItem->type == HostelFee::ELECTRIC) {
                                $item->start_electric = $contractFee->qty;
                                $item->end_electric = $contractFee->qty;
                            }

                            if ($feeItem->type == HostelFee::WATER) {
                                $item->start_water = $contractFee->qty;
                                $item->end_water = $contractFee->qty;
                            }
                        }
                    }

                    $item->delta_electric = 0;
                    $item->delta_water = 0;

                }


            }
            $itemArr['hostel_id'] = $room->hostel->id;
            $itemArr['hostel_name'] = $room->hostel->name;
            $itemArr['item'] = [
                'start_electric' => $item->start_electric,
                'end_electric' => $item->end_electric,
                'start_water' => $item->start_water,
                'end_water' => $item->end_water
            ];
            $retVal[] = $itemArr;
        }


        return response([
            'status' => 1,
            'data' => $retVal
        ]);
    }

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

        if (empty($hostelId)) {
            return response([
                'status' => 0,
                'message' => 'Không được để trống nhà trọ'
            ]);
        }

        if (empty($roomId)) {
            return response([
                'status' => 0,
                'message' => 'Không được để trống phòng trọ'
            ]);
        }

        $item = ElectricWater::where('hostel_id', $hostelId)->where('room_id', $roomId)->latest()->first();
        if ($item) {
            $item->room_name = $item->room->name;
            unset($item->room);
        }

        return response([
            'status' => 1,
            'data' => $item
        ]);
    }

    /**
     * @api {post} /create Tạo điện nước
     * @apiName create
     * @apiGroup electric-water
     * @apiDescription Api Tạo điện nước
     * @apiParam {String} hostel_id
     * @apiParam {String} room_id
     * @apiParam {String} date_action Chốt cho tháng, gửi lên dạng m/Y
     * @apiParam {String} date_execution Ngày chốt, gửi lên dạng d/m/Y
     * @apiParam {String} start_electric
     * @apiParam {String} end_electric
     * @apiParam {String} start_water
     * @apiParam {String} end_water
     *
     * @apiParam {File} start_water_image
     * @apiParam {File} end_water_image
     * @apiParam {File} start_electric_image
     * @apiParam {File} end_electric_image
     *
     * @apiParam {String} contract_id Mã hợp đồng
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

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

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

        $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 ($request->file('start_electric_image') && $request->file('start_electric_image')->isValid()) {
            $image = Functions::uploadImage($request->file('start_electric_image'));
            $data['start_electric_image'] = $image;
        }

        if ($request->file('end_electric_image') && $request->file('end_electric_image')->isValid()) {
            $image = Functions::uploadImage($request->file('end_electric_image'));
            $data['end_electric_image'] = $image;
        }

        if ($request->file('start_water_image') && $request->file('start_water_image')->isValid()) {
            $image = Functions::uploadImage($request->file('start_water_image'));
            $data['start_water_image'] = $image;
        }

        if ($request->file('end_water_image') && $request->file('end_water_image')->isValid()) {
            $image = Functions::uploadImage($request->file('end_water_image'));
            $data['end_water_image'] = $image;
        }

        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();
        }

        if (!empty($dateExecution)) {
            $data['date_execution'] = Carbon::createFromFormat('d/m/Y', $data['date_execution'])->toDateTimeString();
        }

        $startElectric = $data['start_electric'];
        $startWater = $data['start_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;

        $check = ElectricWater::where('room_id', $roomId)
            ->where('hostel_id', $hostelId)
            ->whereBetween('date_action', [$startDateAction, $endDateAction]);

        if (!empty($data['contract_id'])) {
            $check = $check->where('contract_id', $data['contract_id']);
        }

        $check = $check->first();

        if ($check) {
            $check->delete();
        }

        $data['user_id'] = $this->user->id;

        $item = ElectricWater::create($data);

        $content = 'Chốt điện nước tháng ' . $dateAction . ', số điện: ' . $data['end_electric'] . ', số nước: ' . $data['end_water'];
        $payload = [
            'id' => $item->id,
            'type' => 'EW'
        ];

        $renterRooms = RenterRoom::where('room_id', $roomId)->get();

        foreach ($renterRooms as $renterRoom) {
            Notification::create([
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'title' => 'Thông báo từ itro.vn',
                'to_user' => $renterRoom->user_id,
                'content' => $content,
                'user_id' => $this->user->id,
                'payload' => json_encode($payload)
            ]);
        }

        $user = Functions::getCurrentUser();
        $desc = '{' . optional($user)->name . '} chốt điện nước tháng {' . $item->date_action->format('m/Y') . '} cho khách {' . optional($item->contract)->name . '}  phòng {' . optional($item->room)->name . '} nhà {' . optional($item->hostel)->name . '}';

        event(new LogAction([
            'type' => 'create-ew',
            'user_id' => optional($user)->id,
            'object_id' => $item->id,
            'hostel_id' => $item->hostel_id,
            'room_id' => $item->room_id,
            'properties' => $item->toArray(),
            'desc' => $desc
        ]));

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    /**
     * @api {post} /update Cập nhật điện nước
     * @apiName update
     * @apiGroup electric-water
     * @apiDescription Api cập nhật điện nước
     * @apiParam {String} hostel_id
     * @apiParam {String} room_id
     * @apiParam {String} date_action Chốt cho tháng, gửi lên dạng m/Y
     * @apiParam {String} date_execution Ngày chốt, gửi lên dạng d/m/Y
     * @apiParam {String} start_electric
     * @apiParam {String} end_electric
     * @apiParam {String} start_water
     * @apiParam {String} end_water
     * @apiParam {String} id
     *
     * @apiParam {File} start_water_image
     * @apiParam {File} end_water_image
     * @apiParam {File} start_electric_image
     * @apiParam {File} end_electric_image
     *
     *
     * @apiParam {String} contract_id Mã hợp đồng
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

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

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

        $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 ($request->file('start_electric_image') && $request->file('start_electric_image')->isValid()) {
            $image = Functions::uploadImage($request->file('start_electric_image'));
            $data['start_electric_image'] = $image;
        }

        if ($request->file('end_electric_image') && $request->file('end_electric_image')->isValid()) {
            $image = Functions::uploadImage($request->file('end_electric_image'));
            $data['end_electric_image'] = $image;
        }

        if ($request->file('start_water_image') && $request->file('start_water_image')->isValid()) {
            $image = Functions::uploadImage($request->file('start_water_image'));
            $data['start_water_image'] = $image;
        }

        if ($request->file('end_water_image') && $request->file('end_water_image')->isValid()) {
            $image = Functions::uploadImage($request->file('end_water_image'));
            $data['end_water_image'] = $image;
        }

        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();
        }

        if (!empty($dateExecution)) {
            $data['date_execution'] = Carbon::createFromFormat('d/m/Y', $data['date_execution'])->toDateTimeString();
        }

        $startElectric = $data['start_electric'];
        $startWater = $data['start_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;

        $check = ElectricWater::query()->where('room_id', $roomId)
            ->where('hostel_id', $hostelId)
            ->whereBetween('date_action', [$startDateAction, $endDateAction]);

        $contractId = $request->input('contract_id');

        $moneyDetails = MoneyDetail::query()
            ->whereHas('moneyInfo', function ($q) use ($startDateAction, $endDateAction, $roomId, $contractId) {
                $q->where('type', MoneyInfo::VOUCHER_SERVICE)
                    ->where('room_id', $roomId)
                    ->where('contract_id', $contractId);
                $q->whereBetween('date_action', [$startDateAction, $endDateAction]);
            })
            ->where(function ($q) {
                $q->orWhere('is_water', true);
                $q->orWhere('is_electric', true);
            })
            ->count();

        if ($moneyDetails > 0) {
            return response([
                'status' => 0,
                'message' => 'Hóa đơn dịch vụ đã được lập cho tháng chốt. Để sửa điện nước bạn cần xóa hóa đơn dịch vụ đã lập trước đó'
            ]);
        }


        if (!empty($data['contract_id'])) {
            $check = $check->where('contract_id', $data['contract_id']);
        }

        $check = $check->first();

        if ($check) {
            if ($check->id != $request->input('id')) {
                $check->delete();
            }
        }

        $data['user_id'] = $this->user->id;

        $item = ElectricWater::find($request->input('id'));
        if ($item) {
            $item->update($data);
        } else {
            $item = ElectricWater::create($data);
        }

        if ($request->has('delete_start_electric_image')) {
            $item->start_electric_image = null;
        }

        if ($request->has('delete_start_water_image')) {
            $item->start_water_image = null;
        }

        if ($request->has('delete_end_electric_image')) {
            $item->end_electric_image = null;
        }

        if ($request->has('delete_end_water_image')) {
            $item->end_water_image = null;
        }
        $item->save();

//		ElectricWater::query()
//		             ->where( 'id', $request->input( 'id' ) )
//		             ->update( $data );

        $content = 'Chốt điện nước tháng ' . $dateAction . ', số điện: ' . $data['end_electric'] . ', số nước: ' . $data['end_water'];

        $payload = [
            'id' => $item->id,
            'type' => 'EW'
        ];

        $renterRooms = RenterRoom::query()->where('room_id', $roomId)->get();

        foreach ($renterRooms as $renterRoom) {
            Notification::create([
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'title' => 'Thông báo từ itro.vn',
                'to_user' => $renterRoom->user_id,
                'content' => $content,
                'user_id' => $this->user->id,
                'payload' => json_encode($payload)
            ]);
        }

        $user = Functions::getCurrentUser();
        $desc = '{' . $user->name . '}  sửa điện nước tháng {' . optional($item->date_action)->format('m/Y') . '} 
        của khách {' . optional($item->contract)->name . '} phòng {'.optional($item->room)->name.'} nhà {'.optional($item->hostel)->name.'}';
        event(new LogAction([
            'type' => 'update-ew',
            'user_id' => optional($user)->id,
            'object_id' => $item->id,
            'hostel_id' => $item->hostel_id,
            'room_id' => $item->room_id,
            'desc' => $desc
        ]));

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }


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

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

        $infoRoom = Room::find($roomId);
        $dateAction = $data['date_action'];

        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::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 {
            $data['user_id'] = $this->user->id;
            $data['date_execution'] = Carbon::now()->toDateString();
            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' => $this->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',
            ]);

        }


        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);

    }

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

        if (empty($hostelId)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống hostel_id'
            ]);
        }

        if (empty($dateAction)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống date_action'
            ]);
        }

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

        $numberRoomSet = ElectricWater::where('hostel_id', $hostelId)
            ->whereBetween('date_action', [$startDateAction, $endDateAction])
            ->count();

        $numberRoom = Room::where('hostel_id', $hostelId)->count();

        if ($numberRoom == $numberRoomSet) {
            return response([
                'status' => 1,
                'data' => true
            ]);
        }

        return response([
            'status' => 1,
            'data' => false
        ]);

    }


    /**
     * @api {post} /delete Xóa điện nước
     * @apiName delete
     * @apiGroup ElectricWater
     * @apiDescription Api Xóa điện nước
     * @apiParam {String} id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function destroy(Request $request)
    {
        $id = $request->input('id');
        $item = ElectricWater::find($id);

        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if ($item) {
            $user = Functions::getCurrentUser();
            $desc = '{' . optional($user)->name . '} xóa điện nước tháng {' . $item->date_action->format('m/Y') . '} cho khách {' . optional($item->contract)->name . '}  phòng {' . optional($item->room)->name . '} nhà {' . optional($item->hostel)->name . '}';

            event(new LogAction([
                'type' => 'delete-ew',
                'user_id' => optional($user)->id,
                'object_id' => $item->id,
                'hostel_id' => $item->hostel_id,
                'room_id' => $item->room_id,
                'properties' => $item->toArray(),
                'desc' => $desc
            ]));
            $item->delete();
        }



        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    /**
     * @api {get} /check Kiểm tra HĐ có thiếu điện nước không
     * @apiName check
     * @apiGroup ElectricWater
     * @apiDescription Api Kiểm tra HĐ có thiếu điện nước không
     * @apiParam {String} contract_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function checkEw(Request $request)
    {
        $contractId = $request->input('contract_id');
        $contract = Contract::find($contractId);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $status = 1;
        $message = 'Đã thanh toán đủ';
        $dateEnableCarbon = $contract->date_enable;
        //  $dateEnableCarbon = Carbon::createFromFormat('Y-m-d', $dateEnable);
        while ($dateEnableCarbon->lessThanOrEqualTo(Carbon::now())) {
            $dateEnableCarbon = $dateEnableCarbon->startOfMonth();
            $dateEnableCarbon2 = clone $dateEnableCarbon;
            $dateEnableCarbon3 = clone $dateEnableCarbon;
            $check = ElectricWater::where('contract_id', $contractId)
                ->whereBetween('date_action', [
                    $dateEnableCarbon2->toDateString(),
                    $dateEnableCarbon2->endOfMonth()->toDateString()
                ])->count();
            if ($check == 0) {
                $message = 'Bạn chưa chốt điện nước từ ' . $dateEnableCarbon3->format('d/m/Y') . ' đến ' . $dateEnableCarbon3->endOfMonth()->format('d/m/Y') . ' cho HĐ này. Vui lòng chốt điện nước để không bị mất doanh thu';
                $status = 0;
                break;
            }
            $dateEnableCarbon = $dateEnableCarbon->startOfMonth()->addMonth(1);
        }

        return response([
            'status' => 1,
            'data' => [
                'status' => $status,
                'message' => $message
            ],
            'message' => 'Thành công'
        ]);

    }

    public function getPaymentInMonth(Request $request)
    {
        $ownerId = $this->user->id;
        $month = $request->input('month');
        if (empty($month)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $date = Carbon::createFromFormat('d/m/Y', '1/' . $month);
        if ($this->user->type == User::STAFF) {
            $hostelArrs = Functions::getHostelArrStaffApi($this->user);
            $ownerId = $this->user->staff_owner_id;
        } else {
            $hostelArrs = Hostel::query()->where('owner_id', $ownerId)->pluck('id')->toArray();
        }

        $hostels = Hostel::query()->whereIn('id', $hostelArrs)->get();
        $result = [];

        $typeSpendWater = TypeSpend::query()->where('owner_id', $ownerId)
            ->where('is_default', TypeSpend::TIEN_NUOC)
            ->first();

        $typeSpendElectric = TypeSpend::query()->where('owner_id', $ownerId)
            ->where('is_default', TypeSpend::TIEN_DIEN)
            ->first();

        foreach ($hostels as $hostel) {

            $inE = MoneyDetail::query()
                ->where('hostel_id', $hostel->id)
                ->where('is_electric', true)
                ->whereHas('moneyInfo', function ($q) use ($date) {
                    $q->whereBetween('date_action', [
                        $date->copy()->startOfMonth()->startOfDay(),
                        $date->copy()->endOfMonth()->endOfDay()
                    ]);
                })
                ->sum('money_details.amount');
            $inW = MoneyDetail::query()
                ->where('hostel_id', $hostel->id)
                ->where('is_water', true)
                ->whereHas('moneyInfo', function ($q) use ($date) {
                    $q->whereBetween('date_action', [
                        $date->copy()->startOfMonth()->startOfDay(),
                        $date->copy()->endOfMonth()->endOfDay()
                    ]);
                })
                ->sum('amount');

            $outE = 0;
            $outW = 0;

            if ($typeSpendElectric) {
                $outE = CollectSpend::query()
                    ->where('type_purpose', $typeSpendElectric->id)
                    ->where('type', CollectSpend::SPEND)
                    ->where('hostel_id', $hostel->id)
                    ->whereBetween('date_action', [
                        $date->copy()->startOfMonth()->startOfDay(),
                        $date->copy()->endOfMonth()->endOfDay()
                    ])
                    ->sum('amount');
            }

            if ($typeSpendWater) {

                $outW = CollectSpend::query()
                    ->where('type_purpose', $typeSpendWater->id)
                    ->where('type', CollectSpend::SPEND)
                    ->where('hostel_id', $hostel->id)
                    ->whereBetween('date_action', [
                        $date->copy()->startOfMonth()->startOfDay(),
                        $date->copy()->endOfMonth()->endOfDay()
                    ])
                    ->sum('amount');
            }


            $result[] = [
                'hostel_name' => $hostel->name,
                'in_e' => $inE,
                'in_w' => $inW,
                'out_e' => $outE,
                'out_w' => $outW
            ];
        }

        return response([
            'status' => 1,
            'data' => $result
        ]);
    }
}

