<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Logger.php';
require_once __DIR__ . '/../../classes/MraEisCompliance.php';

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

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized.']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed.']);
    exit();
}

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$userId = (int)$_SESSION['user_id'];

if (
    !$auth->isSalesAssistant($userId) &&
    !$auth->isBranchManager($userId) &&
    !$auth->isWarehousePersonnel($userId) &&
    !$auth->isSuperAdmin($userId)
) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied.']);
    exit();
}

$branchId = $auth->getUserBranch($userId);
if (!$branchId) {
    echo json_encode(['success' => false, 'message' => 'No branch assigned.']);
    exit();
}

$action = trim($_POST['action'] ?? '');
$transactionId = trim($_POST['transaction_id'] ?? '');
$reason = trim($_POST['reason'] ?? '');

try {
    $logger = new Logger($conn, $userId, $_SESSION['username'], $_SESSION['role']);
    $eisCompliance = new MraEisCompliance($conn);

    if ($action === 'flush_pending') {
        // Auto-submit all pending/queued/failed sale outbox entries for this branch
        $pendingStmt = $conn->prepare(
            "SELECT id FROM mra_eis_outbox
             WHERE entity_type = 'sale'
               AND branch_id = :branch_id
               AND status IN ('ready', 'failed')
               AND attempts < 5
             ORDER BY created_at ASC, id ASC
             LIMIT 50"
        );
        $pendingStmt->execute([':branch_id' => $branchId]);
        $pending = $pendingStmt->fetchAll(PDO::FETCH_ASSOC);

        $submitted = 0;
        $failed = 0;
        $online = null;
        if (!$pending) {
            $online = $eisCompliance->probeConnection($branchId, $userId);
        }
        foreach ($pending as $row) {
            try {
                $result = $eisCompliance->submitOutbox((int)$row['id'], $userId);
                !empty($result['success']) ? $submitted++ : $failed++;
            } catch (Throwable $e) {
                $failed++;
            }
        }
        if ($online === null) {
            $status = $eisCompliance->offlineStatusForSale($branchId, $userId);
            $online = ($status['connection_status'] ?? '') === 'online';
        }

        echo json_encode([
            'success' => true,
            'submitted' => $submitted,
            'failed' => $failed,
            'total' => count($pending),
            'connection_status' => $online === null ? null : ($online ? 'online' : 'offline'),
        ]);
        exit();
    }

    if (!$transactionId) {
        echo json_encode(['success' => false, 'message' => 'Transaction ID is required.']);
        exit();
    }

    if ($action === 'recall') {
        // Find the existing outbox entry for this sale
        $outboxStmt = $conn->prepare(
            "SELECT id, status FROM mra_eis_outbox
             WHERE entity_type = 'sale' AND source_key = :txn_id
             LIMIT 1"
        );
        $outboxStmt->execute([':txn_id' => $transactionId]);
        $outboxRow = $outboxStmt->fetch(PDO::FETCH_ASSOC);

        if ($outboxRow) {
            $submitResult = $eisCompliance->submitOutbox((int)$outboxRow['id'], $userId);
        } else {
            // No outbox entry yet — prepare the sale then submit
            $prepResult = $eisCompliance->prepareSale($transactionId, $branchId, $userId, []);
            $outboxId = (int)($prepResult['id'] ?? 0);
            if (!$outboxId) {
                echo json_encode(['success' => false, 'message' => 'Could not prepare sale for EIS submission.']);
                exit();
            }
            $submitResult = $eisCompliance->submitOutbox($outboxId, $userId);
        }

        if (!empty($submitResult['success'])) {
            echo json_encode([
                'success' => true,
                'message' => 'Sale successfully submitted to MRA EIS.',
                'new_status' => 'submitted',
                'validation_url' => $submitResult['validation_url'] ?? null,
            ]);
        } elseif (!empty($submitResult['queued'])) {
            echo json_encode([
                'success' => true,
                'message' => $submitResult['message'] ?? 'Sale queued for EIS submission when connection is restored.',
                'new_status' => 'queued',
                'validation_url' => null,
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => $submitResult['message'] ?? 'EIS submission failed. Check connectivity and try again.',
                'new_status' => 'failed',
            ]);
        }

    } elseif ($action === 'cancel') {
        if ($reason === '') {
            echo json_encode(['success' => false, 'message' => 'A cancellation reason is required.']);
            exit();
        }

        // Queue the void receipt in the outbox then submit immediately
        $outboxResult = $eisCompliance->prepareVoidReceipt($transactionId, $reason, $branchId, $userId);
        $outboxId = (int)($outboxResult['id'] ?? 0);
        if (!$outboxId) {
            echo json_encode(['success' => false, 'message' => 'Failed to prepare EIS cancellation request.']);
            exit();
        }

        $submitResult = $eisCompliance->submitOutbox($outboxId, $userId);

        if (!empty($submitResult['success'])) {
            echo json_encode([
                'success' => true,
                'message' => 'Receipt cancellation successfully submitted to MRA EIS.',
            ]);
        } elseif (!empty($submitResult['queued'])) {
            echo json_encode([
                'success' => true,
                'message' => $submitResult['message'] ?? 'Cancellation request queued for EIS submission.',
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => $submitResult['message'] ?? 'EIS cancellation submission failed.',
            ]);
        }

    } elseif ($action === 'get_invoice_items') {
        // Return original EIS line items from the outbox so the UI can pre-populate the adjustment form
        $lines = $eisCompliance->getOutboxLineItems($transactionId);
        echo json_encode(['success' => true, 'lines' => $lines]);

    } elseif ($action === 'adjust_invoice') {
        // Process a credit/debit note via /sales/process-credit-debit-note
        $adjustedLines = json_decode($_POST['adjusted_lines'] ?? '[]', true);
        if (!is_array($adjustedLines) || empty($adjustedLines)) {
            echo json_encode(['success' => false, 'message' => 'Adjusted line items are required.']);
            exit();
        }
        if ($reason === '') {
            echo json_encode(['success' => false, 'message' => 'A reason for adjustment is required.']);
            exit();
        }
        $result = $eisCompliance->processInvoiceAdjustment($transactionId, $adjustedLines, $reason, $branchId, $userId);
        echo json_encode(array_merge(['success' => true, 'message' => 'Invoice adjustment submitted to MRA EIS.'], $result));

    } else {
        echo json_encode(['success' => false, 'message' => 'Unknown action.']);
    }

} catch (Throwable $e) {
    error_log('EIS sale action failed for transaction ' . $transactionId . ': ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
