View file test.4imas.ru/ajax/admin/save_discount.php

File size: 2.61Kb
<?php

require_once __DIR__ . '/../../config/bootstrap.php';
require_once __DIR__ . '/../../config/auth.php';
require_once __DIR__ . '/../../config/functions.php';

header('Content-Type: application/json');

if (!is_admin()) {
    echo json_encode(['success' => false, 'error' => 'Доступ запрещён']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Неверный метод запроса']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

$csrf_token = $input['csrf'] ?? '';
$discount_id = (int)($input['id'] ?? 0);
$code = trim($input['code'] ?? '');
$percent = (int)($input['percent'] ?? 0);
$expires_at = !empty($input['expires_at']) ? $input['expires_at'] : null;
$active = (int)($input['active'] ?? 1);

if (empty($csrf_token) || !check_csrf($csrf_token)) {
    echo json_encode(['success' => false, 'error' => 'Неверный CSRF токен']);
    exit;
}

if (empty($code)) {
    echo json_encode(['success' => false, 'error' => 'Введите код скидки']);
    exit;
}

if ($percent < 1 || $percent > 100) {
    echo json_encode(['success' => false, 'error' => 'Скидка должна быть от 1% до 100%']);
    exit;
}

try {

    if ($discount_id > 0) {

        $stmt = $pdo->prepare("SELECT id FROM discounts WHERE code = ? AND id != ?");
        $stmt->execute([$code, $discount_id]);
    } else {

        $stmt = $pdo->prepare("SELECT id FROM discounts WHERE code = ?");
        $stmt->execute([$code]);
    }
    
    if ($stmt->fetch()) {
        echo json_encode(['success' => false, 'error' => 'Такой код скидки уже существует']);
        exit;
    }
    
    if ($discount_id > 0) {

        $stmt = $pdo->prepare("UPDATE discounts SET code = ?, percent = ?, expires_at = ?, active = ? WHERE id = ?");
        $success = $stmt->execute([$code, $percent, $expires_at, $active, $discount_id]);
    } else {

        $stmt = $pdo->prepare("INSERT INTO discounts (code, percent, expires_at, active) VALUES (?, ?, ?, ?)");
        $success = $stmt->execute([$code, $percent, $expires_at, $active]);
    }
    
    if ($success) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Ошибка сохранения скидки']);
    }
    
} catch (Exception $e) {
    error_log("Ошибка сохранения скидки: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Внутренняя ошибка сервера: ' . $e->getMessage()]);
}
?>