<?php

namespace App\Http\Controllers\Admin;

use App\Models\Coupon;
use App\Models\Order;
use Illuminate\Http\Request;
use App\CentralLogics\Helpers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Config;

class CouponController extends Controller
{
    public function add_new()
    {
        $coupons = Coupon::with('module')->where('created_by','admin')->where('module_id', Config::get('module.current_module_id'))->latest()->paginate(config('default_pagination'));
        return view('admin-views.coupon.index', compact('coupons'));
    }
    public function all()
    {
        $coupons = Coupon::with('module')->where('created_by','admin')->latest()->paginate(config('default_pagination'));
        return view('admin-views.coupon.index', compact('coupons'));
    }

    public function store(Request $request): \Illuminate\Http\RedirectResponse
    {
        $request->validate([
            'code' => 'required|unique:coupons|max:100',
            'title' => 'required|max:191',
            'start_date' => 'required',
            'expire_date' => 'required',
            'image' => 'nullable',
            'discount' => 'required',
            'coupon_type' => 'required|in:zone_wise,store_wise,free_delivery,first_order,default,vip',
            'zone_ids' => 'required_if:coupon_type,zone_wise',
            'store_ids' => 'required_if:coupon_type,store_wise',
            'items_discount_on' => 'required',
            'delivery_discount_on' => 'required',
        ]);
        $data  = '';
        $customer_id  = $request->customer_ids ?? ['all'];
        if($request->coupon_type == 'zone_wise')
        {
            $data = $request->zone_ids;
        }
        else if($request->coupon_type == 'store_wise')
        {
            $data = $request->store_ids;
        }

        if(!empty($request->store_ids)){
            //$storeId = $request->store_ids;
            $storeIds = [];
            for($i = 0; $i < count($request->store_ids); $i++){
                $storeIds[] = $request->store_ids[$i];
            }
        }else{
            //$storeId = null;
            $storeIds = null;
        }

        if(!empty($request->module_id)){
            $moduleIds = [];
            for($i = 0; $i < count($request->module_id); $i++){
                $moduleIds[] = $request->module_id[$i];
            }
        }else{
            $moduleIds = null;
        }

        //$module_id = Config::get('module.current_module_id');
        //if(isset($request->module_id)){
        //    $module_id = $request->module_id;
        //}

        if($request->has('image')){
            $image = Helpers::upload('coupon/', 'png', $request->file('image'));
        }else{
            $image = null;
        }

        DB::table('coupons')->insert([
            'title' => $request->title,
            'code' => $request->code,
            'limit' => $request->coupon_type == 'first_order' ? 1 : $request->limit,
            'one_user_coupon' => $request->one_user_coupon,
            'coupon_type' => $request->coupon_type,
            'start_date' => $request->start_date,
            'expire_date' => $request->expire_date,
            'min_purchase' => $request->min_purchase != null ? $request->min_purchase : 0,
            'max_discount' => $request->max_discount != null ? $request->max_discount : 0,
            'discount' => $request->discount_type == 'amount' ? $request->discount : $request['discount'],
            'discount_type' => $request->discount_type??'',
            'status' => 1,
            'image' => Helpers::upload('coupon/', 'png', $request->file('image')),
            'created_by' => 'admin',
            'data' => json_encode($data),
            'store_id' => null,
            'store_ids' => json_encode($storeIds),
            'customer_id' => json_encode($customer_id),
            'module_id'=> null,
            'module_ids'=> json_encode($moduleIds),
            'view_in_coupons_list'=> $request->view_in_coupons_list,
            'items_discount_on'=> $request->items_discount_on,
            'delivery_discount_on'=> $request->delivery_discount_on,
            'created_at' => now(),
            'updated_at' => now()
        ]);

        Toastr::success(translate('messages.coupon_added_successfully'));
        return back();
    }

    public function edit($id)
    {
        $coupon = Coupon::where(['id' => $id])->first();
        $orders = Order::where('coupon_code', $coupon->code)->orderBy('id', 'DESC')->paginate(20);
        return view('admin-views.coupon.edit', compact('coupon', 'orders'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'code' => 'required|max:100|unique:coupons,code,'.$id,
            'title' => 'required|max:191',
            'start_date' => 'required',
            'expire_date' => 'required',
            'discount' => 'nullable',
            'discount_type' => 'required_unless:coupon_type,free_delivery',
            'zone_ids' => 'required_if:coupon_type,zone_wise',
            'store_ids' => 'required_if:coupon_type,store_wise',
            'items_discount_on' => 'required',
            'delivery_discount_on' => 'required',
        ]);
        $data  = '';
        if($request->coupon_type == 'zone_wise')
        {
            $data = $request->zone_ids;
        }
        else if($request->coupon_type == 'store_wise')
        {
            $data = $request->store_ids;
        }

        //if($request->coupon_type == 'store_wise'){
        //    $storeId = $request->store_ids[0];
        //}else{
        //    $storeId = null;
        //}

        if(!empty($request->store_ids)){
            $storeIds = [];
            for($i = 0; $i < count($request->store_ids); $i++){
                $storeIds[] = $request->store_ids[$i];
            }
        }else{
            //$storeId = null;
            $storeIds = null;
        }

        $customer_id  = $request->customer_ids ?? ['all'];
        $coupon = Coupon::find($id);

        if(!empty($request->module_id)){
            $moduleIds = [];
            for($i = 0; $i < count($request->module_id); $i++){
                $moduleIds[] = $request->module_id[$i];
            }
        }else{
            $moduleIds = null;
        }

        //$module_id = $coupon->module_id;
        //if(isset($request->module_id)){
        //    $module_id = $request->module_id;
        //}

        DB::table('coupons')->where(['id' => $id])->update([
            'title' => $request->title,
            'code' => $request->code,
            'limit' => $request->coupon_type == 'first_order' ? 1 : $request->limit,
            'one_user_coupon' => $request->one_user_coupon,
            'coupon_type' => $request->coupon_type,
            'start_date' => $request->start_date,
            'expire_date' => $request->expire_date,
            'min_purchase' => $request->min_purchase != null ? $request->min_purchase : 0,
            'max_discount' => $request->max_discount != null ? $request->max_discount : 0,
            'discount' => $request->discount_type == 'amount' ? $request->discount : $request['discount'],
            'discount_type' => $request->discount_type??'',
            'module_id' => null,
            'module_ids' => json_encode($moduleIds),
            'view_in_coupons_list' => $request->view_in_coupons_list,
            'items_discount_on'=> $request->items_discount_on,
            'delivery_discount_on'=> $request->delivery_discount_on,
            'image' => $request->has('image') ? Helpers::update('coupon/', $coupon->image, 'png', $request->file('image')) : $coupon->image,
            'data' => json_encode($data),
            'store_id' => null,
            'store_ids' => json_encode($storeIds),
            'customer_id' => json_encode($customer_id),
            'updated_at' => now()
        ]);

        Toastr::success(translate('messages.coupon_updated_successfully'));
        return back();
    }

    public function status(Request $request)
    {
        $coupon = Coupon::find($request->id);
        $coupon->status = $request->status;
        $coupon->save();
        Toastr::success(translate('messages.coupon_status_updated'));
        return back();
    }

    public function delete(Request $request)
    {
        $coupon = Coupon::find($request->id);
        $coupon->delete();
        Toastr::success(translate('messages.coupon_deleted_successfully'));
        return back();
    }

    public function search(Request $request){
        $key = explode(' ', $request['search']);
        $coupons=Coupon::where('created_by','admin')->where(function ($q) use ($key) { //->where('module_id', Config::get('module.current_module_id'))
            foreach ($key as $value) {
                $q->orWhere('title', 'like', "%". $value ."%")
                    ->orWhere('code', 'like', "%". $value ."%");
            }
        })->limit(50)->get();
        return response()->json([
            'view'=>view('admin-views.coupon.partials._table',compact('coupons'))->render(),
            'count'=>$coupons->count()
        ]);
    }
}
