<?php

namespace App\Http\Controllers\API;

use App\OtherRequest;
use App\Helpers\ImageHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\API\OtherRequestsRequest;
use App\Http\Resources\OtherRequestResource;
use App\Http\Resources\OtherRequestTypesResource;
use App\OtherRequestTopic;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;


class OtherRequestController extends Controller
{
    /**
     * Send case request
     * @param OtherRequestsRequest $request
     * @return JsonResponse
     */
    public function otherRequest(OtherRequestsRequest $request) :JsonResponse
    {
        $data = $request->all();

        $files = [];
        if (count($request->files)){
            $allowedTypes = ['application/pdf','image/png', 'image/jpg', 'image/jpeg'];
            foreach ($request['files'] as $file) {
                if (!in_array($file->getMimeType(), $allowedTypes)){
                    $message = __('otherRequests.file_not_allowed');
                    $message = str_replace('@@', $file->getClientOriginalName(), $message);
                    return response()->json(['errors' => $message]);
                }

                $request_files = ImageHelper::upload($file, 'other_requests_files');
                if ($request_files['errors'] ?? null){
                    return response()->json(['message' => $request_files['errors'], 'data' => null], 400);
                }

                $files[] = $request_files;
            }
        }

        $user = Auth::user();
        $data['user_id'] = $user->id;
        $data['name'] = $user->name;
        $data['email'] = $user->email;
        $data['phone'] = $user->phone;
        $data['files'] = $files;

        $request = OtherRequest::create($data);
        $message = __('otherRequests.request_send_successfully') . ' ' .  __('otherRequests.request_no') . ": $request->id";
        $companyRequest = OtherRequestResource::make($request);
        return response()->json(['message' => $message , 'data' => $companyRequest], 200);

    }


    /**
     * Other requests types
     * @return JsonResponse
     */
    public function otherRequestTypes()
    {
        $type = OtherRequestTopic::withDescription();
        $data  = OtherRequestTypesResource::collection($type);
        return response()->json(['message' => '', 'data' => $data], 200);
    }


    public function userOtherRequests()
    {
        $user = Auth::user();
        $otherRequests = OtherRequest::orderByDesc('id')->where('user_id', $user->id)->cursor();
        $data = OtherRequestResource::collection($otherRequests);
        return response()->json(['message' => '', 'data' => $data], 200);

    }
}
