<?php

namespace App\Api\Http\Controllers\Api\V2\RequestLeave;

use App\Api\Http\Requests\RequestLeave\RequestLeaveRequest;
use App\Http\Controllers\Controller;
use App\RequestLeave;
use App\User;
use Carbon\Carbon;
use DB;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;

class RequestLeaveController extends Controller
{
    public function index(Request $request)
    {
        $userId = $request->user_id;
        $fromDate = $request->from_date ? date('Y-m-d', strtotime($request->from_date)) : null;
        $toDate = $request->to_date ? date('Y-m-d', strtotime($request->to_date)) : null;

        $reportingUserIds = auth()->user()->getReportingUsers();
        $reportingUserIds[] = 1;
        $leaveRequests = RequestLeave::with(['getUser', 'chargeAssignedUser'])
            ->whereIn('user_id', $reportingUserIds)
            ->when($userId, function ($q, $userId) {
                return $q->where('user_id', $userId);
            })
            ->when($fromDate, function ($q, $fromDate) {
                return $q->whereDate('from_date', '>=', $fromDate);
            })
            ->when($toDate, function ($q, $toDate) {
                return $q->whereDate('to_date', '<=', $toDate);
            })->get();

        return response()->json([
            'status' => true,
            'data' => $leaveRequests,
        ]);
    }

    public function store(RequestLeaveRequest $request)
    {
        DB::beginTransaction();
        try {
            $fromDate = Carbon::parse($request->from_date);
            $toDate = Carbon::parse($request->to_date);
            $requestLeave = new RequestLeave();
            $requestLeave->user_id = $request->user_id;
            $requestLeave->from_date = $fromDate;
            $requestLeave->to_date = $toDate;
            $diff_in_days = $fromDate->diffInDays($toDate);
            $requestLeave->total_days = $diff_in_days + 1;
            $requestLeave->reason = $request->reason;
            $requestLeave->charge_assigned_to = $request->charge_assigned_to;
            $requestLeave->status = "Pending";
            $requestLeave->save();

            DB::commit();
            return $this->success('Leave request has been added successfully.');
        } catch (\Throwable $th) {
            info($th);
            DB::rollBack();
            return $this->error('Failed to add leave request!');
        }
    }
}
