<?php

namespace App\Http\Controllers\Admin;

use App\Exports\CompanyExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CompanyRequest;
use App\Services\Notification\NotificationService;
use App\Services\Response\ResponseService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;

use App\Models\User;
use Maatwebsite\Excel\Facades\Excel;

class CompanyController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/companies';
    /** View folder */
    private $viewDirectory = 'admin.companies.';

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('companies.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title','request'));
    }

    /**
     * return data of the companies.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request)
    {
        $query = User::where('users.role','company');

        if ($request->date_from) {
            $query->whereDate('users.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('users.created_at', '<=', $request->date_to);
        }

        if ($request->id) {
            $query->where('users.id', $request->id);
        }

        if ($request->name) {
            $query->where('cd.name', 'LIKE', '%'.$request->name.'%');
        }

        if ($request->email) {
            $query->where('users.email', 'LIKE', '%'.$request->email.'%');
        }

        if ($request->type) {
            if($request->type == 'inactive')
            {
                $query->where('users.active_account','inactive');
            }
        }
        else
        {
            $query->where('users.active_account','active');
        }


        if($request->export)
        {
            $members= $query->cursor();
            return Excel::download(new CompanyExport($members), 'Companies.xlsx');
        }
        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $companies= $query->paginate(100);

        return view($this->viewDirectory.'grid',compact('companies'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('companies.store');
        $head = metaFields('companies', 'add_new', getCurrentLocale()) ?? __('companies.new');
        return view( $this->viewDirectory.'form', compact('action', 'head') );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param CompanyRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(CompanyRequest $request)
    {
        $data = $request->all();
        $data['photo'] = 'logo.png';
        $data['active_account'] = 'active';
        $data['role'] = 'company';
        $data['password'] = bcrypt($request->password);

        $company= User::create($data);

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  User  $company
     * @return View
     */
    public function edit(User $company): View
    {
        $action= route('companies.update', $company->id);
        $head = metaFields('companies', 'edit', getCurrentLocale()) ?? __('companies.edit');

        return view( $this->viewDirectory.'form', compact('company', 'action', 'head' ) );
    }
    public function show(User $company)
    {
        $company->update(['active_account'=>'active']);
        $status = 'activation_company_account';
        (new NotificationService)->sendNotification($status,$company->id);
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  CompanyRequest  $request
     * @param  User  $company
     * @return RedirectResponse|Redirector
     */
    public function update(CompanyRequest $request, User $company)
    {
        $data['photo'] = 'logo.png';

        $data= $request->all();
        if($data['password']) {
            $data['password']= bcrypt( $data['password'] );
        } else {
            unset($data['password']);
        }
        $company->update($data);

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

    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $company = User::withTrashed()->find($id);
        if ($company) {
            if ($company->deleted_at) {
                $company->forceDelete();
            } else {
                $company->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            User::onlyTrashed()->whereIn('id', $ids)->where('role', '!=', 'admin')->forceDelete();
        } else {
            User::whereIn('id', $ids)->where('role', '!=', 'admin')->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $company = User::withTrashed()->find($id);

        if ($company){
            $company->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $company = User::whereIn('id', $request->ids)->onlyTrashed();
        if ($company){
            $company->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.saveDone')]);
    }
}
