<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AdditionalStatus;
use App\Models\Property;
use App\Models\PropertyStatus;
use App\Models\PropertyUser;
use App\Models\Status;
use App\Models\User;
use Illuminate\Http\Request;

class PropertyController extends Controller
{
    public function getUserObjects(Request $request)
    {

        $user = User::find($request->userId);
        foreach ($user->properties as $key=>$property) {
            $user->properties[$key]->status = $user->properties[$key]->propertyStatusUser($user->id);
            $user->properties[$key]->statusDetails = $user->properties[$key]->propertyStatusUser($user->id)->status;

        }
        return response()->json($user->properties);
    }

    public function getAllObjects()
    {
        $properties = Property::all();
        return response()->json($properties);
    }

    public function getAllStatuses()
    {
        $statuses = Status::all();
        return response()->json($statuses);
    }

    public function getAllAdditionalStatuses()
    {
        $statuses = AdditionalStatus::all();
        return response()->json($statuses);
    }

    public function addNewObject(Request $request)
    {
        $user = User::find($request->user_id);
        $property = Property::find($request->object_id);
        $property_status = $property->propertyStatusUser($user->id);
        $status_id = $request->status_id;


        if($property_status) {
            if($property_status->approved !== null && !$property_status->approved) {
                return response()->json(['message' => 'Вы уже подавали заявку на данный объект, пожалуйста, дождитесь ее обработки.'], 500);
            }
            return response()->json(['message' => 'Данный объект уже был добавлен для вас!'], 500);
        }

        PropertyStatus::create([
            'status_id'     => $status_id,
            'property_id'   => $property->id,
            'user_id'       => $user->id,
            'approved'      => false,
            'status_notes'  => '',
        ]);

        PropertyUser::create([
            'user_id'     => $user->id,
            'property_id' => $property->id,
        ]);

        return true;
    }

    public function getObjectById(Request $request, $id)
    {
        $property = Property::find($id);
        $property->propertyCategory;
        $property->property_main_status_user = $property->propertyStatusUser($request->user_id);
        $property->status = $property->property_main_status_user->status;
        $temp = [];

        foreach ($property->propertyAdditionalStatusesUser($request->user_id) as $key => $status_user) {
            array_push($temp, $status_user->additionalStatus);
        }
        $property->additional_statuses =  $temp;
        return response()->json($property);
    }
}
