<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Domin;
use App\Models\Group;
use App\Models\Plan;
use App\Models\PlanPrice;
use App\Models\Subscription;
use Carbon\Carbon;

use App\Models\User;
use Illuminate\Http\Request;

class SubscriptionsController extends Controller
{
    public function index(Request $request)
    {
        $this->authorize('viewAny', Subscription::class);
        if ($request->ajax()) {
            // dd($request->all());
            $draw = $request->get('draw');
            $start = $request->get("start");
            $rowperpage = $request->get("length"); // Rows display per page
            $search_arr = $request->get('search');
            $searchValue = $search_arr['value']; // Search value
            $totalRecords = Subscription::select('count(*) as allcount')->count();
            $totalRecordswithFilter = Subscription::select('count(*) as allcount')
                ->whereHas('customer', function ($query) use ($searchValue){
                    $query->where('name','LIKE',"%$searchValue%");
                })
                ->orWhereHas('domin', function ($query) use ($searchValue){
                    $query->where('name','LIKE',"%$searchValue%");
                })
                ->orWhereHas('plan', function ($query) use ($searchValue){
                    $query->whereHas('group', function ($query) use ($searchValue){
                        $query->where('name','LIKE',"%$searchValue%");
                    });
                })
                ->orWhere('id', 'like', '%' . $searchValue . '%')
                ->count();

            $subscriptions = Subscription::select('subscriptions.*')
                ->whereHas('customer', function ($query) use ($searchValue){
                    $query->where('name','LIKE',"%$searchValue%");
                })
                ->orWhereHas('domin', function ($query) use ($searchValue){
                    $query->where('name','LIKE',"%$searchValue%");
                })
                ->orWhereHas('plan', function ($query) use ($searchValue){
                    $query->whereHas('group', function ($query) use ($searchValue){
                        $query->where('name','LIKE',"%$searchValue%");
                    });
                })
                ->orWhere('id', 'like', '%' . $searchValue . '%')
                ->skip($start)
                ->take($rowperpage)
                ->orderBy('subscriptions.id', 'desc')
                ->get();


            $records = [];

            foreach($subscriptions as $item)
            {
                $status = '';
                if($item->status == 0) {
                    
                    $status ='<span class="badge badge-soft-info text-uppercase">' . __('Active') . '</span>';
                }
                else if($item->status == 1) {
                    
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('Canceled') . '</span>';
                }
                else if($item->status == 2) {
                    $status = '<span class="badge badge-soft-warning text-uppercase">' . __('Stopped') . '</span>' ;
                }
                else if($item->status == 3) {
                    $status ='<span class="badge badge-soft-primary text-uppercase">' . __('Not Enabled') . '</span>';
                }

                $status_0 = '';
                if($item->status_0 == 0) {
                    $status_0 = '<span class="badge badge-soft-success text-uppercase">' . __('Paid') . '</span>' ;
                }
                else if($item->status_0 == 1) {
                    $status_0 ='<span class="badge badge-soft-danger text-uppercase">' . __('Worthy') . '</span>' ;
                }

                $currancy = '';
                if($item->currancy == 0) {
                    $currancy = '$';
                } else if ($item->currancy == 1) {
                    $currancy = 'SAR';
                } else if ($item->currancy == 2) {
                    $currancy = 'ILS';
                }

                $records[] = [
                    'record_select' =>view('admin.subscriptions.datatable.record',[ 'item' => $item ])->render(),
                    'id' => $item->id,
                    'customer' => $item->customer->name,
                    'type' => $item->type == 0 ? $item->plan->group->name . ' ' . $item->plan->title : $item->domin->name,
                    'start_date' => $item->start_date,
                    'subscrip_date' => $item->subscrip_date,
                    'due_date' => $item->due_date,
                    'end_date' => $item->end_date,
                    'price' => $item->price . ' ' . $currancy,
                    'status' => $status,
                    'status_0' => $status_0,
                    'actions' => view('admin.subscriptions.datatable.buttons',[ 'item' => $item ])->render() ,
                ];
            }

            $response = [
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordswithFilter,
                "aaData" => $records
            ];

            return response()->json($response);

        }
        $count_subscriptions = Subscription::count();  
        $count_domins = Subscription::where('type','1')->count();
        $count_paid = Subscription::where('status_0','0')->count();
        $count_ntactive = Subscription::where('status', '!=' ,'0')->count();
        return view('admin.subscriptions.index',[
            'count_subscriptions' => $count_subscriptions,
            'count_domins' => $count_domins,
            'count_paid' => $count_paid,
            'count_ntactive' => $count_ntactive
        ]);
    }



    public function subscriptionsdue(Request $request)
    { 
        $this->authorize('viewAny', Subscription::class);
        $date = Carbon::now( )->format('Y-m-d') ;
        if ($request->ajax()) {
            // dd($request->all());
            $draw = $request->get('draw');
            $start = $request->get("start");
            $rowperpage = $request->get("length"); // Rows display per page
            $search_arr = $request->get('search');
            $searchValue = $search_arr['value']; // Search value
            $totalRecords = Subscription::select('count(*) as allcount')->whereDate('due_date', '<=', $date)->count();
            $totalRecordswithFilter = Subscription::select('count(*) as allcount')
                ->whereDate('due_date', '<=', $date) 
                ->orWhere('id', 'like', '%' . $searchValue . '%')
                ->count();
               
            $subscriptions = Subscription::select('subscriptions.*') 
                ->whereDate('due_date', '<=', $date)
                ->skip($start)
                ->take($rowperpage)
                ->orderBy('subscriptions.id', 'desc')
                ->get();


            $records = [];

            foreach($subscriptions as $item)
            {
                $status = '';
                if($item->status == 0) {
                    
                    $status ='<span class="badge badge-soft-info text-uppercase">' . __('Active') . '</span>';
                }
                else if($item->status == 1) {
                    
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('Canceled') . '</span>';
                }
                else if($item->status == 2) {
                    $status = '<span class="badge badge-soft-warning text-uppercase">' . __('Stopped') . '</span>' ;
                }
                else if($item->status == 3) {
                    $status ='<span class="badge badge-soft-primary text-uppercase">' . __('Not Enabled') . '</span>';
                }

                $status_0 = '';
                if($item->status_0 == 0) {
                    $status_0 = '<span class="badge badge-soft-success text-uppercase">' . __('Paid') . '</span>' ;
                }
                else if($item->status_0 == 1) {
                    $status_0 ='<span class="badge badge-soft-danger text-uppercase">' . __('Worthy') . '</span>' ;
                }

                $currancy = '';
                if($item->currancy == 0) {
                    $currancy = '$';
                } else if ($item->currancy == 1) {
                    $currancy = 'SAR';
                } else if ($item->currancy == 2) {
                    $currancy = 'ILS';
                }

                $records[] = [
                    'record_select' =>view('admin.subscriptions.datatable.record',[ 'item' => $item ])->render(),
                    'id' => $item->id,
                    'customer' => $item->customer->name,
                    'type' => $item->type == 0 ? $item->plan->group->name . ' ' . $item->plan->title : $item->domin->name,
                    'start_date' => $item->start_date,
                    'subscrip_date' => $item->subscrip_date,
                    'due_date' => $item->due_date,
                    'end_date' => $item->end_date,
                    'price' => $item->price . ' ' . $currancy,
                    'status' => $status,
                    'status_0' => $status_0,
                    'actions' => view('admin.subscriptions.datatable.buttons',[ 'item' => $item ])->render() ,
                ];
            }

            $response = [
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordswithFilter,
                "aaData" => $records
            ];

            return response()->json($response);

        }
        $count_subscriptions = Subscription::whereDate('due_date', '<=', $date)->count();  
         
        return view('admin.subscriptions.subscriptionsdue',[
            'count_subscriptions' => $count_subscriptions 
        ]);
    }





    public function muSubscriptions(Request $request)
    {
        $this->authorize('client', User::class);
        $type = $request->type;
        if ($request->ajax()) {
            // dd($request->all());
            $draw = $request->get('draw');
            $start = $request->get("start");
            $rowperpage = $request->get("length"); // Rows display per page
            $search_arr = $request->get('search');
            $searchValue = $search_arr['value']; // Search value
            $totalRecords = auth()->user()->subscriptions()->where('type', $request->type)->select('count(*) as allcount')->count();
            $totalRecordswithFilter = auth()->user()->subscriptions()->where('type', $request->type)->select('count(*) as allcount')
                ->where(function ($q) use ($searchValue){
                    $q->whereHas('customer', function ($query) use ($searchValue){
                        $query->where('name','LIKE',"%$searchValue%");
                    })
                    ->orWhereHas('domin', function ($query) use ($searchValue){
                        $query->where('name','LIKE',"%$searchValue%");
                    })
                    ->orWhereHas('plan', function ($query) use ($searchValue){
                        $query->whereHas('group', function ($query) use ($searchValue){
                            $query->where('name','LIKE',"%$searchValue%");
                        });
                    })
                    ->orWhere('id', 'like', '%' . $searchValue . '%');
                })
                ->count();

            $subscriptions = auth()->user()->subscriptions()->where('type', $request->type)->select('subscriptions.*')
                ->where(function ($q) use ($searchValue){
                    $q->whereHas('customer', function ($query) use ($searchValue){
                        $query->where('name','LIKE',"%$searchValue%");
                    })
                    ->orWhereHas('domin', function ($query) use ($searchValue){
                        $query->where('name','LIKE',"%$searchValue%");
                    })
                    ->orWhereHas('plan', function ($query) use ($searchValue){
                        $query->whereHas('group', function ($query) use ($searchValue){
                            $query->where('name','LIKE',"%$searchValue%");
                        });
                    })
                    ->orWhere('id', 'like', '%' . $searchValue . '%');
                })
                ->skip($start)
                ->take($rowperpage)
                ->orderBy('subscriptions.id', 'desc')
                ->get();


            $records = [];

            foreach($subscriptions as $item)
            {
                $status = '';
                if($item->status == 0) {
                    
                    $status ='<span class="badge badge-soft-info text-uppercase">' . __('Active') . '</span>';
                }
                else if($item->status == 1) {
                    
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('Canceled') . '</span>';
                }
                else if($item->status == 2) {
                    $status = '<span class="badge badge-soft-warning text-uppercase">' . __('Stopped') . '</span>' ;
                }
                else if($item->status == 3) {
                    $status ='<span class="badge badge-soft-primary text-uppercase">' . __('Not Enabled') . '</span>';
                }

                $status_0 = '';
                if($item->status_0 == 0) {
                    $status_0 = '<span class="badge badge-soft-success text-uppercase">' . __('Paid') . '</span>' ;
                }
                else if($item->status_0 == 1) {
                    $status_0 ='<span class="badge badge-soft-danger text-uppercase">' . __('Worthy') . '</span>' ;
                }

                $currancy = '';
                if($item->currancy == 0) {
                    $currancy = '$';
                } else if ($item->currancy == 1) {
                    $currancy = 'SAR';
                } else if ($item->currancy == 2) {
                    $currancy = 'ILS';
                }

                $records[] = [
                    'id' => $item->id,
                    'name' => $item->type == 0 ? $item->plan->group->name . ' ' . $item->plan->title : $item->domin->name,
                    'start_date' => $item->start_date,
                    'subscrip_date' => $item->subscrip_date,
                    'due_date' => $item->due_date,
                    'end_date' => $item->end_date,
                    'price' => $item->price . ' ' . $currancy,
                    'status' => $status,
                    'status_0' => $status_0,
                    'actions' => view('admin.subscriptions.datatable.my-buttons',[ 'item' => $item ])->render() ,
                ];
            }

            $response = [
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordswithFilter,
                "aaData" => $records
            ];

            return response()->json($response);

        }

        return view('admin.subscriptions.my-subscriptions', [
            'type' => $type
        ]);
    }

    public function create()
    {
        # code...
        $this->authorize('create', Subscription::class);
        $customers = User::where('role_id',0)->latest()->get();
        return view('admin.subscriptions.create', [
            'customers' => $customers,
        ]);
    }

    public function store(Request $request)
    {
        # code...
        $this->authorize('create', Subscription::class);
        $currancy = null;
        if($request->type == 0){
            $request->validate([
                'status' => 'required|in:0,1,2,3',
                'status_0' => 'required|in:0,1',
                'customer_id' => 'required|exists:users,id',
                'domin_id' => 'nullable|exists:domins,id',
                'price' => 'required|numeric',
                'tax' => 'nullable|numeric',
                'discount' => 'nullable|numeric',
                'start_date' => 'required|date',
                'subscrip_date' => 'required|date',
                'due_date' => 'required|date',
                'end_date' => 'required|date',
                'type' => 'required|in:0,1',
                'plan_id' => 'required|exists:plans,id',
                'price_type' => 'required|in:1,2,3,4,5',
            ]);
            $plan = PlanPrice::where([['plan_id', $request->plan_id], ['type', $request->price_type]])->first();
            $currancy = $plan->currancy ?? '0';
            $price = $plan->price;
        }else{
            $request->validate([
                'status' => 'required|in:0,1,2,3',
                'status_0' => 'required|in:0,1',
                'customer_id' => 'required|exists:users,id',
                'domin_id' => 'required|exists:domins,id',
                'price' => 'required|numeric',
                'tax' => 'nullable|numeric',
                'discount' => 'nullable|numeric',
                'start_date' => 'required|date',
                'subscrip_date' => 'required|date',
                'due_date' => 'required|date',
                'end_date' => 'required|date',
                'type' => 'required|in:0,1',
                'plan_id' => 'nullable|exists:plans,id',
                'price_type' => 'nullable|in:1,2,3,4,5',
            ]);
            $domin = Domin::where('id', $request->domin_id)->first();
            $currancy = $domin->currancy;
            $price = $domin->price;
        }

        $data = $request->all();

        $data['user_id'] = $request->customer_id;
        $data['currancy'] = $currancy;
        $data['price'] = $price;

        Subscription::create($data);

        return redirect()->route('c-panel.subscriptions.index')->with('success', __('Added Done !'));
    }

    public function edit(Subscription $subscription)
    {
        # code...
        $this->authorize('update', $subscription);
        $customers = User::where('role_id',0)->latest()->get();
        return view('admin.subscriptions.edit', [
            'customers' => $customers,
            'subscription' => $subscription
        ]);
    }

    public function update(Request $request, Subscription $subscription)
    {
        # code...
        $this->authorize('update', $subscription);
        if($request->type == 0){
            $request->validate([
                'status' => 'required|in:0,1,2,3',
                'status_0' => 'required|in:0,1',
                'customer_id' => 'required|exists:users,id',
                'domin_id' => 'nullable|exists:domins,id',
                'price' => 'required|numeric',
                'tax' => 'nullable|numeric',
                'discount' => 'nullable|numeric',
                'start_date' => 'required|date',
                'subscrip_date' => 'required|date',
                'due_date' => 'required|date',
                'end_date' => 'required|date',
                'type' => 'required|in:0,1',
                'plan_id' => 'required|exists:plans,id',
                'price_type' => 'required|in:1,2,3,4,5',
            ]);
            $plan = PlanPrice::where([['plan_id', $request->plan_id], ['type', $request->price_type]])->first();
            $currancy = $plan->currancy;
            $price = $plan->price;
        }else{
            $request->validate([
                'status' => 'required|in:0,1,2,3',
                'status_0' => 'required|in:0,1',
                'customer_id' => 'required|exists:users,id',
                'domin_id' => 'required|exists:domins,id',
                'price' => 'required|numeric',
                'tax' => 'nullable|numeric',
                'discount' => 'nullable|numeric',
                'start_date' => 'required|date',
                'subscrip_date' => 'required|date',
                'due_date' => 'required|date',
                'end_date' => 'required|date',
                'type' => 'required|in:0,1',
                'plan_id' => 'nullable|exists:plans,id',
                'price_type' => 'nullable|in:1,2,3,4,5',
            ]);
            $domin = Domin::where('id', $request->domin_id)->first();
            $currancy = $domin->currancy;
            $price = $domin->price;
        }

        $data = $request->all();

        $data['user_id'] = $request->customer_id;
        $data['currancy'] = $currancy;
        $data['price'] = $price;

        $subscription->update($data);

        return redirect()->route('c-panel.subscriptions.index')->with('success', __('Updated Done !'));
    }

    public function destroy(Subscription $subscription)
    {
        # code...
        $this->authorize('delete', $subscription);
        $subscription->delete();
        return redirect()->route('c-panel.subscriptions.index')->with('success', __('Deleted Done !'));
    }


    public function bulkDelete()
    {
        // dd(json_decode(request()->record_ids));
        if(count(json_decode(request()->record_ids)) != 0){
            foreach (json_decode(request()->record_ids) as $recordId) {
                $subscription = Subscription::FindOrFail($recordId);
                $this->authorize('delete', $subscription);
                $this->delete($subscription);
            }//end of for each
        }else{
            return redirect()->route('c-panel.subscriptions.index')->with('error',__('Please Select Record Before Delete'));
        }

        return redirect()->route('c-panel.subscriptions.index')->with('success',__('Selected  Deleted Done !'));
    }// end of bulkDelete

    private function delete(Subscription $subscription)
    {
        $this->authorize('delete', $subscription);
        $subscription->delete();
    }

    public function getPlans(Group $group)
    {
        # code...
        return response()->json($group->plans);
    }

    public function getPrices(Plan $plan)
    {
        # code...
        return response()->json($plan->prices);
    }

    public function getGroupPrice($type,Plan $plan)
    {
        # code...
        $price = $plan->prices()->where('type', $type)->first()->price;
        return response()->json([
            'price' => $price,
        ]);
    }

    public function getDominPrice(Domin $domin)
    {
        # code...
        $price = $domin->price;
        return response()->json([
            'price' => $price,
        ]);
    }
}
