0, 'code' => '', 'type' => 'percentage', 'value' => 0, 'min_cart_amount' => 0, 'usage_limit' => 0, 'start_date' => '', 'end_date' => '', 'status' => 1]; if ($id) { $stmt = $db->prepare("SELECT * FROM coupons WHERE id = ?"); $stmt->execute([$id]); $coupon = $stmt->fetch(PDO::FETCH_ASSOC); if (!$coupon) { admin_set_flash('error', 'Not found'); header('Location: ' . ADMIN_PATH . 'pages/coupons.php'); exit; } $page_title = 'Edit Coupon'; } if ($_SERVER['REQUEST_METHOD'] == 'POST' && verify_csrf($_POST[CSRF_TOKEN_NAME] ?? '')) { $code = strtoupper(trim($_POST['code'])); $type = $_POST['type']; $value = floatval($_POST['value']); $min_cart_amount = floatval($_POST['min_cart_amount'] ?? 0); $usage_limit = intval($_POST['usage_limit'] ?? 0); $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null; $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null; $status = intval($_POST['status']); try { if ($id) { $stmt = $db->prepare("UPDATE coupons SET code=?, type=?, value=?, min_cart_amount=?, usage_limit=?, start_date=?, end_date=?, status=? WHERE id=?"); $stmt->execute([$code, $type, $value, $min_cart_amount, $usage_limit, $start_date, $end_date, $status, $id]); admin_set_flash('success', 'Coupon updated'); } else { $stmt = $db->prepare("INSERT INTO coupons (code, type, value, min_cart_amount, usage_limit, start_date, end_date, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); $stmt->execute([$code, $type, $value, $min_cart_amount, $usage_limit, $start_date, $end_date, $status]); admin_set_flash('success', 'Coupon added'); } header('Location: ' . ADMIN_PATH . 'pages/coupons.php'); exit; } catch (Exception $e) { $error = 'Failed: ' . $e->getMessage(); } } ?>