<?php

namespace App\Http\Controllers\Web;

use App\Helpers\ImageHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\Web\CasesRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use App\CaseRequest;


class CaseController extends Controller
{
    private $view = 'web.cases.';

    public function index()
    {
        $title = __('caseRequests.case_request');
        return view($this->view.'case_request', get_defined_vars());
    }

    /**
     * Cases request
     * @param CasesRequest $request
     * @return JsonResponse
     */
        public function caseRequest(CasesRequest $request)
    {
        $data = $request->all();
        $files = [];
        if ($request->files){
            $allowedTypes = ['application/pdf','image/png', 'image/jpg', 'image/jpeg'];
            foreach ($request['files'] as $file) {
                if (!in_array($file->getMimeType(), $allowedTypes)){
                    $message = __('caseRequests.file_not_allowed');
                    $message = str_replace('@@', $file->getClientOriginalName(), $message);
                    return response()->json(['errors' => $message]);
                }

                $files[] = ImageHelper::upload($file, 'cases_files');
            }
        }
        $user = Auth::user();
        $data['user_id'] = $user->id;
        $data['name'] = $user->name;
        $data['email'] = $user->email;
        $data['phone'] = $user->phone;
        $data['files'] = $files;
        CaseRequest::create($data);

        return response()->json(['success' => true]);

    }


}
