<?php

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

use App\Lead;
use Carbon\Carbon;
use App\Api\Http\Resources\Leads\LeadCollection;
use Illuminate\Database\Eloquent\Builder;
use App\Http\Controllers\Requests\Lead\LeadListRequest;
use App\Http\Controllers\Controller;
use App\Quarter;
use App\User;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;
use Illuminate\Http\Request;

class LeadsController extends Controller
{
    public function index(LeadListRequest $request)
    {
        $user = auth()->user();
        $id = $user->id;
        $list = $request->list;
        $yesterday = Carbon::yesterday();
        $lastFifteenDays = Carbon::today()->subDays(15);
        $month = Carbon::now()->subMonth();
        $seven = Carbon::today()->subDays(7);
        $currentDate = date('Y-m-d');
        $leads = Lead::with('getProjectType', 'getPreferredProject', 'getSource')->where('created_by', $id)->
            when($list == 1, function ($query) use ($currentDate) {
                $query->where('lead_date', today());
            })
            ->when($list == 2, function ($query) use ($yesterday) {
                $query->where('lead_date', $yesterday);
            })
            ->when($list == 3, function ($query) use ($lastFifteenDays) {
                $query->where('lead_date', '>=', $lastFifteenDays);
            })
            ->when($list == 4, function ($query) use ($month) {
                $query->where('lead_date', '>=', $month);
            })->orderBy('id', 'desc')->get();


        return response()->json([
            'status' => true,
            'count' => $leads->count(),
            'lead_list' => $leads,
        ]);
    }

    public function leadFilter(Request $request)
    {
        $user = auth()->user();
        $from_date = $request->from_date;
        $to_date = $request->to_date;
        $project_type = $request->project_type;
        $source = $request->source;

        $leads = Lead::with(
            'getProjectType',
            'getPreferredProject',
            'getSource'
        )->where('created_by', $user->id)
            ->when($from_date, function ($query, $from_date) {
                $query->where('lead_date', '>=', $from_date);
            })
            ->when($to_date, function ($query, $to_date) {
                $query->where('lead_date', '<=', $to_date);
            })
            ->when($project_type, function ($query, $project_type) {
                $query->where('project_type', $project_type);
            })
            ->when($source, function ($query, $source) {
                $query->where('source', $source);
            })
            ->get();

        return response()->json([
            'status' => true,
            'count' => $leads->count(),
            'lead_list' => $leads,
        ]);
    }
}
