View file shop/process_ad.php

File size: 2.91Kb
<?php
/**
 * CMS: LaiCMS (v1.0 Edition 2026)
 * File: shop/process_ad.php
 * Description: Backend-процессор для покупки рекламы с валидацией транзакций.
 */

require_once '../system/db.php';
require_once '../system/functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_SESSION['user_id'])) {
    header("Location: ads.php");
    exit;
}

$user_id = (int)$_SESSION['user_id'];
$title = $mysqli->real_escape_string($_POST['title']);
$link = $mysqli->real_escape_string($_POST['link']);
$description = $mysqli->real_escape_string($_POST['description']);
$type = $_POST['ad_type'] ?? 'start';

// Конфигурация тарифов
$plans = [
    'start'    => ['cost' => 50,  'days' => 1],
    'media'    => ['cost' => 250, 'days' => 7],
    'infinity' => ['cost' => 900, 'days' => 30]
];

if (!isset($plans[$type])) {
    die("Критическая ошибка: Неверный тип тарифа.");
}

$cost = $plans[$type]['cost'];
$days = $plans[$type]['days'];

// 1. Проверка баланса пользователя
$user = $mysqli->query("SELECT balance FROM users WHERE id = $user_id")->fetch_assoc();

if ($user['balance'] < $cost) {
    set_flash("Недостаточно LaiCoins! Пополните баланс.", "danger");
    header("Location: ads.php");
    exit;
}

// 2. Обработка изображения (если тариф поддерживает)
$image_path = null;
if (($type === 'media' || $type === 'infinity') && !empty($_FILES['banner']['name'])) {
    $upload_dir = '../uploads/ads/';
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

    $ext = pathinfo($_FILES['banner']['name'], PATHINFO_EXTENSION);
    $filename = bin2hex(random_bytes(10)) . '.' . $ext;
    $target = $upload_dir . $filename;

    if (move_uploaded_file($_FILES['banner']['tmp_name'], $target)) {
        $image_path = '/uploads/ads/' . $filename;
    }
}

// 3. Начало транзакции
$mysqli->begin_transaction();

try {
    // Списание валюты
    $mysqli->query("UPDATE users SET balance = balance - $cost WHERE id = $user_id");

    // Расчет даты истечения
    $expires_at = date('Y-m-d H:i:s', strtotime("+$days days"));

    // Добавление рекламы в базу
    $stmt = $mysqli->prepare("INSERT INTO ads (user_id, title, link, description, image, type, cost, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("isssssis", $user_id, $title, $link, $description, $image_path, $type, $cost, $expires_at);
    $stmt->execute();

    // Фиксация изменений
    $mysqli->commit();
    
    set_flash("Рекламная кампания успешно запущена! Списано: $cost LC", "success");
} catch (Exception $e) {
    $mysqli->rollback();
    set_flash("Ошибка транзакции: " . $e->getMessage(), "danger");
}

header("Location: /index.php");
exit;