<?php

namespace App\Http\Controllers\Admin;

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

use App\Package;
use App\PackageDescriptions;
use App\Language;
use App\Module;
use Users_model;

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 packages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query =Package::orderBy('id', 'ASC');

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

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

        if ($request->name) {
            $query->whereIn('id', packagesearchname($request->name));
        }
        if ($request->description) {
            $query->whereIn('id', packagesearchname($request->description));
        }
        if ($request->cost) {
            $query->where('cost',$request->cost);
        }

        if ($request->lang) {
            $query->whereIn('language_id', currentLanguageid($request->lang) );
        }

      

        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');
        $language = Language::where('status',1)->get();

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

    /**
     * Store a newly created resource in storage.
     *
     * @param PackageRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(PackageRequest $request) :RedirectResponse
    {
        
        $package  = Package::create([
            'cost'=>$request->cost
        ]);
        $img=$request->file('img');
        
        $name=mt_rand(1000000, 9999999).time().'img-'.$package->id.'.'.$img->getClientOriginalExtension();
        $img->move(public_path('/lamis/images/packages/'),$name);
        $package->img=$name;
        $package->save();
        foreach ($request->package as $key => $row) {
            
            PackageDescriptions::create([
                'name'=>$row['name'],
                'language_id'=>$row['language_id'],
                'description'=>$row['description'],
                'package_id' =>$package->id,
                
           ]);
        }
        

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

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

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

    /**
     * Update the specified resource in storage.
     *
     * @param  PackageRequest  $request
     * @param  PackageDescriptions  $package
     * @return RedirectResponse|Redirector
     */
    public function update(PackageRequest $request, Package $package) :RedirectResponse
    {
        if ($request->hasFile('img')) {
            $image = $request->hasFile('img');
        }
        else{
            $image = $package->img;
            
        }
        $package->forceDelete();
        
         $packages  = Package::create([
            'cost'=>$request->cost
        ]);
        if ($request->hasFile('img')) {
            
        $img=$request->img;
        
        $name=mt_rand(1000000, 9999999).time().'img-'.$packages->id.'.'.$img->getClientOriginalExtension();
        $img->move(public_path('/lamis/images/packages/'),$name);
        $packages->img=$name;
        $packages->save();
        }
        else{
            $packages->img=$image;
        $packages->save();
        }
        foreach ($request->package as $key => $row) {
            
            PackageDescriptions::create([
                'name'=>$row['name'],
                'language_id'=>$row['language_id'],
                'description'=>$row['description'],
                'package_id' =>$packages->id,
                
           ]);
        }
        


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

    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $package = Package::withTrashed()->find($id);
        if ($package) {
            if ($package->deleted_at) {
                $package->forceDelete();
            } else {
                $package->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
    {
        $package = Package::withTrashed()->find($id);

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