<?php


namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class CouponController extends Controller
{
    private function processJsonInput(Request $request, array $fields): array
    {
        $data = [];
        foreach ($fields as $field) {
            $textField = $field . '_text';
            if ($request->filled($textField)) {
                $data[$field] = array_map('trim', explode(',', $request->input($textField)));
            } else {
                $data[$field] = []; // Use an empty array as the default value
            }
        }
        return $data;
    }

    private function getValidationRules($couponId = null): array
    {
        return [
            'code' => ['required', 'string', 'max:255', Rule::unique('coupons')->ignore($couponId)],
            'description' => ['nullable', 'string'],
            'type' => ['required', Rule::in(Coupon::TYPES)],
            'amount' => ['required', 'numeric', 'min:0'],
            'allow_free_shipment' => ['nullable', 'boolean'],
            'expire_date' => ['nullable', 'date'],
            'max_discount' => ['nullable', 'numeric', 'min:0'],
            'minimum_spend' => ['nullable', 'numeric', 'min:0'],
            'maximum_spend' => ['nullable', 'numeric', 'min:0', 'gte:minimum_spend'],
            'individual_use_only' => ['nullable', 'boolean'],
            'exclude_sale_items' => ['nullable', 'boolean'],
            'products_text' => ['nullable', 'string'],
            'exclude_products_text' => ['nullable', 'string'],
            'product_categories_text' => ['nullable', 'string'],
            'exclude_categories_text' => ['nullable', 'string'],
            'allowed_emails_text' => ['nullable', 'string'],
            'usage_limit' => ['nullable', 'integer', 'min:0'],
            'product_limit' => ['nullable', 'integer', 'min:0'],
            'usage_limit_per_user' => ['nullable', 'integer', 'min:0'],
        ];
    }

    public function index()
    {
        $coupons = Coupon::latest()->paginate(15);
        return view('pages.admin.coupon.index', compact('coupons'));
    }

    public function create()
    {
        return view('pages.admin.coupon.create');
    }

    public function store(Request $request)
    {

        $validatedData = $request->validate($this->getValidationRules());
        $jsonFieldsData = $this->processJsonInput($request, [
            'products',
            'exclude_products',
            'product_categories',
            'exclude_categories',
            'allowed_emails'
        ]);

        $couponData = array_merge(
            $request->except(['_token', '_method', 'products_text', 'exclude_products_text', 'product_categories_text', 'exclude_categories_text', 'allowed_emails_text']),
            $jsonFieldsData
        );

        $couponData['allow_free_shipment'] = $request->has('allow_free_shipment');
        $couponData['individual_use_only'] = $request->has('individual_use_only');
        $couponData['exclude_sale_items'] = $request->has('exclude_sale_items');


        Coupon::create($couponData);

        return redirect()->route('admin.coupons.index')->with('success', __('Coupon created successfully.'));
    }

    public function show(Coupon $coupon)
    {
        return view('pages.admin.coupon.show', compact('coupon'));
    }

    public function edit(Coupon $coupon)
    {
        return view('pages.admin.coupon.edit', compact('coupon'));
    }

    public function update(Request $request, Coupon $coupon)
    {
        $validatedData = $request->validate($this->getValidationRules($coupon->id));

        $jsonFieldsData = $this->processJsonInput($request, [
            'products',
            'exclude_products',
            'product_categories',
            'exclude_categories',
            'allowed_emails'
        ]);

        $couponData = array_merge(
            $request->except(['_token', '_method', 'products_text', 'exclude_products_text', 'product_categories_text', 'exclude_categories_text', 'allowed_emails_text']),
            $jsonFieldsData
        );

        $couponData['allow_free_shipment'] = $request->has('allow_free_shipment');
        $couponData['individual_use_only'] = $request->has('individual_use_only');
        $couponData['exclude_sale_items'] = $request->has('exclude_sale_items');

        $coupon->update($couponData);

        return redirect()->route('admin.coupons.index')->with('success', __('Coupon updated successfully.'));
    }

    public function destroy(Coupon $coupon)
    {
        $coupon->delete();
        return redirect()->route('admin.coupons.index')->with('success', __('Coupon deleted successfully.'));
    }
}
