<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CompanyRequest;
use App\Services\Notification\NotificationService;
use App\Models\Country;
use App\Models\UserDescription;
use App\Models\UserLink;
use App\Models\UserPhoto;
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;

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) :View
    {
        $query = User::where('users.role','company')->join('user_descriptions AS cd', 'users.id', 'cd.user_id')
            ->where('cd.language_id', currentLanguage()->id)
            ->select(['cd.name', 'users.email','users.id','users.active_account','users.created_at']);

        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 ( !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');
        $type_certificate_commercial = 'image';
        $type_tax_certificate = 'image';
        return view( $this->viewDirectory.'form', compact('action', 'head','type_certificate_commercial','type_tax_certificate') );
    }

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

        $company= User::create($data);
        $this->saveData( $request, $company->id );

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * 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');

        $query = UserDescription::where('user_id', $company->id)
            ->join('languages', 'languages.id', 'user_descriptions.language_id')
            ->select(['user_descriptions.*', 'languages.local']);

        $userDescription= $query->get();

        foreach ($userDescription as $row) {
            $company[$row->local]= $row;
        }
        $type_certificate_commercial = str_contains($company->certificate_commercial, '.pdf') ? 'pdf' : 'image';
        $type_tax_certificate = str_contains($company->tax_certificate, '.pdf') ? 'pdf' : 'image';
        $links = UserLink::where('user_id',$company->id)->cursor();
        return view( $this->viewDirectory.'form', compact('company', 'action', 'head','links','type_certificate_commercial','type_tax_certificate' ) );
    }
    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) :RedirectResponse
    {

        $data['photo'] = 'user.png';

        // dd($request->all());
        $data= $request->all();
        unset($data['certificate_commercial']);
        unset($data['tax_certificate']);
        if($data['password']) {
            $data['password']= bcrypt( $data['password'] );
        } else {
            unset($data['password']);
        }
        $company->update($data);
        if($request->hasFile('certificate_commercial'))
        {
            $file = ImageService::uploadImage($request->certificate_commercial);
            $company->update(['certificate_commercial'=>$file]);
        }
        else
        {
            $company->update(['certificate_commercial'=>$request->certificate_commercial]);
        }
        if($request->hasFile('tax_certificate'))
        {
            $file = ImageService::uploadImage($request->tax_certificate);
            $company->update(['tax_certificate'=>$file]);
        }
        else
        {
            $company->update(['tax_certificate'=>$request->tax_certificate]);
        }
        UserPhoto::where('user_id',$company->id)->delete();
        UserLink::where('user_id',$company->id)->delete();
        UserDescription::where('user_id',$company->id)->delete();

        $this->saveData( $request, $company->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    private function saveData(CompanyRequest $request, int $company_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'name'=> $requestData['name_'.$lang->local],
                'purchasing'=> $requestData['purchasing_'.$lang->local],
                'user_id'=> $company_id,
                'language_id'=> $lang->id,
            ];
            UserDescription::create($data);
        }

        if(isset($request->images))
        {
            foreach ($request->images as $row)
            {
                UserPhoto::create([
                    'photo' => $row,
                    'user_id' => $company_id,
                ]);
            }
        }
        if(isset($request->links))
        {
            foreach ($request->links as $link)
            {
                UserLink::create([
                    'link'=>$link,
                    'user_id'=>$company_id
                ]);
            }
        }

    }
    /**
     * 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')]);
    }
}
