<?php

namespace App\Http\Controllers\Web;

use App\OtherRequest;
use App\OtherRequestTopic;
use App\Helpers\ImageHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\Web\OtherRequestsRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;


class OtherController extends Controller
{
    private $view = 'web.others.';

    public function index()
    {
        $title = __('otherRequests.others');
        $requestTopics = OtherRequestTopic::withDescription();

        return view($this->view.'index', get_defined_vars());
    }

    /**
     * Cases request
     * @param OtherRequestsRequest $request
     * @return JsonResponse
     */
    public function request(OtherRequestsRequest $request)
    {
        $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]);
                }

                $requestFile = ImageHelper::upload($file, 'other_requests_files');

                if ($requestFile['errors'] ?? null){
                    return response()->json(['errors' => $requestFile['errors']]);
                }

                $files[] = $requestFile;
            }
        }
        $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);

        return response()->json(['success' => true, 'request_no' => $request->id]);

    }


}
