<?php
header('Access-Control-Allow-Origin: *');
header(
    'Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS'
);
header(
    'Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization'
);
header('Content-Type: application/json');

include '../../../../config/db.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'));
    if (
        !empty($data->couponCode) &&
        !empty($data->discount) &&
        !empty($data->maxUsage) &&
        !empty($data->activeCouponDate) &&
        !empty($data->minAmount) &&
        !empty($data->couponDescription) &&
        !empty($data->expireDate)
    ) {
        $couponCode = $data->couponCode;
        $discount = $data->discount;
        $isPercentage = $data->isPercentage;
        $maxUsage = $data->maxUsage;
        $minAmount = $data->minAmount;
        $activeCouponDate = $data->activeCouponDate;
        $couponDescription = $data->couponDescription;
        $expireDate = $data->expireDate;

        $dateTime = date('Y-m-d H:i:s');
        $isExistQuery = "SELECT * FROM Coupon WHERE CouponCode = '$couponCode' ";
        if (mysqli_num_rows(mysqli_query($con, $isExistQuery)) == 0) {
            $query = "INSERT INTO `Coupon`(`CouponId`, `CouponCode`, `MinAmount`,`Discount`, `IsPercentage`, `MaxUsage`, `ActiveCouponDate`, `ExpireDate`,`CouponDescription`, `CreatedDate`, `UpdatedDate`,`IsDeleted`) VALUES (0,'$couponCode','$minAmount','$discount','$isPercentage','$maxUsage','$activeCouponDate','$expireDate','$couponDescription','$dateTime','$dateTime',0)";
            if (mysqli_query($con, $query)) {
                if (mysqli_affected_rows($con) == 1) {
                    echo json_encode([
                        'status' => 1,
                        'message' => 'Coupon created successfully.',
                    ]);
                    http_response_code(200);
                } else {
                    echo json_encode([
                        'status' => 0,
                        'message' => 'Could not insert data.',
                    ]);
                    http_response_code(200);
                }
            } else {
                echo json_encode([
                    'status' => 0,
                    'message' => mysqli_error($con),
                ]);
                http_response_code(200);
            }
        } else {
            echo json_encode([
                'status' => -2,
                'message' => 'Data already exists',
            ]);
            http_response_code(200);
        }
    } else {
        echo json_encode([
            'status' => -1,
            'message' => 'Required fields are missing',
        ]);
        http_response_code(200);
    }
} else {
    echo json_encode([
        'status' => -1,
    ]);
    die();
}
