<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/subscriber_contracts_bulk_export_lib.php';

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

try {
    require_login('index.php?login=1');
    if (function_exists('require_perm')) require_perm('can_view_subscribers');
    if (function_exists('ensure_db')) ensure_db(true);
    $conn = $GLOBALS['conn'] ?? null;
    if (!($conn instanceof mysqli)) throw new RuntimeException('تعذر الاتصال بقاعدة البيانات.');
    sc_ensure_schema($conn);
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') throw new RuntimeException('طريقة الطلب غير مدعومة.');
    if (!ua_csrf_verify()) throw new RuntimeException('انتهت صلاحية الطلب. أعد فتح الصفحة وحاول مجدداً.');

    $action = (string)($_POST['action'] ?? '');
    if ($action === 'start') {
        $job = sc_bulk_export_start($conn, $_POST);
        echo json_encode(sc_bulk_export_public_state($job), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
    if ($action === 'process') {
        $token = (string)($_POST['token'] ?? '');
        $job = [];
        for ($step = 0; $step < 3; $step++) {
            $job = sc_bulk_export_process_next($conn, $token);
            if (($job['status'] ?? '') !== 'running') break;
        }
        echo json_encode(sc_bulk_export_public_state($job), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
    throw new RuntimeException('عملية التصدير المطلوبة غير معروفة.');
} catch (Throwable $error) {
    http_response_code(422);
    echo json_encode([
        'ok' => false,
        'status' => 'failed',
        'message' => $error->getMessage(),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
