<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Models\CouponDiscountModel;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Log;

class CouponUpdateController extends Controller
{
   public function updateCoupon(Request $request, $id) {
    try {
        Log::info("Received data for updating coupon:", $request->all());

        // Find the coupon by the provided ID
        $couponUpdate = CouponDiscountModel::find($id);

        if (!$couponUpdate) {
            return response()->json(['error' => 'Coupon not found'], 404);
        }

        // Update the coupon with the new data
        $couponUpdate->coupon_code = $request->input('coupon_code', $couponUpdate->coupon_code);
        $couponUpdate->usage_limit = $request->input('usage_limit', $couponUpdate->usage_limit);
        $couponUpdate->apply_coupon_on_product = $request->input('apply_coupon_on_product', $couponUpdate->apply_coupon_on_product);
        $couponUpdate->discount = $request->input('discount', $couponUpdate->discount);
        $couponUpdate->orderValues = $request->input('orderValues', $couponUpdate->orderValues);
        $couponUpdate->orderQuality = $request->input('orderQuality', $couponUpdate->orderQuality);
        $couponUpdate->minimum_value = $request->input('minimum_value', $couponUpdate->minimum_value);
        $couponUpdate->upto_value = $request->input('upto_value', $couponUpdate->upto_value);
        $couponUpdate->start_date = $request->input('start_date', $couponUpdate->start_date);
        $couponUpdate->end_date = $request->input('end_date', $couponUpdate->end_date);
        $couponUpdate->time = $request->input('time', $couponUpdate->time);
        $couponUpdate->coupon_functionality = $request->input('coupon_functionality', $couponUpdate->coupon_functionality);

        // Save the updated coupon
        $couponUpdate->save();

        Log::info("Coupon updated successfully:", $couponUpdate->toArray());

        return response()->json(['message' => 'Coupon updated successfully!'], 200);
    } catch (\Exception $e) {
        Log::error("Error updating coupon:", ['error' => $e->getMessage()]);
        return response()->json(['error' => 'Internal Server Error: ' . $e->getMessage()], 500);
    }
}
}
