<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\CreateLeadAPIRequest;
use App\Http\Requests\Api\UpdateLeadAPIRequest;
use App\Models\Lead;
use App\Models\LeadTeam;
use App\Repositories\Admin\LeadRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\DB;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Illuminate\Http\Response;

/**
 * Class LeadController
 * @package App\Http\Controllers\Api
 */
class LeadAPIController extends AppBaseController
{
    /** @var  LeadRepository */
    private $leadRepository;

    public function __construct(LeadRepository $leadRepo)
    {
        $this->leadRepository = $leadRepo;
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \Prettus\Repository\Exceptions\RepositoryException
     * @return Response
     *
     * @SWG\Get(
     *      path="/leads",
     *      summary="Get a listing of the Leads.",
     *      tags={"Lead"},
     *      description="Get all Leads",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="Authorization",
     *          description="User Auth Token{ Bearer ABC123 }",
     *          type="string",
     *          required=true,
     *          default="Bearer ABC123",
     *          in="header"
     *      ),
     *      @SWG\Parameter(
     *          name="orderBy",
     *          description="Pass the property name you want to sort your response. If not found, Returns All Records in DB without sorting.",
     *          type="string",
     *          required=false,
     *          in="query"
     *      ),
     *      @SWG\Parameter(
     *          name="sortedBy",
     *          description="Pass 'asc' or 'desc' to define the sorting method. If not found, 'asc' will be used by default",
     *          type="string",
     *          required=false,
     *          in="query"
     *      ),
     *      @SWG\Parameter(
     *          name="limit",
     *          description="Change the Default Record Count. If not found, Returns All Records in DB.",
     *          type="integer",
     *          required=false,
     *          in="query"
     *      ),
     *     @SWG\Parameter(
     *          name="offset",
     *          description="Change the Default Offset of the Query. If not found, 0 will be used.",
     *          type="integer",
     *          required=false,
     *          in="query"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  type="array",
     *                  @SWG\Items(ref="#/definitions/Lead")
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function index(Request $request)
    {
        $leads = $this->leadRepository
            ->pushCriteria(new RequestCriteria($request))
            ->pushCriteria(new LimitOffsetCriteria($request))
            //->pushCriteria(new leadCriteria($request))
            ->all();

        return $this->sendResponse($leads->toArray(), 'Leads retrieved successfully');
    }

    /**
     * @param CreateLeadAPIRequest $request
     * @return Response
     *
     * @SWG\Post(
     *      path="/leads",
     *      summary="Store a newly created Lead in storage",
     *      tags={"Lead"},
     *      description="Store Lead",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="Authorization",
     *          description="User Auth Token{ Bearer ABC123 }",
     *          type="string",
     *          required=true,
     *          default="Bearer ABC123",
     *          in="header"
     *      ),
     *      @SWG\Parameter(
     *          name="body",
     *          in="body",
     *          description="Lead that should be stored",
     *          required=false,
     *          @SWG\Schema(ref="#/definitions/Lead")
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/Lead"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function store(CreateLeadAPIRequest $request)
    {
        $leads = $this->leadRepository->saveRecord($request);

        return $this->sendResponse($leads->toArray(), 'Lead saved successfully');
    }

    /**
     * @param int $id
     * @return Response
     *
     * @SWG\Get(
     *      path="/leads/{id}",
     *      summary="Display the specified Lead",
     *      tags={"Lead"},
     *      description="Get Lead",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="Authorization",
     *          description="User Auth Token{ Bearer ABC123 }",
     *          type="string",
     *          required=true,
     *          default="Bearer ABC123",
     *          in="header"
     *      ),
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of Lead",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/Lead"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function show($id)
    {
        /** @var Lead $lead */
        $lead = $this->leadRepository->findWithoutFail($id);

        if (empty($lead)) {
            return $this->sendErrorWithData(['Lead not found']);
        }

        return $this->sendResponse($lead->toArray(), 'Lead retrieved successfully');
    }

    /**
     * @param int $id
     * @param UpdateLeadAPIRequest $request
     * @return Response
     *
     * @SWG\Put(
     *      path="/leads/{id}",
     *      summary="Update the specified Lead in storage",
     *      tags={"Lead"},
     *      description="Update Lead",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="Authorization",
     *          description="User Auth Token{ Bearer ABC123 }",
     *          type="string",
     *          required=true,
     *          default="Bearer ABC123",
     *          in="header"
     *      ),
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of Lead",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Parameter(
     *          name="body",
     *          in="body",
     *          description="Lead that should be updated",
     *          required=false,
     *          @SWG\Schema(ref="#/definitions/Lead")
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/Lead"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function update($id, UpdateLeadAPIRequest $request)
    {
        /** @var Lead $lead */
        $lead = $this->leadRepository->findWithoutFail($id);

        if (empty($lead)) {
            return $this->sendErrorWithData(['Lead not found']);
        }

        $lead = $this->leadRepository->updateRecord($request, $lead);

        return $this->sendResponse($lead->toArray(), 'Lead updated successfully');
    }

    /**
     * @param int $id
     * @return Response
     *
     * @SWG\Delete(
     *      path="/leads/{id}",
     *      summary="Remove the specified Lead from storage",
     *      tags={"Lead"},
     *      description="Delete Lead",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="Authorization",
     *          description="User Auth Token{ Bearer ABC123 }",
     *          type="string",
     *          required=true,
     *          default="Bearer ABC123",
     *          in="header"
     *      ),
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of Lead",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  type="string"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function destroy($id)
    {
        /** @var Lead $lead */
        $lead = $this->leadRepository->findWithoutFail($id);

        if (empty($lead)) {
            return $this->sendErrorWithData(['Lead not found']);
        }

        $this->leadRepository->deleteRecord($id);

        return $this->sendResponse($id, 'Lead deleted successfully');
    }

    public function setLeads()
    {

//        set_time_limit(300);
//        $leads = app(LeadRepository::class)->all();
//
//        foreach ($leads as $key => $lead) {
//            if ($lead->team_id == null) {
//                $input['team_id'] = 4;
//                $this->leadRepository->where('id', $lead->id)->update(['team_id' => 4]);
//            } else {
//                $logs          = new LeadTeam();
//                $logs->lead_id = $lead->id;
//                $logs->team_id = $lead->team_id;
//                $logs->save();
//            }
//
//        }


//        $re    = LeadTeam::pluck('lead_id')->all();
//        $leads = app(LeadRepository::class)->whereNotIn('id', $re)->get();
//        dd($leads);
    }


    public function moveSiteData(Request $request)
    {
        if (isset($request->website_id) && isset($request->team_id)) {
            $ids = Lead::where('website_id', $request->website_id)->pluck('id');
            DB::table('lead_team')->whereIn('lead_id', $ids)->update(['team_id' => $request->team_id]);

        } else {
            return "not found id";
        }
    }

}
