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

    $branchId = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : null;
    $docTypeHint = (string)($_POST['doc_type_hint'] ?? 'auto');
    $integrationId = !empty($_POST['integration_id']) ? (int)$_POST['integration_id'] : null;

    $service = new DocumentImportService($conn);
    $result = $service->uploadDocument($branchId, (int)$_SESSION['user_id'], $_FILES['document'] ?? [], $docTypeHint, $integrationId);

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