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

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/SystemSettings.php';
require_once __DIR__ . '/../../classes/Suppliers.php';
require_once __DIR__ . '/../../classes/MraEisCompliance.php';

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

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

    $role = strtolower((string)($_SESSION['role'] ?? ''));
    if (!in_array($role, ['admin', 'warehouse'], true)) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized.']);
        exit;
    }

    $systemSettings = new SystemSettings();
    $compliance = new MraEisCompliance($conn);
    $syncResult = $compliance->syncSuppliersFromEis($systemSettings->eisWarehouseBranchId());

    $suppliers = (new Suppliers($conn))->getSuppliers('active');
    $suppliers = array_map(function ($s) {
        return [
            'supplier_id' => (int)$s['supplier_id'],
            'supplier_name' => $s['supplier_name'],
            'eis_supplier_id' => $s['eis_supplier_id'] ?? null,
        ];
    }, $suppliers);

    echo json_encode([
        'success' => true,
        'message' => "MRA EIS supplier sync complete: {$syncResult['created']} added, {$syncResult['updated']} matched/updated.",
        'suppliers' => $suppliers,
    ]);
} catch (Throwable $e) {
    error_log('MRA EIS supplier sync failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'MRA EIS supplier sync failed: ' . $e->getMessage()]);
}
