<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Http\Controllers\Controller;
use Modules\Admin\app\Http\Controllers\AbstractController;
use Modules\Admin\app\Models\ProjectReview;
use Carbon\Carbon;
use Illuminate\Http\Request;
use DateTime;

class ProjectReviewController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function getListReviews(Request $request)
    {
        $request->validate([
            'userID' => 'required|exists:users,id',
            'fromDate' => 'nullable|date',
            'toDate' => 'nullable|date',
        ]);
        $userID = $request->input('userID');
        $startDate = $request->input('fromDate');
        $endDate = $request->input('toDate');
        $projectsData = ProjectReview::where('user_id', $userID);

        if ($startDate && $endDate) {
            $projectsData->whereBetween('updated_at', [$startDate, $endDate . ' 23:59:59']);
        } elseif ($startDate) {
            $projectsData->where('updated_at', '>=', $startDate);
        } elseif ($endDate) {
            $projectsData->where('updated_at', '<=', $endDate . ' 23:59:59');
        }
        return AbstractController::ResultSuccess($projectsData->get());
    }

    /**
     * Store a newly created resource in storage.
     */
    public function create(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'role' => 'required|string',
            'note' => 'required|string',
            'user_id' => 'required|exists:users,id',
        ]);

        $review = ProjectReview::create($request->all());
        return response()->json($review, 201);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request)
    {
        $request->validate([
            'name' => 'sometimes|required|string',
            'role' => 'sometimes|required|string',
            'note' => 'sometimes|required|string',
            'user_id' => 'sometimes|required|exists:users,id',
        ]);
        $id = $request->get('id');
        $projectReview = ProjectReview::find($id);
        $payload = $request->all();
        // if ($request->has('created_at')) {
        //     $created_at = Carbon::create($request->get('created_at'))->setTimezone(env('TIME_ZONE'));
        //     $payload['created_at'] = $created_at;
        // }
        if ($projectReview) {
            $projectReview->update($payload);
        }
        return response()->json([
            'data' => $projectReview,
            'status' => true
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request)
    {
        $id = $request->get('id');
        ProjectReview::destroy($id);
        return response()->json(['message' => 'Deleted successfully', 'status' => true]);
    }
}
