<?php

namespace EasyRestaurantManager\Http\Controllers;

use EasyRestaurantManager\Http\Requests\StoreCouponRequest;
use EasyRestaurantManager\Resources\CouponResource;
use WP_REST_Request;

class CouponController
{
   

    public static function getCoupon()
    {
        $res = CouponResource::getCoupon();

        if (!$res) {
            return rest_ensure_response([
                'message' => 'Failed to create coupon'
            ], 500);
        }
        return rest_ensure_response([
            'message' => 'coupon get successfully',
            'coupons' => $res
        ]);
    }

    public static function postCoupon(WP_REST_Request $request){
     
        $data = $request->get_param('data');
        $id = $data['id'];

        $validatedRequest = new StoreCouponRequest($request);
        if ($validatedRequest->fails()) {
            return rest_ensure_response([
                'message' => 'Validation failed',
                'errors'  => $validatedRequest->errors()
            ], 400);
        }
    
        if ($id) {
            $res = CouponResource::updateCoupon($data);
            if ($res === false) {
                return rest_ensure_response([
                    'message' => 'Failed to update coupon'
                ], 500);
            }
            return rest_ensure_response([
                'message' => 'Coupon updated successfully',
                'coupon_data' => $res
            ]);
        }
    
        $res = CouponResource::store($validatedRequest->validated());
        if (!$res) {
            return rest_ensure_response([
                'message' => 'Failed to create coupon'
            ], 500);
        }
        return rest_ensure_response([
            'message' => 'Coupon created successfully',
            'coupon_data' => $res
        ]);
    }

    public static function deleteCoupon(WP_REST_Request $request)
    {
        $id = $request->get_param('id');
        if (!$id) {
            return rest_ensure_response([
                'message' => 'Coupon id is required'
            ], 400);
        }
        $res = CouponResource::deleteCoupon($id);
        
        if (!$res) {
            return rest_ensure_response([
                'message' => 'Failed to delete coupon'
            ], 500);
        }
        return rest_ensure_response([
            'message' => 'coupon deleted successfully',
            'category_data' => $res
        ]);
    }
}
