<?php

namespace App\Http\Controllers\Api\v1;

use App\Models\Extra;
use App\Models\Hostel;
use App\Models\Notification;
use App\Models\RenterRoom;
use App\Models\Room;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ExtraController extends BaseController
{
    //
    public function getItems(Request $request)
    {

        $hostelId = $request->input('hostel_id');
        $retVal = [];

        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');

        $times = Extra::select(\DB::raw('MONTH(date_action) as month, YEAR(date_action) as year'))
            ->groupBy(\DB::raw('month, year'))
            ->orderBy('month', 'desc')->orderBy('year', 'desc');

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

        if (empty($hostelId)) {
            $hostels = Hostel::where('owner_id', $userId)->pluck('id')->toArray();
            $times = $times->whereIn('hostel_id', $hostels);
        } else {
            $times = $times->where('hostel_id', $hostelId);
            if (!empty($roomId)) {
                $times = $times->where('room_id', $roomId);
            }
        }

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

        $times = $times->orderBy('month', 'desc')->orderBy('year', 'desc')->get();

        foreach ($times as $time) {
            $month = $time->month;
            $year = $time->year;

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

            $items = Extra::orderBy('id', 'desc');

            if (empty($hostelId)) {
                $hostels = Hostel::where('owner_id', $userId)->pluck('id')->toArray();
                $items = $items->whereIn('hostel_id', $hostels);
            } else {
                $items = $items->where('hostel_id', $hostelId);
                if (!empty($roomId)) {
                    $items = $items->where('room_id', $roomId);
                }
            }

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

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

            $items = $items->orderBy('id', 'desc')->get();

            foreach ($items as $item) {
                $item->hostel_name = '';
                $item->room_name = '';

                if ($item->hostel_id) {
                    $hostel = Hostel::find($item->hostel_id);

                    if ($hostel) {
                        $item->hostel_name = $hostel->name;
                    }
                }

                if ($item->room_id) {
                    $room = Room::find($item->room_id);

                    if ($room) {
                        $item->room_name = $room->name;
                    }
                }
            }
            $itemVal = [
                'time' => 'Tháng ' . $month . '/' . $year,
                'histories' => $items
            ];

            $retVal[] = $itemVal;
        }


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

    }

    public function create(Request $request)
    {
        $data = $request->all();
        $date = Carbon::now()->format('d/m/Y');
        try {

            $room = $data['room_id'];
            $infoRoom = Room::find($room);

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

            //   $data['user_id'] = auth('backend')->user()->id;
            $dateAction = Carbon::createFromFormat('d/m/Y', '01/'.$data['date_action'])->toDateString();

            $data['date_action'] = $dateAction;

            Extra::create($data);

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

            if($data['amount'] == $data['pay'])
            {
                $content = 'Phát sinh tiền '.$data['name'].' ngày '.$date.' với số tiền '.number_format($data['amount'], 0, '.', '.').' đ. Đã thanh toán '.number_format($data['pay'], 0, '.', '.').' đ';
            } else {
                $content = 'Phát sinh tiền '.$data['name'].' ngày '.$date.' với số tiền '.number_format($data['amount'], 0, '.', '.').' đ. Đã thanh toán '.number_format($data['pay'], 0, '.', '.').' đ, còn lại '.number_format(($data['amount'] - $data['pay']), 0, '.', '.').' đ sẽ được thu vào tiền nhà cuối tháng';
            }


            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'   => $content
                ] );

            }

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


        } catch (\Exception $ex) {
            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra'
            ]);
        }

    }
}
