<?php

namespace Modules\Deal\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\ContactList\Services\ContactListService;
use Modules\Country\Exports\CountryExport;
use Modules\Deal\Exports\DealExport;
use Modules\Deal\Requests\Admin\DealRequest;
use Modules\Deal\Services\DealService;
use Modules\MainService\Enums\ViewEnum;
use Modules\Company\Services\CompanyService;
use Modules\Country\Services\CountryService;
use Modules\Deal\Enums\DealPaymentStatusEnum;
use Modules\Deal\Enums\DealStatusEnum;
use Modules\Product\Services\ProductService;
use Modules\Sector\Services\SectorService;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Services\UserService;

class DealController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/deals';
    /** View folder */
    private $viewDirectory = 'admin.deals.';

    private $viewDirectoryMain = 'admin.deals.main.';
    private $viewDirectoryCompany = 'admin.deals.companies.';
    private $viewDirectorySector = 'admin.deals.sectors.';
    private $viewDirectoryStatus = 'admin.deals.statuses.';
    private $viewDirectoryPayment = 'admin.deals.payments.';
    private $viewDirectoryContactList = 'admin.deals.contact_lists.';
    //

    public function __construct(
        private DealService $dealService,
        private CompanyService $companyService,
        private UserService $userService,
        private ProductService $productService,
        private ContactListService $contactListService,
        private SectorService $sectorService,
    ){}

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

    /**
     * return data of the deals.
     *
     * @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']]]);
        }
        if($request->export)
        {
            $deals = $this->dealService->get($request->all());
            return Excel::download(new DealExport($deals,Auth::user()), 'deals.xlsx');
        }
        $typeView = $request->typeView ?? ViewEnum::LIST->value;
        $request->merge([
            'route' => $this->viewDirectory,
            'view' => $typeView,
            'request'=>$request,
            'months'=>[1,2,3,4,5,6,7,8,9,10,11,12],
            'deal_id' => $typeView == ViewEnum::KANBAN->value ? 'main' : $request->deal_id,
            'statuses'=>DealStatusEnum::values(),
            'kanban' => $typeView == ViewEnum::KANBAN->value ? true : false,
            'paginate' => $typeView != ViewEnum::KANBAN->value ? true : false,
            'monthDeals'=> $this->dealService->get($request->all())->groupBy('month')
        ]);

        return $this->dealService->renderView($request->all());
    }

    public function addItem(Request $request)
    {
        $request->merge([
            'route' => $this->viewDirectoryPayment,
            'view' => ViewEnum::INDEX->value,
            'key' => $request->key
        ]);
        return $this->contactListService->renderView($request->all());
    }

    public function fetchSector(Request $request)
    {
        $data =
        [
            'view' => ViewEnum::INDEX->value,
            'sector_id' => $request->sector_id
        ];
        $companiesContent = $data;
        $companiesContent['route'] = $this->viewDirectoryCompany;
//        $statusesContent = $data;
//        $statusesContent['route'] = $this->viewDirectoryStatus;

        return
        [
            'companies' => $this->companyService->renderView($companiesContent)->render(),
        ];
    }
    public function fetchEmployee(Request $request)
    {
        $request->merge([
            'route' => $this->viewDirectorySector,
            'view' => ViewEnum::INDEX->value,
        ]);
        return $this->sectorService->renderView($request->all());
    }

    public function fetchCompany(Request $request)
    {
        $request->merge([
            'route' => $this->viewDirectoryContactList,
            'view' => ViewEnum::INDEX->value,
            'company_id' => $request->company_id
        ]);
        return $this->contactListService->renderView($request->all());
    }



    /**
     * Show the form for creating a new company.
     *
     * @return View
     */
    public function create(Request $request) :View
    {
        $data =
        [
            'head'=>__('deals.new'),
            'action' => route('deals.store'),
            'view' => ViewEnum::FORM->value,
            'route'=>  $this->viewDirectory ,
            'products' => $this->productService->get(),
            'payments'=>[],
            'users' => [],
            'deals' => $this->dealService->get([
                'deal_id' => 'main'
            ]),
            'payment_statuses'=>DealPaymentStatusEnum::values(),
            'statuses'=>DealStatusEnum::values(),
            'companies' => [],
            'contact_lists' => [],
            'employees' => $this->userService->get([
                'roles'=>UserRoleEnum::employees()
            ]),
            'sectors' =>[],
            'request'=>$request
        ];
        return $this->dealService->render($data);
    }

    /**
     * Store a newly created company in storage.
     * @param DealRequest $request
     * @return JsonResponse
     */
    public function store(DealRequest $request) :JsonResponse
    {
        $data = $request->validated();
        $data['month'] = date('m',strtotime($data['start_date']));
        $this->dealService->create($data);

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

    public function lock($id)
    {
        $deal = $this->dealService->getItem($id);
        if (!$deal)
        {
            abort(404);
        }
        $this->dealService->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
    {
        $deal = $this->dealService->getItem($id);
        if (!$deal)
        {
            abort(404);
        }
        $data =
        [
            'head'=>__('deals.edit'),
            'action' => route('deals.update',$deal->id),
            'view' => ViewEnum::FORM->value,
            'route'=> $this->viewDirectory,
            'products' => $this->productService->get(),
            'payments'=>$this->dealService->payments($id),
            'payment_statuses'=>DealPaymentStatusEnum::values(),
            'deals' => $this->dealService->get([
                'deal_id' => 'main'
            ]),
            'companies' => $this->companyService->get([
                'sector_id'=>$deal->sector_id
            ]),
            'employees' => $this->userService->get([
                'roles'=>UserRoleEnum::employees()
            ]),
            'contact_lists' => $this->contactListService->get([
                'company_id'=>$deal->company_id
            ]),
            'sectors' => $this->sectorService->get([
                'employee_id'=>$deal->employee_id
            ]),
            'statuses'=>DealStatusEnum::values(),
            'deal' => $deal
        ];
        return $this->dealService->render($data);
    }

    public function show(int $id) :View
    {
        $deal = $this->dealService->getItem($id);
        if (!$deal)
        {
            abort(404);
        }
        $data =
        [
            'head'=>__('deals.show'),
            'view' => ViewEnum::SHOW->value,
            'route'=> $this->viewDirectory,
            'payments'=>$this->dealService->payments($id),
            'deal' => $deal
        ];
        return $this->dealService->render($data);
    }

    /**
     * Update the specified company in storage.
     * @param DealRequest $request
     * @param int $id
     * @return JsonResponse
     */
    public function update(DealRequest $request, int $id) :JsonResponse
    {
        $deal = $this->dealService->checkItem($id);
        if (!$deal)
        {
            abort(404);
        }
        $data = $request->validated();
        $data['month'] = date('m',strtotime($data['start_date']));
        $this->dealService->update($data, $id);
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> 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->dealService->destroy($id);
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('deals.index'),
        ];
        return ResponseService::response($response);
    }

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

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

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