<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\CobonRequest;
use App\Models\CobonUser;
use App\Models\User;
use Exception;
use App\Models\Product;
use App\Models\CobonProduct;
use App\Models\Cobon;
use App\Models\CobonDescription;
use App\Services\Notification\NotificationService;
use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Services\Response\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class CobonController extends Controller
{

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

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('cobons.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 = Cobon::where('seller_id',null);

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

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

        if ($request->code) {
            $query->where('code', 'LIKE', '%'.$request->code.'%');
        }
        if ($request->start_date) {
            $query->where('start_date', $request->start_date);
        }
        if ($request->end_date) {
            $query->where('end_date', $request->end_date);
        }
        if ($request->discount_amount) {
            $query->where('discount_amount', $request->discount_amount);
        }
        if ($request->discount_type) {
            $query->where('discount_type', $request->discount_type);
        }
        if ($request->type) {
            $query->where('type', $request->type);
        }
        if ($request->count) {
            $query->where('count', $request->count);
        }

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create(Request $request) :View
    {
        $action= route('cobons.store');
        $head= __('cobons.new');

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

    /**
     * Store a newly created resource in storage.
     *
     * @param CobonRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(CobonRequest $request)
    {
        $data = $request->all();
        if($data['cobon_status'] == 'event')
        {
            $data['status'] = 'all';
        }
        $cobon = Cobon::create($data);
        $cobon->users()->attach($request->user_ids);
        $cobon->products()->attach($request->product_ids);
        
        
        if($cobon->cobon_status == 'event')
        {
            $this->saveData($request, $cobon->id);
            
            $type = 'cobon';
            if(!is_null($request->user_ids))
            {
                foreach($request->user_ids as $user_id)
                {
                    $notification_service = new NotificationService();
                    $name_ar = 'لديك  كوبون خصم  ( '.$cobon->code.' ) ';
                    $name_en = 'You have a coupon ( '.$cobon->code.' )';
                    $notification_service->sendNotification($type,$user_id,null,$name_ar,$name_en,$request->name_ar,$request->name_en);
                }
            }
            else
            {
                $users = User::where('role','user')->cursor();
                foreach($users as $user)
                {
                    CobonUser::create([
                        'cobon_id'=>$cobon->id,
                        'user_id'=>$user->id,
                        ]);
                    $notification_service = new NotificationService();
                    $name_ar = 'لديك  كوبون خصم  ( '.$cobon->code.' ) ';
                    $name_en = 'You have a coupon ( '.$cobon->code.' )';
                    $notification_service->sendNotification($type,$user->id,null,$name_ar,$name_en,$request->name_ar,$request->name_en);
                }
            }
        }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param Cobon  $cobon
     * @return View
     */
    public function edit(Cobon  $cobon) :View
    {
        $head= __('cobons.edit');
        $action= route('cobons.update', $cobon->id);
        $ids = CobonUser::where('cobon_id',$cobon->id)->pluck('user_id')->toArray();
        $users = User::find($ids);

        $query = CobonDescription::where('cobon_id', $cobon->id)
            ->join('languages', 'languages.id', 'cobon_descriptions.language_id')
            ->select(['cobon_descriptions.*', 'languages.local']);

        $cobonDescription= $query->get();

        foreach ($cobonDescription as $row) {
            $cobon[$row->local]= $row;
        }
        
        $ids = CobonProduct::where('cobon_id',$cobon->id)->pluck('product_id')->toArray();
        $products = Product::withDescription()->find($ids);

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

    /**
     * Update the specified resource in storage.
     *
     * @param CobonRequest $request
     * @param Cobon  $cobon
     * @return RedirectResponse|Redirector
     */
    public function update(CobonRequest $request, Cobon  $cobon)
    {

        // Update image and category id if request has it

        $data = $request->all();
        if($data['cobon_status'] == 'event')
        {
            $data['status'] = 'all';
        }
        $cobon->update($data);
        $cobon->users()->sync($request->user_ids);
        $cobon->products()->sync($request->product_ids);
        CobonDescription::where('cobon_id',$cobon->id)->delete();
        if($cobon->cobon_status == 'event')
        {
            $this->saveData($request, $cobon->id);
            
            $type = 'cobon';
            if(!is_null($request->user_ids))
            {
                foreach($request->user_ids as $user_id)
                {
                    $notification_service = new NotificationService();
                    $name_ar = 'لديك  كوبون خصم  ( '.$cobon->code.' ) ';
                    $name_en = 'You have a coupon ( '.$cobon->code.' )';
                    $notification_service->sendNotification($type,$user_id,null,$name_ar,$name_en,$request->name_ar,$request->name_en);
                }
            }
            else
            {
                $users = User::where('role','user')->cursor();
                foreach($users as $user)
                {
                    CobonUser::create([
                        'cobon_id'=>$cobon->id,
                        'user_id'=>$user->id,
                        ]);
                    $notification_service = new NotificationService();
                    $name_ar = 'لديك  كوبون خصم  ( '.$cobon->code.' ) ';
                    $name_en = 'You have a coupon ( '.$cobon->code.' )';
                    $notification_service->sendNotification($type,$user->id,null,$name_ar,$name_en,$request->name_ar,$request->name_en);
                }
            }
        }
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }

    /**
     * Handle Save form data
     *
     * @param CobonRequest $request
     * @param int $cobon_id
     * @return void
     */

    private function saveData(CobonRequest $request, int $cobon_id ):void
    {

        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'cobon_id'=> $cobon_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
            ];
            CobonDescription::create($data);
        }
    }

    public function userFilter(Request $request)
    {
        $users = User::where('role','user')->where('name', 'like', '%' . $request->name . '%')->get();

        return json_encode($users);
    }

    public function productFilter(Request $request)
    {
        $products = Product::withDescription()->where('ad.name', 'like', '%' . $request->name . '%')->get();

        return json_encode($products);
    }

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

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