<?php

namespace App\Http\Controllers\Admin;

use App\Package;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\PackageDescription;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\PackageRequest;

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

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

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Package::join('package_descriptions AS pcd', 'packages.id', 'pcd.package_id')
            ->where('pcd.language_id', currentLanguage()->id)
            ->select(['pcd.name', 'packages.*']);

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

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

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

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

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

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

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

    /**
     * Store a newly created resource in storage.
     * @param PackageRequest $request
     * @return RedirectResponse
     */
    public function store(PackageRequest $request) :RedirectResponse
    {
        $packages = Package::create($request->all());

        // Insert Description
        $this->saveData($request, $packages->id);

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


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

        $query = PackageDescription::where('package_id', $package->id)
            ->join('languages', 'languages.id', 'package_descriptions.language_id')
            ->select(['package_descriptions.*', 'languages.local']);

        $packagesDescription= $query->get();

        foreach ($packagesDescription as $row) {
            $package[$row->local]= $row;
        }


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

    /**
     * Update the specified resource in storage.
     * @param PackageRequest $request
     * @param Package $package
     * @return RedirectResponse|Redirector
     */
    public function update(PackageRequest $request, Package $package)
    {
        // Update the "updated_at" column only
        $data = $request->all();
//        if ($request->type != 'guest'){
//            $data['price'] = $request->price;
//            $data['period'] = $request->period;
//        } else {
//            $data['price'] = null;
//            $data['period'] = null;
//        }

        $package->update($data);

        // Delete old description
        PackageDescription::where('package_id', $package->id)->delete();

        // Insert new description
        $this->saveData( $request, $package->id);

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

    /**
     * Handle Save form data
     * @param PackageRequest $request
     * @param int $packages_id
     */

    private function saveData(PackageRequest $request, int $packages_id)
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'name'=> $requestData['name_'.$lang->local],
                'period'=> $requestData['period_'.$lang->local],
//                'description'=> $requestData['description_'.$lang->local],
                'package_id'=> $packages_id,
                'language_id'=> $lang->id,
            ];
            PackageDescription::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
    {
        $packages = Package::withTrashed()->find($id);
        if ($packages) {
            if ($packages->deleted_at) {
                $packages->forceDelete();
            } else {
                $packages->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) {
            Package::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Package::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
    {
        $packages = Package::withTrashed()->find($id);

        if ($packages){
            $packages->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
    {
        $packages = Package::whereIn('id', $request->ids)->onlyTrashed();
        if ($packages){
            $packages->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
