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

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/DocumentImportService.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Login required.']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    $auth = new Auth($conn);
    if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized.']);
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
        exit;
    }

    $importId = (int)($_POST['import_id'] ?? 0);
    if ($importId <= 0) {
        echo json_encode(['success' => false, 'message' => 'Missing import_id.']);
        exit;
    }

    $service = new DocumentImportService($conn);
    $result = $service->processImport($importId);

    echo json_encode($result);
} catch (Throwable $e) {
    error_log('Document import processing failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Unable to process document.']);
}
