<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Lib\ApiAuthHelper;
use App\Models\Application;
use App\Models\ApplicationCategory;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Validator;
use mysql_xdevapi\Exception;

class ServiceApplicationsController extends Controller
{
    use ApiAuthHelper;

    public function getCategories()
    {
        $categories = ApplicationCategory::all();
        return response()->json($categories);

    }

    public function store(Request $request)
    {

       // return response()->json($request->all(), 500);

        $validate = Validator::make($request->all(),[
            'services' => 'required',
            'objectId' => 'required'
        ], [
            'services.required' => 'Вы не выбрали желаемую услугу...',
            'objectId.required' => 'Указание и наличие активного объекта является обязательным.'
        ]);


        if ($validate->fails()) {

            return $this->apiResponse(false, 'Валидация данных... : ' . $validate->errors()->all()[0], $validate->errors()->all()[0], null, null, 500);
        }

        try {
            foreach ($request->services as $service) {

                Application::create([

                    'user_id'  => $request->id,
                    'application_category_id' => $service['id'],
                    'property_id' => $request->objectId,
                    'message'   => $request->message,
                    'status'    => 'Новая',
                    'due_date'  => $request->date . ' ' . $request->time,
                    'delivered' => false,
                    'visited'   => false,
                    ]);
            }

            return $this->apiResponse(true, 'Заявка успешно отправлена. Спасибо за обращение!', null, null, null, 200 );

        } catch (Exception $e) {
            return $this->apiResponse(false, 'Неизвестная ошибка' , $e->getLine(), null, null, 500);
        }

    }

    public function getUserApplications(Request $request)
    {
        $user = User::find($request->id);
        $applications = [];

        foreach ($user->applications()->orderBy('updated_at', 'desc')->paginate(25) as $application) {
            $application->applicationCategory;
            array_push($applications, $application);
        }

        return response()->json($applications);
    }

    public function cancelApplication(Request $request)
    {
        $application = Application::find($request->id);

        $application->status = 'Отменена';
        $application->save();
    }

    public function showApplication($id)
    {
        $application = Application::find($id);
        $application->applicationCategory;
        $application->property;
        return response()->json($application);
    }

    public function editApplication(Request $request, $id)
    {
        $application = Application::find($id);
        $application->due_date = $request->date . ' ' . $request->time;
        $application->message  = $request->message;
        $application->status   = 'Изменена';
        $application->save();
    }

}
