<?php

namespace Modules\Company\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\Company\Exports\CompanyExport;
use Modules\Company\Requests\Admin\CompanyRequest;
use Modules\Company\Services\CompanyService;
use Modules\ContactList\Exports\ContactListExport;
use Modules\Country\Services\CountryService;
use Modules\MainService\Enums\ViewEnum;
use Modules\Region\Services\RegionService;
use Modules\Sector\Services\SectorService;

class CompanyController extends Controller
{

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

    public function __construct(
        private CompanyService $companyService,
        private CountryService $countryService,
        private RegionService $regionService,
        private SectorService $sectorService
    ){}

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

    /**
     * return data of the companies.
     *
     * @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)
        {
            $companies = $this->companyService->get($request->all());
            return Excel::download(new CompanyExport($companies,Auth::user()), 'companies.xlsx');
        }
        $typeView = $request->typeView ?? ViewEnum::LIST->value;
        $request->merge([
            'route' => $this->viewDirectory,
            'view' => $typeView,
            'request'=>$request,
            'groupSector' => $typeView == ViewEnum::KANBAN->value ? true : false,
            'paginate' => $typeView != ViewEnum::KANBAN->value ? true : false,
            'countries' => $this->countryService->get(),
            'sectors'=>$this->sectorService->get()
        ]);
        return $this->companyService->renderView($request->all());
    }

    public function fetchRegions(Request $request) :View
    {
        $data =
        [
            'regions' => $this->regionService->get($request->all()),
            'view' => ViewEnum::INDEX->value,
            'route'=> $this->viewDirectoryRegions,
        ];
        return $this->companyService->render($data);
    }

    /**
     * Show the form for creating a new company.
     *
     * @return View
     */
    public function create() :View
    {
        $data =
        [
            'head'=>__('companies.new'),
            'action' => route('companies.store'),
            'view' => ViewEnum::FORM->value,
            'route'=> $this->viewDirectory,
            'countries' => $this->countryService->get(),
            'regions'=> [],
            'sectors' => $this->sectorService->get(),
        ];
        return $this->companyService->render($data);
    }

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

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

    public function lock($id)
    {
        $company = $this->companyService->getItem($id);
        if (!$company)
        {
            abort(404);
        }
        $this->companyService->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
    {
        $company = $this->companyService->getItem($id);
        if (!$company)
        {
            abort(404);
        }
        $data =
        [
            'head'=>__('companies.edit'),
            'action' => route('companies.update',$company->id),
            'view' => ViewEnum::FORM->value,
            'route'=> $this->viewDirectory,
            'sectors' => $this->sectorService->get(),
            'countries' => $this->countryService->get(),
            'regions' => $this->regionService->get(['country_id' => $company->country_idx]),
            'company' => $company
        ];
        return $this->companyService->render($data);
    }

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

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

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

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

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