<?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;
    }

    $service = new DocumentImportService($conn);

    if (!empty($_GET['import_id'])) {
        $row = $service->getImport((int)$_GET['import_id']);
        if (!$row) {
            echo json_encode(['success' => false, 'message' => 'Import not found.']);
            exit;
        }
        $row['extracted_data'] = $row['extracted_data'] ? json_decode($row['extracted_data'], true) : null;
        echo json_encode(['success' => true, 'import' => $row]);
        exit;
    }

    $imports = $service->listImports();
    foreach ($imports as &$row) {
        $row['extracted_data'] = $row['extracted_data'] ? json_decode($row['extracted_data'], true) : null;
    }
    unset($row);

    echo json_encode(['success' => true, 'imports' => $imports]);
} catch (Throwable $e) {
    error_log('Document imports list failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Unable to load imports.']);
}
