<?php

namespace App\Http\Controllers\Api\V1\DailyWorkPlan;

use App\Http\Controllers\Requests\DailyWorkPlan\DailyWorkPlanRequest;
use App\DailyWorkEfficiency;
use App\DailyWorkPlan;
use App\Http\Controllers\Controller;
use App\User;

class DailyWorkPlanController extends Controller
{
    public function store(DailyWorkPlanRequest $request)
    {
        $user = auth()->user();
        $create_task_ids = $request->create_task_id;
        $count = $request->count;
        $point = $request->point;
        $total_point = $request->total_point;
        $date = today();

        DailyWorkPlan::where('user_id', $user->id)
            ->where('date', $date)
            ->delete();

        foreach ($create_task_ids as $key => $create_task_id) {
            $dailyWorkPlan = new DailyWorkPlan();
            $dailyWorkPlan->user_id = $user->id;
            $dailyWorkPlan->create_task_id = $create_task_id;
            $dailyWorkPlan->count = $count[$key] ?? 0;
            $dailyWorkPlan->point = $point[$key] ?? 0;
            $dailyWorkPlan->date = $date;
            $dailyWorkPlan->save();
        }

        $users = User::find($user->id);
        $users->daily_work_plan_point = $total_point;
        $users->daily_work_plan_point_date = $date;
        $users->save();

        DailyWorkEfficiency::updateOrCreate(
            [
                'user_id' => $user->id,
                'date' => $date
            ],
            [
                'work_plan' => $total_point,
                'user_name' => $user->name,
                'team_leader_id' => $user->reporting_to,
            ],
        );

        return response()->json([
            'status' => true,
            'message' => "Successfully added daily work plan",
        ]);
    }


}
