<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../../classes/Database.php';
require_once '../../includes/auth.php';
require_once '../../classes/MraEisOnboarding.php';
require_once '../../classes/SystemSettings.php';

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

if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit;
}

$eis = new MraEisOnboarding($conn);
$systemSettings = new SystemSettings(null, $conn);
$systemEnvironment = $systemSettings->eisEnvironment();
$eisEnabled = $systemSettings->eisEnabled();
$eisOffline = $systemSettings->eisOfflineMode();
$branches = $eis->branches();
$message = null;
$messageType = 'success';
$terminal = null;
$terminalId = trim((string)($_GET['id'] ?? $_POST['id'] ?? ''));

if (empty($_SESSION['mra_eis_activation_csrf'])) {
    $_SESSION['mra_eis_activation_csrf'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['mra_eis_activation_csrf'];

if ($terminalId !== '') {
    if (!ctype_digit($terminalId) || (int)$terminalId <= 0) {
        $message = 'The selected terminal is invalid.';
        $messageType = 'danger';
        $terminalId = '';
    } else {
        $terminal = $eis->find((int)$terminalId);
        if (!$terminal) {
            $message = 'The selected terminal was not found.';
            $messageType = 'danger';
            $terminalId = '';
        }
    }
}

$recordEnvironment = $terminal
    ? strtolower(trim((string)$terminal['environment']))
    : $systemEnvironment;
$recordEnvironment = $recordEnvironment === 'production' ? 'production' : 'sandbox';
$recordApiBaseUrl = $eis->defaultApiBaseUrl($recordEnvironment);

$form = array_merge([
    'id' => '',
    'terminal_label' => '',
    'branch_id' => '',
    'terminal_activation_code' => '',
    'taxpayer_tin' => '',
    'site_id' => '',
    'global_config_version' => 1,
    'taxpayer_config_version' => 1,
    'terminal_config_version' => 1,
    'environment' => $recordEnvironment,
    'api_base_url' => $recordApiBaseUrl,
    'os_name' => 'Windows 11',
    'os_version' => 'Windows 11',
    'os_build' => '',
    'mac_address' => '',
    'pos_product_id' => $recordEnvironment === 'production' ? '' : $eis->generateProductId(),
    'pos_product_version' => '1.0.0',
], $terminal ?: [], $_POST ?: []);
$form['environment'] = $recordEnvironment;
$form['api_base_url'] = $recordApiBaseUrl;

$isCredentialed = $terminal && (
    !empty($terminal['mra_terminal_id'])
    || !empty($terminal['secret_key'])
    || in_array((string)($terminal['status'] ?? ''), ['activation_pending', 'activated'], true)
);
$isProduction = $recordEnvironment === 'production';
$environmentMatchesSettings = $recordEnvironment === $systemEnvironment;
$activationBlocked = !$environmentMatchesSettings || !$eisEnabled || $eisOffline || $isCredentialed;

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $postedCsrf = (string)($_POST['csrf_token'] ?? '');
        if ($postedCsrf === '' || !hash_equals($csrfToken, $postedCsrf)) {
            throw new RuntimeException('The form session expired. Refresh the page and try again.');
        }

        $trustedInput = $_POST;
        $trustedInput['environment'] = $recordEnvironment;
        $trustedInput['api_base_url'] = $recordApiBaseUrl;
        $vendorAccessKey = trim((string)($_POST['vendor_access_key'] ?? ''));

        if (isset($_POST['generate_product_id'])) {
            if ($isProduction) {
                throw new RuntimeException('Automatic development product IDs are disabled for Production. Enter the approved POS Product ID assigned to this installation.');
            }
            $form['pos_product_id'] = $eis->generateProductId();
            $message = 'A development POS product ID has been generated.';
        } elseif (isset($_POST['save_terminal']) || isset($_POST['activate_terminal'])) {
            if ($isCredentialed) {
                throw new RuntimeException('This terminal already has MRA credentials and is locked. Continue with Confirmation instead of editing or reactivating it.');
            }

            $macAddress = trim((string)($trustedInput['mac_address'] ?? ''));
            if (!preg_match('/^(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$/', $macAddress)) {
                throw new InvalidArgumentException('Enter a valid MAC address, for example AA-BB-CC-DD-EE-FF.');
            }
            $trustedInput['mac_address'] = strtoupper(str_replace(':', '-', $macAddress));

            if ($isProduction) {
                foreach (['taxpayer_tin' => 'Taxpayer TIN', 'site_id' => 'EIS Site ID', 'pos_product_id' => 'approved POS Product ID'] as $field => $label) {
                    if (trim((string)($trustedInput[$field] ?? '')) === '') {
                        throw new InvalidArgumentException($label . ' is required for a Production terminal.');
                    }
                }
                if (parse_url($recordApiBaseUrl, PHP_URL_SCHEME) !== 'https') {
                    throw new RuntimeException('Production activation is blocked because the configured MRA API URL is not HTTPS. Correct it in Settings first.');
                }
            }

            if (isset($_POST['activate_terminal'])) {
                if (!$eisEnabled) {
                    throw new RuntimeException('MRA EIS is disabled in system Settings. Enable it before terminal activation.');
                }
                if ($eisOffline) {
                    throw new RuntimeException('EIS Offline mode is enabled. Disable Offline mode before terminal activation.');
                }
                if (!$environmentMatchesSettings) {
                    throw new RuntimeException('This terminal uses ' . ucfirst($recordEnvironment) . ' but system Settings uses ' . ucfirst($systemEnvironment) . '. Switch Settings to the matching environment before activation.');
                }
                if ($isProduction && empty($_POST['confirm_production_activation'])) {
                    throw new RuntimeException('Confirm that the live Production activation details were checked before sending the request.');
                }
            }

            $terminalId = $eis->saveDraft($trustedInput, $_SESSION['user_id'] ?? null);
            $terminal = $eis->find($terminalId);
            $form = array_merge($form, $terminal ?: []);
            $message = 'Terminal onboarding details saved.';

            if (isset($_POST['activate_terminal'])) {
                $result = $eis->activate($terminalId, $vendorAccessKey);
                $terminal = $eis->find($terminalId);
                $form = array_merge($form, $terminal ?: []);
                $message = 'Activation request accepted. MRA terminal ID: ' . $result['terminal_id'];
            }
        } elseif (isset($_POST['delete_terminal'])) {
            if ($isCredentialed) {
                throw new RuntimeException('A terminal with issued MRA credentials cannot be deleted from this page.');
            }
            $eis->delete($terminalId);
            header('Location: mra_eis_onboarding.php');
            exit;
        }
    }
} catch (Exception $e) {
    $message = $e->getMessage();
    $messageType = 'danger';
}

$isCredentialed = $terminal && (
    !empty($terminal['mra_terminal_id'])
    || !empty($terminal['secret_key'])
    || in_array((string)($terminal['status'] ?? ''), ['activation_pending', 'activated'], true)
);
$recordEnvironment = strtolower(trim((string)($form['environment'] ?? $recordEnvironment))) === 'production' ? 'production' : 'sandbox';
$isProduction = $recordEnvironment === 'production';
$environmentMatchesSettings = $recordEnvironment === $systemEnvironment;
$activationBlocked = !$environmentMatchesSettings || !$eisEnabled || $eisOffline || $isCredentialed;

$maskedActivationCode = trim((string)$form['terminal_activation_code']);
if ($maskedActivationCode !== '') {
    $visibleSuffix = substr($maskedActivationCode, -4);
    $maskedActivationCode = str_repeat('•', max(8, strlen($maskedActivationCode) - 4)) . $visibleSuffix;
}

$preview = [
    'terminalActivationCode' => $maskedActivationCode,
    'environment' => [
        'platform' => [
            'osName' => $form['os_name'],
            'osVersion' => $form['os_version'],
            'osBuild' => $form['os_build'],
            'macAddress' => $form['mac_address'],
        ],
        'pos' => [
            'productID' => $form['pos_product_id'],
            'productVersion' => $form['pos_product_version'],
        ],
    ],
];

require_once '../../includes/header.php';
?>

<style>
    body { background: #f4f6f8; }
    .eis-shell { max-width: 1280px; margin: 30px auto; padding: 0 15px; }
    .eis-topbar { display: flex; justify-content: space-between; gap: 16px; align-items: center; margin-bottom: 20px; }
    .eis-title { font-weight: 800; color: #172033; }
    .eis-card { border: 0; border-radius: 8px; box-shadow: 0 2px 12px rgba(15, 23, 42, 0.08); }
    .eis-card .card-header { background: #1f2937; color: #fff; border-radius: 8px 8px 0 0; }
    .request-preview { white-space: pre-wrap; min-height: 360px; font-size: 0.875rem; }
    .small-help { color: #667085; font-size: 0.875rem; }
    .environment-banner { border-left: 5px solid #2563eb; }
    .environment-banner.production { border-left-color: #dc2626; background: #fff7ed; }
    .terminal-fieldset { min-width: 0; margin: 0; padding: 0; border: 0; }
    @media (max-width: 768px) {
        .eis-topbar { display: block; }
        .eis-topbar .btn { width: 100%; margin-top: 10px; }
    }
</style>

<div class="eis-shell">
    <?php $eisNavCurrent = 'onboarding'; require __DIR__ . '/../../includes/eis_admin_nav.php'; ?>

    <div class="eis-topbar">
        <div>
            <h2 class="eis-title mb-1"><i class="fas fa-plug"></i> Terminal Activation</h2>
            <p class="text-muted mb-0">Prepare and submit the MRA EIS <code>/onboarding/activate-terminal</code> request using the centrally configured environment.</p>
        </div>
        <div class="d-flex flex-wrap" style="gap: 8px;">
            <a href="mra_eis_onboarding.php" class="btn btn-outline-primary">
                <i class="fas fa-list"></i> Onboarding
            </a>
            <?php if (!empty($form['id'])): ?>
                <a href="mra_eis_terminal_confirmation.php?id=<?php echo urlencode($form['id']); ?>" class="btn btn-outline-success">
                    <i class="fas fa-check-circle"></i> Confirmation
                </a>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="alert environment-banner <?php echo $isProduction ? 'production' : ''; ?>">
        <div class="d-flex flex-wrap justify-content-between align-items-center" style="gap:10px;">
            <div>
                <strong><?php echo $isProduction ? 'LIVE PRODUCTION' : 'Sandbox / Testing'; ?></strong>
                <div class="small mt-1">API destination: <code><?php echo htmlspecialchars($recordApiBaseUrl); ?></code></div>
            </div>
            <span class="badge bg-<?php echo $isProduction ? 'danger' : 'primary'; ?>"><?php echo strtoupper($recordEnvironment); ?></span>
        </div>
    </div>

    <?php if (!$environmentMatchesSettings): ?>
        <div class="alert alert-warning">
            This terminal belongs to <strong><?php echo htmlspecialchars(ucfirst($recordEnvironment)); ?></strong>, while system Settings currently uses
            <strong><?php echo htmlspecialchars(ucfirst($systemEnvironment)); ?></strong>. It may be saved, but activation is blocked until the environments match.
        </div>
    <?php endif; ?>

    <?php if (!$eisEnabled || $eisOffline): ?>
        <div class="alert alert-danger">
            Activation is unavailable because <?php echo !$eisEnabled ? 'MRA EIS is disabled' : 'EIS Offline mode is enabled'; ?> in system Settings.
        </div>
    <?php endif; ?>

    <?php if ($isCredentialed): ?>
        <div class="alert alert-info">
            <strong>Credentialed terminal locked.</strong> Activation-critical fields cannot be edited, reactivated, or deleted.
            <?php if (($terminal['status'] ?? '') === 'activation_pending'): ?>Continue to Terminal Confirmation to complete onboarding.<?php endif; ?>
        </div>
    <?php endif; ?>

    <form method="POST">
        <input type="hidden" name="id" value="<?php echo htmlspecialchars($form['id'] ?? ''); ?>">
        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrfToken); ?>">
        <div class="row">
            <div class="col-lg-7 mb-4">
                <div class="card eis-card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-cash-register"></i> Terminal Details</h5>
                    </div>
                    <div class="card-body">
                        <fieldset class="terminal-fieldset" <?php echo $isCredentialed ? 'disabled' : ''; ?>>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="terminal_label" class="form-label">Terminal Label</label>
                                <input type="text" class="form-control" id="terminal_label" name="terminal_label" required value="<?php echo htmlspecialchars($form['terminal_label']); ?>" placeholder="Till-01">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="branch_id" class="form-label">Branch</label>
                                <select class="form-control" id="branch_id" name="branch_id" required>
                                    <option value="">Select branch</option>
                                    <?php foreach ($branches as $branch): ?>
                                        <option value="<?php echo htmlspecialchars($branch['branch_id']); ?>" <?php echo (string)$form['branch_id'] === (string)$branch['branch_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($branch['branch_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="terminal_activation_code" class="form-label">Terminal Activation Code</label>
                                <input type="password" class="form-control" id="terminal_activation_code" name="terminal_activation_code" required maxlength="50" autocomplete="new-password" value="<?php echo htmlspecialchars($form['terminal_activation_code']); ?>" placeholder="Activation code issued by MRA">
                                <div class="small-help mt-1">The TAC is issued from the MRA EIS Portal after terminal acquisition.</div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="taxpayer_tin" class="form-label">Taxpayer TIN</label>
                                <input type="text" class="form-control" id="taxpayer_tin" name="taxpayer_tin" value="<?php echo htmlspecialchars($form['taxpayer_tin']); ?>" <?php echo $isProduction ? 'required' : ''; ?>>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="site_id" class="form-label">EIS Site ID</label>
                                <input type="text" class="form-control" id="site_id" name="site_id" maxlength="80" value="<?php echo htmlspecialchars($form['site_id'] ?? ''); ?>" <?php echo $isProduction ? 'required' : ''; ?>>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="global_config_version" class="form-label">Global Config Version</label>
                                <input type="number" class="form-control" id="global_config_version" name="global_config_version" min="1" value="<?php echo htmlspecialchars((string)($form['global_config_version'] ?? 1)); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="taxpayer_config_version" class="form-label">Taxpayer Config Version</label>
                                <input type="number" class="form-control" id="taxpayer_config_version" name="taxpayer_config_version" min="1" value="<?php echo htmlspecialchars((string)($form['taxpayer_config_version'] ?? 1)); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="terminal_config_version" class="form-label">Terminal Config Version</label>
                                <input type="number" class="form-control" id="terminal_config_version" name="terminal_config_version" min="1" value="<?php echo htmlspecialchars((string)($form['terminal_config_version'] ?? 1)); ?>">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="environment" class="form-label">Environment</label>
                                <input type="text" class="form-control" id="environment" value="<?php echo htmlspecialchars(ucfirst($recordEnvironment)); ?>" readonly>
                                <input type="hidden" name="environment" value="<?php echo htmlspecialchars($recordEnvironment); ?>">
                                <div class="small-help mt-1">Controlled by EIS Environment in system Settings for new terminals.</div>
                            </div>
                            <div class="col-md-8 mb-3">
                                <label for="api_base_url" class="form-label">API Base URL</label>
                                <input type="url" class="form-control" id="api_base_url" name="api_base_url" value="<?php echo htmlspecialchars($recordApiBaseUrl); ?>" readonly>
                                <div class="small-help mt-1">The browser cannot override the configured MRA endpoint.</div>
                            </div>
                        </div>

                        <hr>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="os_name" class="form-label">OS Name</label>
                                <input type="text" class="form-control" id="os_name" name="os_name" required maxlength="50" value="<?php echo htmlspecialchars($form['os_name']); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="os_version" class="form-label">OS Version</label>
                                <input type="text" class="form-control" id="os_version" name="os_version" required maxlength="50" value="<?php echo htmlspecialchars($form['os_version']); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="os_build" class="form-label">OS Build</label>
                                <input type="text" class="form-control" id="os_build" name="os_build" maxlength="50" value="<?php echo htmlspecialchars($form['os_build']); ?>">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="mac_address" class="form-label">MAC Address</label>
                            <input type="text" class="form-control" id="mac_address" name="mac_address" required maxlength="17" pattern="(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}" value="<?php echo htmlspecialchars($form['mac_address']); ?>" placeholder="AA-BB-CC-DD-EE-FF">
                        </div>

                        <div class="row">
                            <div class="col-md-8 mb-3">
                                <label for="pos_product_id" class="form-label">POS Product ID</label>
                                <input type="text" class="form-control" id="pos_product_id" name="pos_product_id" maxlength="50" value="<?php echo htmlspecialchars($form['pos_product_id']); ?>" <?php echo $isProduction ? 'required' : ''; ?>>
                                <?php if ($isProduction): ?><div class="small-help mt-1">Use the approved Production POS Product ID for this installation.</div><?php endif; ?>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="pos_product_version" class="form-label">POS Version</label>
                                <input type="text" class="form-control" id="pos_product_version" name="pos_product_version" required maxlength="50" value="<?php echo htmlspecialchars($form['pos_product_version']); ?>">
                            </div>
                        </div>

                        <?php if ($isProduction && !$isCredentialed): ?>
                            <div class="mb-3">
                                <label for="vendor_access_key" class="form-label">MRA Vendor Access Key</label>
                                <input type="password" class="form-control" id="vendor_access_key" name="vendor_access_key" maxlength="255" autocomplete="off" placeholder="Access key issued by MRA to the certified POS vendor">
                                <div class="small-help mt-1">
                                    Required only for Production activation and sent as <code>x-access-key</code>. It is used for this request only and is not stored.
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($isProduction && !$isCredentialed): ?>
                            <div class="form-check border border-danger rounded p-3 ps-5 mb-3 bg-light">
                                <input class="form-check-input" type="checkbox" value="1" id="confirm_production_activation" name="confirm_production_activation">
                                <label class="form-check-label" for="confirm_production_activation">
                                    I verified the live TAC, TIN, Site ID, branch, MAC address and approved POS Product ID. I understand activation sends this request to the live MRA Production service.
                                </label>
                            </div>
                        <?php endif; ?>

                        <div class="d-flex flex-wrap" style="gap: 8px;">
                            <button type="submit" name="save_terminal" value="1" class="btn btn-primary">
                                <i class="fas fa-save"></i> Save
                            </button>
                            <button type="submit" name="activate_terminal" value="1" class="btn <?php echo $isProduction ? 'btn-danger' : 'btn-success'; ?>" <?php echo $activationBlocked ? 'disabled' : ''; ?> onclick="return confirm('<?php echo $isProduction ? 'Send this activation request to the LIVE MRA Production service?' : 'Send this activation request to the MRA Sandbox service?'; ?>');">
                                <i class="fas fa-paper-plane"></i> <?php echo $isProduction ? 'Save & Activate LIVE' : 'Save & Activate Sandbox'; ?>
                            </button>
                            <?php if (!$isProduction): ?>
                                <button type="submit" name="generate_product_id" value="1" class="btn btn-outline-secondary">
                                    <i class="fas fa-sync-alt"></i> Generate Development Product ID
                                </button>
                            <?php endif; ?>
                            <?php if (!empty($form['id']) && !$isCredentialed): ?>
                                <button type="submit" name="delete_terminal" value="1" class="btn btn-outline-danger" onclick="return confirm('Delete this onboarding terminal?');">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            <?php endif; ?>
                        </div>
                        </fieldset>
                    </div>
                </div>
            </div>

            <div class="col-lg-5 mb-4">
                <div class="card eis-card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-code"></i> Request Preview</h5>
                    </div>
                    <div class="card-body">
                        <pre class="bg-light border rounded p-3 request-preview"><?php echo htmlspecialchars(json_encode($preview, JSON_PRETTY_PRINT)); ?></pre>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<?php include '../../includes/footer.php'; ?>
