<?php

namespace App\Http\Controllers\API;

use App\Helpers\ImageHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\API\TrainingsRequest;
use App\Http\Resources\PurposeTrainingResource;
use App\Http\Resources\TrainingRequestResource;
use App\PurposeTraining;
use App\TrainingRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;


class TrainingController extends Controller
{

    /**
     * Send training request
     * @param TrainingsRequest $request
     * @return JsonResponse
     */
    public function trainingRequest(TrainingsRequest $request) :JsonResponse
    {
        $data = $request->all();
        $cv = [];
        $certifications = [];


        if ($request->files){
            $allowedTypes = ['application/pdf','image/png', 'image/jpg', 'image/jpeg'];

            foreach ($request['cv'] as $file) {
                if (!in_array($file->getMimeType(), $allowedTypes)){
                    $message = __('trainingRequests.file_not_allowed');
                    $message = str_replace('@@', $file->getClientOriginalName(), $message);
                    return response()->json(['message' => $message, 'data' => null], 400);
                }

                $cv[] = ImageHelper::upload($file, 'trainings_files');

            }

            foreach ($request['certifications'] as $file) {
                if (!in_array($file->getMimeType(), $allowedTypes)){
                    $message = __('trainingRequests.file_not_allowed');
                    $message = str_replace('@@', $file->getClientOriginalName(), $message);
                    return response()->json(['message' => $message, 'data' => null], 400);
                }

                $certifications[] = ImageHelper::upload($file, 'trainings_files');
            }
        }


        $user = Auth::user();
        $data['user_id'] = $user->id;
        $data['name'] = $request->name ?? $user->name;
        $data['email'] = $request->email ?? $user->email;
        $data['phone'] = $request->phone ?? $user->phone;
        $data['cv'] = $cv;
        $data['certifications'] = $certifications;

//        $data['purpose_training_id'] = 1;
//        $data['university'] = 'test';
//        $data['phone'] = '530345592';
//        $data['birth_date'] = '05-02-1980';
//        $data['graduation_date'] = '05-02-1980';

        $trainingRequest = TrainingRequest::create($data);
        $trainingRequest = TrainingRequestResource::make($trainingRequest);
        return response()->json(['message' => '', 'data' => $trainingRequest], 200);

    }

    /**
     * Get training request requires
     * like training purpose
     * @return JsonResponse
     */
    public function requires() :JsonResponse
    {
        $trainingPurposes = PurposeTraining::withDescription();
        $data = PurposeTrainingResource::make($trainingPurposes);
        return response()->json(['message' => '', 'data' => $data], 200);
    }


}
