<?php
declare(strict_types=1);

require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../subscribers_lib.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');

function sisb_reply(array $payload, int $status = 200): void
{
    http_response_code($status);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

require_login('index.php?login=1');
if (function_exists('require_perm')) require_perm('can_manage_subscribers');

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    sisb_reply(['ok' => false, 'message' => 'طريقة الطلب غير مسموحة.'], 405);
}
if (function_exists('ua_csrf_verify') && !ua_csrf_verify()) {
    sisb_reply(['ok' => false, 'message' => 'انتهت صلاحية الطلب. أعد تحميل الصفحة ثم حاول مجدداً.'], 419);
}

$rawIds = $_POST['ids'] ?? [];
if (is_string($rawIds)) $rawIds = preg_split('/[^0-9]+/', $rawIds, -1, PREG_SPLIT_NO_EMPTY);
if (!is_array($rawIds)) $rawIds = [];
$ids = [];
foreach ($rawIds as $rawId) {
    $id = (int)$rawId;
    if ($id > 0) $ids[$id] = $id;
    if (count($ids) >= 12) break;
}
$ids = array_values($ids);
if (!$ids) sisb_reply(['ok' => false, 'message' => 'لا توجد حسابات صالحة في هذه الدفعة.'], 422);

$conn = ensure_db(true);
subs_ensure_pppoe_cols($conn);
$results = [];
$succeeded = 0;
$failed = 0;
foreach ($ids as $subscriberId) {
    try {
        $result = subs_stage_policy_account($conn, $subscriberId);
    } catch (Throwable $error) {
        $result = ['ok' => false, 'message' => $error->getMessage()];
    }
    $ok = !empty($result['ok']);
    if ($ok) $succeeded++; else $failed++;
    $results[] = [
        'id' => $subscriberId,
        'ok' => $ok,
        'message' => trim((string)($result['message'] ?? ($ok ? 'تم التجهيز' : 'تعذر التجهيز'))),
        'username' => trim((string)($result['username'] ?? '')),
        'profile' => trim((string)($result['profile'] ?? '')),
    ];
}

sisb_reply([
    'ok' => true,
    'processed' => count($ids),
    'succeeded' => $succeeded,
    'failed' => $failed,
    'results' => $results,
]);

