<?php

namespace Modules\ContactList\Controllers\Admin;

/** Ajax Request */

use App\Services\Response\ResponseService;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Category\Services\CategoryService;
use Modules\ContactList\Enums\ContactDecisionEnum;
use Modules\ContactList\Exports\ContactListExport;
use Modules\ContactList\Requests\Admin\ContactListRequest;
use Modules\ContactList\Services\ContactListService;
use Modules\MainService\Enums\ViewEnum;
use Modules\Company\Services\CompanyService;
use Modules\ContactList\Enums\ContactStatusEnum;
use Modules\Country\Services\CountryService;
use Modules\Sector\Exports\SectorExport;
use Modules\User\Services\UserService;
use Modules\User\Enums\UserRoleEnum;
use Modules\ContactList\Enums\GenderEnum;

class ContactListController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/admin/contact_lists';
    /** View folder */
    private $viewDirectory= 'admin.contact_lists.';
    private $phoneDirectory= 'admin.contact_lists.phones.';
    private $sectorDirectory= 'admin.contact_lists.sector.';
    //

    public function __construct(
        private ContactListService $contactListService,
        private CategoryService $categoryService,
        private CompanyService $companyService,
        private CountryService $countryService,
        private UserService $userService
    ){}

    /**
     * Display a listing of the contact_lists.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $typeView = $request->typeView ?? ViewEnum::LIST->value;
        $data =
        [
            'head'=>__('contact_lists.head'),
            'view' => ViewEnum::INDEX->value,
            'route'=>$this->viewDirectory,
            'typeView' => $typeView,
            'kanbanView'=>ViewEnum::KANBAN->value,
            'listView'=>ViewEnum::LIST->value,
            'statuses' => ContactStatusEnum::values(),
            'request' => $request,
        ];
        return $this->contactListService->render($data);
    }

    public function fetchBudget(Request $request) :View
    {
        $category = $this->categoryService->getCategoryByBudget($request->budget);
        $data =
            [
                'view' => ViewEnum::INDEX->value,
                'category' => $category,
                'route'=>$this->viewDirectory.'budget.',
            ];
        return $this->contactListService->render($data);
    }

    public function fetchCompanySector(Request $request)
    {
        $company = $this->companyService->getItem($request->company_id);
        $request->merge([
            'route' => $this->sectorDirectory,
            'view' => ViewEnum::SHOW->value,
            'company' => $company
        ]);
        return $this->contactListService->renderView($request->all());
    }

    /**
     * return data of the contact_lists.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request)
    {
        if(isset($request->orderBy))
        {
            $orderBy = json_decode($request->orderBy, true);
            $request->merge(['orderBy'=>['key'=>$orderBy['key'], 'value'=>$orderBy['value']]]);
        }

        $typeView = $request->typeView ?? ViewEnum::LIST->value;
        if($request->export)
        {
            $contact_lists = $this->contactListService->get($request->all());
            return Excel::download(new ContactListExport($contact_lists,Auth::user()), 'contact_lists.xlsx');
        }
        $request->merge([
            'route' => $this->viewDirectory,
            'view' => $typeView,
            'request'=>$request,
            'groupCompany' => $typeView == ViewEnum::KANBAN->value ? true : false,
            'paginate' => $typeView != ViewEnum::KANBAN->value ? true : false,
            'statuses' => ContactStatusEnum::values(),
            'decision_statuses'=>ContactDecisionEnum::values(),
            'employees'=>$this->userService->get(['roles'=>UserRoleEnum::employees()]),
            'countries' => $this->countryService->get(),
            'companies' => $this->companyService->get(),
        ]);
        return $this->contactListService->renderView($request->all());
    }

    public function addPhone(Request $request) :View
    {
        $data = [
            'key' => $request->key,
            'request' => $request,
            'view' => ViewEnum::INDEX->value,
            'countries' => $this->countryService->get(),
            'route' => $this->phoneDirectory,
        ];
        return $this->contactListService->render($data);
    }
    /**
     * Show the form for creating a new company.
     *
     * @return View
     */
    public function create() :View
    {
        $data =
        [
            'head'=>__('contact_lists.new'),
            'action' => route('contact_lists.store'),
            'view' => ViewEnum::FORM->value,
            'route'=> $this->viewDirectory,
            'companies' => $this->companyService->get(),
            'countries' => $this->countryService->get(),
            'statuses' => ContactStatusEnum::values(),
            'genders'=>GenderEnum::values(),
            'specialCase'=>ContactStatusEnum::BRIEF_RECIEVED->value,
            'phones' => [],
            'decision_maker_statuses'=>ContactDecisionEnum::values(),
            'employees'=>$this->userService->get(['roles'=>UserRoleEnum::employees()])
        ];
        return $this->contactListService->render($data);
    }

    /**
     * Store a newly created company in storage.
     * @param ContactListRequest $request
     * @return JsonResponse
     */
    public function store(ContactListRequest $request) :JsonResponse
    {
        $contactList = $this->contactListService->create($request->validated());

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> [
                'status' => $contactList->status == ContactStatusEnum::BRIEF_RECIEVED->value ? 'question' : 'url',
                'url' => url()->previous()
            ],
        ];
        return ResponseService::response($response);
    }


    public function lock($id)
    {
        $contactList = $this->contactListService->getItem($id);
        if (!$contactList)
        {
            abort(404);
        }
        $this->contactListService->updateLock($id);
        session()->flash('message', __('dashboard.saveDone'));
        return redirect()->back();
    }

    /**
     * Show the form for editing the specified company.
     *
     * @param  int $id
     * @return View
     */
    public function edit(int $id) :View
    {
        $contactList = $this->contactListService->getItem($id);
        if (!$contactList)
        {
            abort(404);
        }
        $data =
        [
            'head'=>__('contact_lists.edit'),
            'action' => route('contact_lists.update',$contactList->id),
            'view' => ViewEnum::FORM->value,
            'route'=> $this->viewDirectory,
            'companies' => $this->companyService->get(),
            'countries' => $this->countryService->get(),
            'statuses' => ContactStatusEnum::values(),
            'genders'=>GenderEnum::values(),
            'specialCase'=>ContactStatusEnum::BRIEF_RECIEVED->value,
            'decision_maker_statuses'=>ContactDecisionEnum::values(),
            'phones' => $this->contactListService->phones($contactList->id),
            'employees'=>$this->userService->get(['role'=>UserRoleEnum::employees()]),
            'contactList' => $contactList
        ];
        return $this->contactListService->render($data);
    }

    public function show(int $id) :View
    {
        $contactList = $this->contactListService->getItem($id);
        if (!$contactList)
        {
            abort(404);
        }
        $data =
        [
            'head'=>__('contact_lists.show'),
            'view' => ViewEnum::SHOW->value,
            'route'=> $this->viewDirectory,
            'specialCase'=>ContactStatusEnum::BRIEF_RECIEVED->value,
            'phones' => $this->contactListService->phones($contactList->id),
            'contactList' => $contactList
        ];
        return $this->contactListService->render($data);
    }

    /**
     * Update the specified company in storage.
     * @param ContactListRequest $request
     * @param int $id
     * @return JsonResponse
     */
    public function update(ContactListRequest $request, int $id) :JsonResponse
    {
        $contactList = $this->contactListService->checkItem($id);
        if (!$contactList)
        {
            abort(404);
        }
        $this->contactListService->update($request->validated(), $id);
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=>  [
                'status' => ($request->status == ContactStatusEnum::BRIEF_RECIEVED->value && auth()->user()->canAccess('deals','index')) ? 'question' : 'url',
                'url' => url()->previous()
            ],
        ];
        return ResponseService::response($response);
    }

    /**
     * Remove the specified company from storage.
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(int $id) :JsonResponse
    {
        $this->contactListService->destroy($id);
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('contact_lists.index'),
        ];
        return ResponseService::response($response);
    }

    /**
     * Remove several contact_lists by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $this->contactListService->destroyAll([
            'ids' => $request->ids,
            'status' => 1
        ]);
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('contact_lists.index'),
        ];
        return ResponseService::response($response);
    }

    /**
     * Restore the specified company from storage.
     *
     * @param int $id
     * @return JsonResponse
     */
    public function restore(int $id) :JsonResponse
    {
        $this->contactListService->destroy($id);
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('contact_lists.index'),
        ];
        return ResponseService::response($response);
    }

    /**
     * Restore several contact_lists by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $this->contactListService->destroyAll([
            'ids' => $request->ids,
            'status' => 0
        ]);
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('contact_lists.index'),
        ];
        return ResponseService::response($response);
    }
}
