<?php

namespace App\Http\Controllers\Web;

use App\Http\Requests\Web\CompleteApplyRequest;
use App\Http\Requests\Web\FirstApplyRequest;
use App\Models\Category;
use App\Models\Choise;
use App\Models\Demand;
use App\Models\Product;
use App\Services\File\FileService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\View\View;
use App\Http\Controllers\Controller;

class CourseController extends Controller
{
    private $view = 'web.pages.courses.';

    public function index(): View
    {
        $title = __('web.courses');
        $categories = Category::withDescription()->with(['courses'=>function($query){
            $query->with(['details'])->where('publish','true');
        }])->get();

        return view($this->view.'index', get_defined_vars());
    }
    public function show($id)
    {
        $course = Product::withDescription($id)->with(['city','category'])->firstOrFail();
        $title = $course->name;
        return view($this->view.'show', get_defined_vars());
    }
    public function applyCourse($id)
    {
        $course = Product::withDescription($id)->firstOrFail();
        $title = __('web.apply_course').' - '.$course->name;
        $action = route('applying.course',$id);
        $processes = Choise::withDescription()->where('choises.status','process')->cursor();
        return view($this->view.'apply_course', get_defined_vars());
    }
    public function applyingCourse(FirstApplyRequest $request ,$id)
    {
        $course = Product::withDescription($id)->firstOrFail();
        Session::put('content', $request->all());
        return response()->json(['message'=> __('web.success'),'data'=>route('complete_course',$id)]);
    }
    public function completeCourse($id)
    {
        $course = Product::withDescription($id)->firstOrFail();
        $title = __('web.complete_course').' - '.$course->name;
        $content = Session::get('content');
        if(!isset($content))
        {
            abort(404);
        }
        $action = route('completing_course',$id);
        $courses = Product::withDescription()->cursor();
        return view($this->view.'complete_course', get_defined_vars());
    }
    public function completingCourse(CompleteApplyRequest $request ,$id)
    {
        $first = Session::get('content');
        $second = $request->all();
        $content= array_merge($second, $first);
        $content['cv'] = FileService::uploadImage($content['cv']);
        $content['user_id'] = Auth::user()->id;
        $demand = Demand::create($content);
        $demand->processes()->attach($content['process_id']);
        return response()->json(['message'=> __('web.success'),'data'=>route('courses.show',$id)]);
    }
}
