<?php


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

use App\Api\Http\Resources\Leads\LeadCollection;
use App\Http\Controllers\Controller;
use App\Lead;
use App\Location;
use App\User;
use Illuminate\Support\Facades\DB;
use Spatie\QueryBuilder\QueryBuilder;


class CustomerController extends Controller
{
    public function index()
    {
       
        $userPermissions = auth()
            ->user()
            ->userPermissions();

        $userRoles = auth()
            ->user()
            ->userRoles();

        if (!$userRoles->contains('slug', 'ceo') && !$userRoles->contains('slug', 'super-admin') && !$userRoles->contains('slug', 'admin')) { //Except superadmin and admin
            $all_reporting_users_id_array = \Auth::user()->getAllReportingUsersIds();

            array_push($all_reporting_users_id_array, \Auth::user()->id);
        } elseif ($userRoles->contains('slug', 'team-leader')) {
            $all_reporting_users_id_array = \Auth::user()->getAllReportingUsersIds();
            array_push($all_reporting_users_id_array, \Auth::user()->id);
        } else {
            $users = User::where('status', 1)->get();
            $all_reporting_users_id_array =  $users->pluck('id');
        }
        
        $customers = QueryBuilder::for(Lead::class)
            ->with([
                'getLeadCategory',
                'getLeadStage',
                'getUnit',
                'getSource',
                'getProjectType',
                'getPreferredProject',
                'getBudget',
                'getLeadCategory',
                'getSaleActivity'
            ])
            
            ->whereHas('getSaleActivity', function($q) use ($all_reporting_users_id_array){
                $q->whereIn('sale_status',['yes', 'old'])
                ->whereNotIn('booking_status', ['hold', 'cancelled'])
                ->whereIn('sales_owner', $all_reporting_users_id_array)
                ->orderBy('sales_date', 'DESC');
            })
            ->jsonPaginate()
            ->appends(request()->query());

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