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

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Logger.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;
    }

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

    $logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'] ?? null, $_SESSION['role'] ?? null);
    $service = new DocumentImportService($conn, $logger);

    switch ($action) {
        case 'confirm':
            $targetModule = (string)($_POST['target_module'] ?? '');
            $branchId = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : ($auth->getUserBranch($_SESSION['user_id']) ?: null);

            $fields = [
                'supplier_id' => $_POST['supplier_id'] ?? null,
                'customer_name' => $_POST['customer_name'] ?? '',
                'customer_contact' => $_POST['customer_contact'] ?? '',
                'document_number' => $_POST['document_number'] ?? '',
                'document_date' => $_POST['document_date'] ?? null,
                'due_date' => $_POST['due_date'] ?? null,
                'subtotal' => $_POST['subtotal'] ?? 0,
                'tax' => $_POST['tax'] ?? 0,
                'total' => $_POST['total'] ?? 0,
                'validity_days' => $_POST['validity_days'] ?? 30,
                'bank_name' => $_POST['bank_name'] ?? '',
                'account_reference' => $_POST['account_reference'] ?? '',
                'notes' => $_POST['notes'] ?? '',
                'receipt_reference' => $_POST['receipt_reference'] ?? '',
                'line_items' => [],
            ];

            $itemNames = $_POST['item_name'] ?? [];
            $itemQtys = $_POST['item_qty'] ?? [];
            $itemPrices = $_POST['item_unit_price'] ?? [];
            if (is_array($itemNames)) {
                foreach ($itemNames as $i => $name) {
                    if (trim((string)$name) === '') {
                        continue;
                    }
                    $fields['line_items'][] = [
                        'item_name' => $name,
                        'qty' => $itemQtys[$i] ?? 0,
                        'unit_price' => $itemPrices[$i] ?? 0,
                    ];
                }
            }

            $result = $service->confirmImport($importId, $targetModule, $fields, (int)$_SESSION['user_id'], $branchId);
            break;

        case 'reject':
            $result = $service->rejectImport($importId);
            break;

        case 'delete':
            $result = $service->deleteImport($importId);
            break;

        default:
            $result = ['success' => false, 'message' => 'Unknown action.'];
    }

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