Your IP : 216.73.217.78


Current Path : /home/seto/testhive.pm/api/
Upload File :
Current File : /home/seto/testhive.pm/api/redistribute.php

<?php
// Batch redistribution endpoint — called via AJAX from assignments.php
// Auth: same session guard as admin panel

require_once __DIR__ . '/../includes/config.php';
if (session_status() === PHP_SESSION_NONE) session_start();
if (empty($_SESSION[ADMIN_SESSION])) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/distribution.php';

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

$offset    = max(0, (int)($_GET['offset'] ?? 0));
$batchSize = 500;

// On first batch: clear all existing assignments
if ($offset === 0) {
    db()->exec("DELETE FROM page_assignments");
}

// Load active campaigns with links (preload to avoid N+1)
$campaigns = db()->query(
    "SELECT id, target_url, weight, coverage_percent, rotation_days
     FROM campaigns WHERE status='active'"
)->fetchAll();

$allLinks = [];
foreach ($campaigns as $c) {
    $stmt = db()->prepare("SELECT id, weight FROM links WHERE campaign_id=?");
    $stmt->execute([$c['id']]);
    $allLinks[$c['id']] = $stmt->fetchAll();
}

// Total pages
$total = (int)db()->query("SELECT COUNT(*) FROM pages")->fetchColumn();

// Batch of pages
$stmt = db()->prepare("SELECT id FROM pages ORDER BY id LIMIT ? OFFSET ?");
$stmt->execute([$batchSize, $offset]);
$pageRows = $stmt->fetchAll();

$assigned = 0;
$now = time();

if (!empty($campaigns) && !empty($pageRows)) {
    $ins = db()->prepare(
        "INSERT OR IGNORE INTO page_assignments
         (page_id, link_id, campaign_id, assigned_at, expires_at)
         VALUES (?, ?, ?, ?, ?)"
    );

    db()->beginTransaction();
    foreach ($pageRows as $page) {
        $campaign = weighted_random($campaigns);
        if (!$campaign || empty($allLinks[$campaign['id']])) continue;

        // Coverage roll
        if (mt_rand(0, 99) >= (float)$campaign['coverage_percent']) continue;

        $link = weighted_random($allLinks[$campaign['id']]);
        if (!$link) continue;

        $expiresAt = $now + max(1, (int)$campaign['rotation_days']) * 86400;
        $ins->execute([$page['id'], $link['id'], $campaign['id'], $now, $expiresAt]);
        $assigned++;
    }
    db()->commit();
}

$done = $offset + count($pageRows);

echo json_encode([
    'done'     => $done,
    'total'    => $total,
    'assigned' => $assigned,
    'finished' => $done >= $total,
]);