<?php

namespace App\Http\Controllers;

use App\Models\UserTask;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class UserTaskController extends Controller
{
    public function save(Request $request){
        $date= Carbon::today();
        $userId= Auth::id();
        $check= UserTask::where('date',$date)->where('user_id',$userId)->first();
        if($check){
            try {
                $check->details = $request->details;
                $check->user_id = $userId;
                $check->comment = $request->comment;
                $check->next_task = $request->next_task;
                $check->created_by = $userId;
                $check->updated_by = $userId;
                $check->client_id = Auth::user()->client_id;
                $check->date = $date;
                $check->save();
                return redirect()->back()->with('success','Task submitted successfully!');
            }
            catch (\Exception $e){
                return redirect()->back()->with('error','Something wrong!');

            }

        } else{
            $check= new UserTask;
            $check->details = $request->details;
            $check->user_id = $userId;
            $check->client_id = Auth::user()->client_id;
            $check->comment = $request->comment;
            $check->next_task = $request->next_task;
            $check->date = $date;
            $check->created_by = $userId;
            $check->updated_by = $userId;
            $check->save();
            return redirect()->back()->with('success','Task submitted successfully!');
        }
    }
    public function update( Request $request){
        $userId= Auth::id();
        $date= $request->date;
        $check= UserTask::where('date',$date)->where('user_id',$userId)->first();
        if($check){
            try {
                $check->details = $request->details;
                $check->user_id = $userId;
                $check->comment = $request->comment;
                $check->next_task = $request->next_task;
                $check->updated_by = $userId;
                $check->client_id = Auth::user()->client_id;
                $check->save();
                return redirect()->back()->with('success','Task submitted successfully!');
            }
            catch (\Exception $e){
                return redirect()->back()->with('error','Something wrong!');

            }

        } else{
            $check= new UserTask();
            $check->details = $request->details;
            $check->user_id = $userId;
            $check->client_id = Auth::user()->client_id;
            $check->comment = $request->comment;
            $check->next_task = $request->next_task;
            $check->date = $date;
            $check->created_by = $userId;
            $check->updated_by = $userId;
            $check->save();
            return redirect()->back()->with('success','Task submitted successfully!');
        }
    }
}
