<?php

namespace Modules\DailyLog\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\Enums\ContactStatusEnum;
use Modules\ContactList\Services\ContactListService;
use Modules\DailyLog\Enums\DailyLogActionEnum;
use Modules\DailyLog\Enums\DailyLogObjectiveEnum;
use Modules\DailyLog\Enums\DailyLogTypeEnum;
use Modules\DailyLog\Exports\DailyLogExport;
use Modules\DailyLog\Requests\Admin\DailyLogRequest;
use Modules\DailyLog\Services\DailyLogService;
use Modules\MainService\Enums\ViewEnum;
use Modules\Sector\Services\SectorService;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Services\UserService;

class DailyLogController extends Controller
{

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

    public function __construct(
        private DailyLogService $dailyLogService,
        private ContactListService $contactListService,
        private UserService $userService
    ){}

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

    public function fetchContactList(Request $request)
    {
        $contactList = $this->contactListService->getItem($request->contact_list_id);
        $data =
            [
                'view' => ViewEnum::LIST->value,
                'route'=>$this->viewDirectory.'contact_lists.',
                'contactList' => $contactList,
            ];
        $info = $this->dailyLogService->render($data);

        $data =
        [
            'view' => ViewEnum::INDEX->value,
            'statuses'=>ContactStatusEnum::values(),
            'contactList' => $contactList,
            'route'=>$this->viewDirectory.'contact_lists.',
        ];
        $statuses = $this->dailyLogService->render($data);

        return [
            'info'=>$info->render(),
            'statuses'=>$statuses->render(),
        ];
    }

    /**
     * return data of the daily_logs.
     *
     * @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)
        {
            $daily_logs = $this->dailyLogService->get($request->all());
            return Excel::download(new DailyLogExport($daily_logs,Auth::user()), 'daily_logs.xlsx');
        }
        $typeView = $request->typeView ?? ViewEnum::LIST->value;
        $objectives = DailyLogObjectiveEnum::values();
        $actions = DailyLogActionEnum::values();
        $types = DailyLogTypeEnum::values();
        $request->merge([
            'route' => $this->viewDirectory,
            'view' => $typeView,
            'request'=>$request,
            'objectives'=>$objectives,
            'types'=>$types,
            'actions'=>$actions,
            'paginate' => $typeView != ViewEnum::KANBAN->value ? true : false,
        ]);
        return $this->dailyLogService->renderView($request->all());
    }

    /**
     * Show the form for creating a new daily_logs.
     *
     * @return View
     */
    public function create() :View
    {
        $types = DailyLogTypeEnum::values();
        $objectives = DailyLogObjectiveEnum::values();
        $next_actions = DailyLogActionEnum::values();
        $statuses = ContactStatusEnum::values();
        $data =
            [
                'head'=>__('daily_logs.new'),
                'action' => route($this->actionDirectory.'store'),
                'view' => ViewEnum::FORM->value,
                'employees'=>$this->userService->get(['roles'=>UserRoleEnum::employees()]),
                'contact_lists'=>$this->contactListService->get(),
                'types'=>$types,
                'objectives'=>$objectives,
                'next_actions'=>$next_actions,
                'statuses'=>$statuses,
                'other'=>DailyLogObjectiveEnum::OTHER->value,
                'route'=> $this->viewDirectory,
            ];
        return $this->dailyLogService->render($data);
    }

    /**
     * Store a newly created DailyLog in storage.
     * @param DailyLogRequest $request
     * @return JsonResponse
     */
    public function store(DailyLogRequest $request) :JsonResponse
    {
        $this->dailyLogService->create($request->validated());
        $contact_list = $this->contactListService->getItem($request->contact_list_id);
        if(!is_null($request->status) & $request->status != $contact_list->status)
        {
            $this->contactListService->update([
                'status'=>$request->status
            ],$request->contact_list_id);
        }
        $contact_list = $this->contactListService->getItem($request->contact_list_id);
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $contact_list->status == ContactStatusEnum::BRIEF_RECIEVED->value ? route('deals.index').'?open_create=true' : url()->previous(),
        ];
        return ResponseService::response($response);
    }

    public function lock($id)
    {
        $dailyLog = $this->dailyLogService->getItem($id);
        if (!$dailyLog)
        {
            abort(404);
        }
        $this->dailyLogService->updateLock($id);
        session()->flash('message', __('dashboard.saveDone'));
        return redirect()->back();
    }
    /**
     * Show the form for editing the specified DailyLog.
     *
     * @param  int $id
     * @return View
     */
    public function edit(int $id) :View
    {
        $dailyLog = $this->dailyLogService->getItem($id);
        if (!$dailyLog)
        {
            abort(404);
        }
        $types = DailyLogTypeEnum::values();
        $objectives = DailyLogObjectiveEnum::values();
        $next_actions = DailyLogActionEnum::values();
        $statuses = ContactStatusEnum::values();
        $data =
            [
                'head'=>__('daily_logs.edit'),
                'action' => route($this->actionDirectory.'update',$dailyLog->id),
                'view' => ViewEnum::FORM->value,
                'route'=> $this->viewDirectory,
                'employees'=>$this->userService->get(['roles'=>UserRoleEnum::employees()]),
                'contact_lists'=>$this->contactListService->get(),
                'types'=>$types,
                'objectives'=>$objectives,
                'next_actions'=>$next_actions,
                'other'=>DailyLogObjectiveEnum::OTHER->value,
                'statuses'=>$statuses,
                'dailyLog' => $dailyLog
            ];
        return $this->dailyLogService->render($data);
    }
    public function show(int $id) :View
    {
        $dailyLog = $this->dailyLogService->getItem($id);
        if (!$dailyLog)
        {
            abort(404);
        }
        $data =
            [
                'head'=>__('daily_logs.show'),
                'view' => ViewEnum::SHOW->value,
                'route'=> $this->viewDirectory,
                'dailyLog' => $dailyLog
            ];
        return $this->dailyLogService->render($data);
    }

    /**
     * Update the specified DailyLog in storage.
     * @param DailyLogRequest $request
     * @param int $id
     * @return JsonResponse
     */
    public function update(DailyLogRequest $request, int $id) :JsonResponse
    {
        $dailyLog = $this->dailyLogService->checkItem($id);
        if (!$dailyLog)
        {
            abort(404);
        }
        $this->dailyLogService->update($request->validated(), $id);
        $contact_list = $this->contactListService->getItem($request->contact_list_id);
        if(!is_null($request->status) & $request->status != $contact_list->status)
        {
            $this->contactListService->update([
                'status'=>$request->status
            ],$request->contact_list_id);
        }
        $contact_list = $this->contactListService->getItem($request->contact_list_id);
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $contact_list->status == ContactStatusEnum::BRIEF_RECIEVED->value ? route('deals.index').'?open_create=true' : url()->previous(),
        ];
        return ResponseService::response($response);
    }

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

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

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

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