<?php

namespace App\Api\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\Api\Http\Requests\Lead\LeadListRequest;
use App\Api\Http\Requests\ReallocatedRequest;
use App\Http\Controllers\Controller;
use App\Location;
use App\Quarter;
use App\User;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;

class ReallocatedLeadController extends Controller
{
    public function index(LeadListRequest $request): LeadCollection
    {
        $lists = $request->list;
        $week = Carbon::today()->subDays(15);
        $month = Carbon::now()->subMonth();
        $yesterday = Carbon::yesterday();
        $seven = Carbon::today()->subDays(7);
        $currentDate = date('Y-m-d');
        $quarter = Quarter::whereRaw('? between date_from and date_to', $currentDate)
            ->first();

        if ($quarter) {
            $from_date = $quarter->date_from;
            $to_date = $quarter->date_to;
        }
        $userRoles = auth()
            ->user()
            ->userRoles();
        $all_reporting_users_id_array = [];
        $authUser = auth()->user();
        if (!$userRoles->contains('slug', 'ceo') && !$userRoles->contains('slug', 'super-admin') && !$userRoles->contains('slug', 'admin') && !$userRoles->contains('slug', 'head-sales')) { //Except superadmin and admin
            $all_reporting_users_id_array = $authUser->getAllReportingUsersIds();
            array_push($all_reporting_users_id_array, $authUser->id);
        } elseif ($userRoles->contains('slug', 'sales-head')) {
            $all_reporting_users_id_array = User::whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })->where('branch_id', auth()->user()->branch_id)
            ->where('status', 1)
            ->get()
            ->pluck('id')
            ->toArray();
        }

        $leads = QueryBuilder::for(Lead::class)
            ->with([
                'getLeadStage',
                'getUnit',
                'getAttendedBy',
                'getSource',
                'getProjectType',
                'getPreferredProject',
                'getPreferredProject.getProjectType',
                'getBudget',
                'getLeadCategory',
            ])

            ->when($lists == 1, function ($query) {
                $query->whereDate('lead_date', today());
            })
            ->when($lists == 2, function ($query) use ($week) {
                $query->whereDate('lead_date', '>=', $week);
            })
            ->when($lists == 3, function ($query) use ($month) {
                $query->whereDate('lead_date', '>=', $month);
            })
            ->when($lists == 4, function ($query) use ($request) {
                $from = $request->from_date;
                $to = $request->to_date;
                $query->whereBetween('lead_date', [$from, $to]);
            })
            ->when($lists == 5, function ($query) use ($yesterday) {
                $query->whereDate('lead_date', $yesterday);
            })
            ->when($lists == 6, function ($query) {
                $query->whereBetween('lead_date', ['2023-11-20', '2023-12-31']);
            })
            ->when($lists == 7, function ($query) use ($seven) {
                $query->whereDate('lead_date', '>=', $seven);
            })
            ->when($lists == 8, function ($query) use ($from_date, $to_date) {
                $query->whereBetween('lead_date', [$from_date, $to_date]);
            })
            ->where(function ($query) {
                $query->whereNotIn('lead_stage_id', [6, 7, 8])->orWhereNull('lead_stage_id');
            })

            ->when(!$userRoles->contains('slug', 'super-admin') && !$userRoles->contains('slug', 'admin') && !$userRoles->contains('slug', 'ceo') && !$userRoles->contains('slug', 'head-sales'), function ($q) use ($all_reporting_users_id_array) {
                $q->whereIn('re_attended_by', $all_reporting_users_id_array);
            })
            ->where('sale_status', 'no')
            ->where('reallocate_new', 1)
            ->orWhere('lead_bank_reallocate', 1)
            ->where('lead_bank_reattended', 0)
            ->when(function ($query) {
                $query->where('lead_bank_reallocate', 1);
            }, function ($query) use ($all_reporting_users_id_array) {
                $query->whereIn('lead_bank_reattended_by', $all_reporting_users_id_array);
            })
            ->defaultSort('-created_at')
            ->allowedFilters([
                AllowedFilter::callback('is_today', function (Builder $query, $value) {
                    $query->whereDate('created_at', today());
                }),
                AllowedFilter::exact('id'),
                AllowedFilter::exact('project_type', 'getProjectType.id'),
                AllowedFilter::exact('source', 'getSource.id'),
                AllowedFilter::exact('project', 'getPreferredProject.id'),
                AllowedFilter::scope('starts_between'),
            ])
            ->jsonPaginate(10)
            ->appends(request()->query());

        return (new LeadCollection($leads))->additional(['message' => 'Leads list!']);
    }

    public function store(ReallocatedRequest $request)
    {
        if ($request->location_id != 15 && $request->location_id != 16) {
            $locat = Location::find($request->location_id);
            $location = $locat->name ?? '';
        } else {
            $location = $request->location_name;
        }
        if ($request->preffered_location_id != 15 && $request->preffered_location_id != 16) {
            $locat = Location::find($request->preffered_location_id);
            $preffered_location = $locat->name ?? '';
        } else {
            $preffered_location = $request->preffered_location_name;
        }
        $lead = Lead::find($request->lead_id);
        if($lead->lead_bank_reallocate == 1){
            $lead->lead_category = $request->lead_category;
            $lead->budget = $request->budget;
            $lead->reallocate_new = 0;
            $lead->project_type = $request->project_type;
            $lead->preferred_project = $request->preferred_project;
            $lead->location_id = $request->location_id;
            $lead->location = $location;
            $lead->profession = $request->profession;
            $lead->investment_purpose = $request->investment_purpose;
            $lead->preferred_investment_location = $preffered_location;
            $lead->residential_status = $request->residential_status;
            $lead->job = $request->job;
            $lead->lead_bank_reattended = 1;
            $lead->lead_bank_reattended_date = now();
        }else{
            $lead->lead_category = $request->lead_category;
            $lead->budget = $request->budget;
            $lead->reallocate_new = 0;
            $lead->project_type = $request->project_type;
            $lead->preferred_project = $request->preferred_project;
            $lead->location_id = $request->location_id;
            $lead->location = $location;
            $lead->profession = $request->profession;
            $lead->investment_purpose = $request->investment_purpose;
            $lead->preferred_investment_location = $preffered_location;
            $lead->residential_status = $request->residential_status;
            $lead->job = $request->job;
        }
        
        if ($lead->save()) {
            return $this->success(
                'Lead has been added successfully..',
            );
        }

        return $this->error(
            'Failed to add Lead..',
        );
    }
}
