<?php
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/MraEisOnboarding.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$returnBase = '../../views/admin/mra_eis_site_products.php';

try {
    $database = new Database();
    $conn = $database->getConnection();
    $auth = new Auth($conn);
    $auth->requireLogin();

    if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
        throw new RuntimeException('Only administrators can fetch live EIS data.');
    }
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new RuntimeException('Use the EIS data-source form to fetch live data.');
    }

    $source = trim((string)($_POST['data_source'] ?? ''));
    if ($source === 'warehouse') {
        header('Location: ' . $returnBase . '?warehouse_stock=1&live=1');
        exit;
    }

    if (!preg_match('/^site:(\d+)$/', $source, $matches)) {
        throw new RuntimeException('Select either EIS Warehouse or an EIS site terminal.');
    }

    $eis = new MraEisOnboarding($conn);
    $terminal = $eis->find((int)$matches[1]);
    if (!$terminal || $terminal['status'] !== 'activated') {
        throw new RuntimeException('The selected site terminal is not activated.');
    }

    $tin = trim((string)($terminal['taxpayer_tin'] ?? ''));
    $siteId = trim((string)($terminal['site_id'] ?? ''));
    $result = $eis->syncSiteProducts($terminal['id'], $tin, $siteId);
    $_SESSION['eis_flash'] = [
        'type' => 'success',
        'message' => 'Fetched and saved ' . (int)$result['saved'] . ' live product(s) from ' . $terminal['terminal_label'] . '.',
    ];

    header('Location: ' . $returnBase . '?warehouse_stock=1&source=site&terminal_id=' . urlencode((string)$terminal['id']) . '&site_id=' . urlencode($siteId));
    exit;
} catch (Throwable $e) {
    $_SESSION['eis_flash'] = ['type' => 'danger', 'message' => $e->getMessage()];
    header('Location: ' . $returnBase . '?warehouse_stock=1');
    exit;
}
