<?php

namespace App\Http\Controllers\API;

use App\CompanyRequest;
use App\CompanyRequestTopic;
use App\Helpers\ImageHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\API\CompanyRequestsRequest;
use App\Http\Resources\CompanyRequestResource;
use App\Http\Resources\CompanyRequestTypesResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;


class CompanyRequestController extends Controller
{
    /**
     * Send case request
     * @param CompanyRequestsRequest $request
     * @return JsonResponse
     */
    public function companyRequest(CompanyRequestsRequest $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 = __('companyRequests.file_not_allowed');
                    $message = str_replace('@@', $file->getClientOriginalName(), $message);
                    return response()->json(['errors' => $message]);
                }

                $request_files = ImageHelper::upload($file, 'company_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 = CompanyRequest::create($data);
        $message = __('companyRequests.request_send_successfully') . ' ' .  __('companyRequests.request_no') . ": $request->id";
        $companyRequest = CompanyRequestResource::make($request);
        return response()->json(['message' => $message, 'data' => $companyRequest], 200);

    }


    /**
     * Company requests types
     * @return JsonResponse
     */
    public function companyRequestTypes()
    {
        $type = CompanyRequestTopic::withDescription();
        $data  = CompanyRequestTypesResource::collection($type);
        return response()->json(['message' => '', 'data' => $data], 200);
    }


    public function userCompanyRequests()
    {
        $user = Auth::user();
        $companyRequests = CompanyRequest::orderByDesc('id')->where('user_id', $user->id)->cursor();
        $data = CompanyRequestResource::collection($companyRequests);
        return response()->json(['message' => '', 'data' => $data], 200);

    }
}
