<?php

namespace App\Http\Controllers\Admin;

use App\Models\Installment;
use App\Http\Requests\Admin\InstallmentRequest;
use Exception;
use App\Models\InstallmentDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class InstallmentController extends Controller
{

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

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

    /**
     * return data of the courses.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Installment::join('installment_descriptions AS cd', 'installments.id', 'cd.installment_id')
            ->where('cd.language_id', currentLanguage()->id)
            ->select(['cd.name', 'installments.*']);

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

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

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


        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

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

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

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

    /**
     * Store a newly created resource in storage.
     * @param InstallmentRequest $request
     * @return JsonResponse
     */
    public function store(InstallmentRequest $request)
    {
        $installment = Installment::create($request->all());
        $this->saveData( $request, $installment->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


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

        $query = InstallmentDescription::where('installment_id', $installment->id)
            ->join('languages', 'languages.id', 'installment_descriptions.language_id')
            ->select(['installment_descriptions.*', 'languages.local']);

        $installmentDescription= $query->get();

        foreach ($installmentDescription as $row) {
            $installment[$row->local]= $row;
        }

        $local = getCurrentLocale();

        return view( $this->viewDirectory.'form', compact('installment', 'action', 'head', 'local'));
    }

    /**
     * Update the specified resource in storage.
     * @param InstallmentRequest $request
     * @param Installment $installment
     * @return JsonResponse
     */
    public function update(InstallmentRequest $request, Installment $installment)
    {
        $installment->update($request->all());
        // Delete old description
        InstallmentDescription::where('installment_id', $installment->id)->delete();
        $this->saveData( $request, $installment->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Handle Save form data
     *
     * @param InstallmentRequest $request
     * @param int $installment_id
     * @return void
     */

    private function saveData(InstallmentRequest $request, int $installment_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'name'=> $requestData['name_'.$lang->local],
                'installment_id'=> $installment_id,
                'language_id'=> $lang->id,
            ];
            InstallmentDescription::create($data);
        }

    }



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

    /**
     * Remove several courses by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Installment::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Installment::whereIn('id', $ids)->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
    {
        $installment = Installment::withTrashed()->find($id);

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

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