<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Store;
use App\Models\StoreCoupon;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Validator;

class StoreCouponController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth']);
        $this->middleware(function ($request, $next) {
            $this->user = auth()->user();
            return $next($request);
        });
        $this->theme = template();
    }

    public function index(Request $request)
    {
        $search = $request->all();
        $start_date = isset($search['start_date']) ? preg_match("/^[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}$/", $search['start_date']) : 0;
        $end_date = isset($search['end_date']) ? preg_match("/^[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}$/", $search['end_date']) : 0;

        $data['coupons'] = StoreCoupon::own($this->user->id)->with('store')
            ->when(isset($search['store_name']), function ($query) use ($search) {
                $query->whereHas('store', function ($query) use ($search) {
                    $query->where('name', 'like', '%' . $search['store_name'] . '%');
                });
            })
            ->when(isset($search['code']), function ($query) use ($search) {
                $query->where('code', 'LIKE', '%' . $search['code'] . '%');
            })
            ->when(isset($search['min_orders']), function ($query) use ($search) {
                $query->where('min_order', '>=', $search['min_orders']);
            })
            ->when($start_date == 1, function ($query) use ($search) {
                return $query->whereDate("start_date", '>=', $search['start_date']);
            })
            ->when($end_date == 1, function ($query) use ($search) {
                return $query->whereDate("end_date", '<=', $search['end_date']);
            })
            ->when(isset($search['status']), function ($query) use ($search) {
                if ($search['status'] == 'active') {
                    $query->where('status', 1)->where('end_date', '>=', Carbon::now());
                } elseif ($search['status'] == 'inactive') {
                    $query->where('status', 0)->where('end_date', '>=', Carbon::now());
                } else {
                    $query->where('end_date', '<=', Carbon::now());
                }
            })
            ->orderBy('id', 'desc')->paginate(basicControl()->paginate);
        return view($this->theme . 'user.store.coupon.index', $data);
    }

    public function create(Request $request)
    {
        if ($request->method() == 'GET') {
            $stores = Store::own($this->user->id)->where('status', 1)->toBase()->get();
            return view($this->theme . 'user.store.coupon.create', compact('stores'));
        } elseif ($request->method() == 'POST') {
            $validator = Validator::make($request->all(), [
                'store' => 'required',
                'code' => 'required|min:4|max:20',
                'min_order' => 'required|min:0|not_in:0',
                'start_date' => 'required|date|after_or_equal:today',
                'end_date' => 'required|date|after_or_equal:start_date',
                'discount_amount' => 'required|min:0|not_in:0',
                'status' => 'required',
            ]);
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }

            $purifiedData = (object)$request->all();
            $store = Store::own($this->user->id)->where('status', 1)->findOrFail($purifiedData->store);
            $couponCode = StoreCoupon::own($this->user->id)->where('code', $purifiedData->code)->where('store_id', $store->id)->exists();
            if ($couponCode) {
                return back()->withInput()->with('error', 'Code Already exists');
            }

            StoreCoupon::create([
                'store_id' => $purifiedData->store,
                'user_id' => $this->user->id,
                'code' => $purifiedData->code,
                'min_order' => $purifiedData->min_order,
                'start_date' => $purifiedData->start_date,
                'end_date' => $purifiedData->end_date,
                'discount_amount' => $purifiedData->discount_amount,
                'discount_type' => $purifiedData->discount_type,
                'status' => $purifiedData->status,
            ]);
            return back()->with('success', 'Coupon Added Successfully');
        }
    }

    public function edit(Request $request, $id)
    {
        $coupon = StoreCoupon::own($this->user->id)->findOrFail($id);
        if ($request->method() == 'GET') {
            $stores = Store::own($this->user->id)->where('status', 1)->tobase()->get();
            return view($this->theme . 'user.store..coupon.edit', compact('coupon', 'stores'));
        } elseif ($request->method() == 'POST') {
            $validator = Validator::make($request->all(), [
                'store' => 'required',
                'code' => 'required|min:4|max:15',
                'min_order' => 'required|min:0|not_in:0',
                'start_date' => 'required|date|after_or_equal:today',
                'end_date' => 'required|date|after_or_equal:start_date',
                'discount_amount' => 'required|min:0|not_in:0',
                'status' => 'required',
            ]);
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }

            $purifiedData = (object)$request->all();
            $store = Store::own($this->user->id)->where('status', 1)->findOrFail($purifiedData->store);
            $couponCode = StoreCoupon::own($this->user->id)->where('code', $purifiedData->code)->where('store_id', $store->id)->count();
            if ($couponCode > 1) {
                return back()->withInput()->with('error', 'Code Already exists');
            }

            $coupon->update([
                'store_id' => $purifiedData->store,
                'code' => $purifiedData->code,
                'min_order' => $purifiedData->min_order,
                'start_date' => $purifiedData->start_date,
                'end_date' => $purifiedData->end_date,
                'discount_amount' => $purifiedData->discount_amount,
                'discount_type' => $purifiedData->discount_type,
                'status' => $purifiedData->status,
            ]);
            return back()->with('success', 'Coupon Updated Successfully');
        }
    }

    public function delete($id)
    {
        $coupon = StoreCoupon::own($this->user->id)->findOrFail($id);
        $coupon->delete();
        return back()->with('success', 'Coupon Deleted Successfully');
    }
}
