<?php
/**
 * View: Demo Oracle — liste et formulaire des bases de demonstration.
 *
 * Variables : $action, $record, $databases, $hasRoom, $maxDbs, $errors,
 *             $post, $csrfToken, $pageTitle
 */
include WEBROOT_PATH . '/includes/header.php';

/** Valeur a afficher : la saisie refusee prime sur l'enregistrement. */
$val = function (string $key, $default = '') use ($record, $post, $action) {
    if (!empty($post) && ($post['action'] ?? '') === 'save') {
        return $post[$key] ?? $default;
    }
    return $record[$key] ?? $default;
};
?>

<div class="page-header" style="display:flex;align-items:center;flex-wrap:wrap;gap:.75rem">
    <h1 style="margin:0"><?= t('demo_oracle.db_manage') ?></h1>
    <a href="<?= demo_oracle_url('home') ?>" class="btn btn-sm btn-secondary" style="margin-left:auto">
        &larr; <?= t('demo_oracle.back_home') ?>
    </a>
</div>

<?php if (!empty($errors)): ?>
<div class="alert alert-error">
    <ul style="margin:0;padding-left:1.2rem">
        <?php foreach ($errors as $e): ?><li><?= htmlspecialchars($e) ?></li><?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

<?php if ($action === 'list'): ?>

<div class="card">
    <h2 style="margin:0 0 .5rem;font-size:1rem;display:flex;align-items:center;gap:.5rem">
        <?= t('demo_oracle.databases') ?>
        <span class="badge"><?= count($databases) ?> / <?= (int)$maxDbs ?></span>
    </h2>

    <?php if (empty($databases)): ?>
        <p><?= t('demo_oracle.no_db_manager') ?></p>
    <?php else: ?>
    <table class="data-table">
        <thead>
            <tr>
                <th><?= t('demo_oracle.db_name') ?></th>
                <th><?= t('demo_oracle.db_host') ?></th>
                <th><?= t('demo_oracle.db_service') ?></th>
                <th><?= t('demo_oracle.db_user') ?></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($databases as $d): ?>
            <tr>
                <td><strong><?= htmlspecialchars((string)$d['name']) ?></strong></td>
                <td><?= htmlspecialchars((string)$d['host']) ?>:<?= (int)$d['port'] ?></td>
                <td><?= htmlspecialchars((string)$d['service_name']) ?></td>
                <td><?= htmlspecialchars((string)($d['username'] ?? '')) ?></td>
                <td style="text-align:right;white-space:nowrap">
                    <a href="<?= demo_oracle_url('db.edit', ['id' => (int)$d['id']]) ?>"
                       class="btn btn-secondary btn-sm"><?= t('demo_oracle.edit') ?></a>
                    <form method="post" action="<?= demo_oracle_url('db.list') ?>" style="display:inline"
                          onsubmit="return confirm('<?= htmlspecialchars(t('demo_oracle.db_delete_confirm')) ?>')">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="db_id" value="<?= (int)$d['id'] ?>">
                        <button type="submit" class="btn btn-danger btn-sm"><?= t('demo_oracle.delete') ?></button>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <p style="margin:1rem 0 0;display:flex;align-items:center;gap:.6rem;flex-wrap:wrap">
        <?php if ($hasRoom): ?>
        <a href="<?= demo_oracle_url('db.new') ?>" class="btn btn-primary btn-sm"><?= t('demo_oracle.db_add') ?></a>
        <?php else: ?>
        <button type="button" class="btn btn-primary btn-sm"<?= DemoOracleDemo::disabled() ?>>
            <?= t('demo_oracle.db_add') ?>
        </button>
        <?= DemoOracleDemo::badge(t('demo_oracle.db_limit_hint', ['max' => (string)$maxDbs])) ?>
        <?php endif; ?>
    </p>
</div>

<?php else: ?>

<form method="post" action="<?= demo_oracle_url('db.list') ?>" class="card"
      enctype="multipart/form-data">
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
    <input type="hidden" name="action" value="save">
    <?php if ($action === 'edit'): ?>
    <input type="hidden" name="id" value="<?= (int)($record['id'] ?? 0) ?>">
    <?php endif; ?>

    <h2 style="margin:0 0 .75rem;font-size:1rem">
        <?= $action === 'edit' ? t('demo_oracle.db_edit') : t('demo_oracle.db_new') ?>
    </h2>

    <div class="form-row">
        <div class="form-group">
            <label for="name"><?= t('demo_oracle.db_name') ?></label>
            <input type="text" id="name" name="name" required maxlength="60"
                   value="<?= htmlspecialchars((string)$val('name')) ?>">
        </div>
        <div class="form-group">
            <label for="description"><?= t('demo_oracle.db_description') ?></label>
            <input type="text" id="description" name="description" maxlength="200"
                   value="<?= htmlspecialchars((string)$val('description')) ?>">
        </div>
    </div>

<?php
$connType  = (string)$val('conn_type', 'standard');
$isCloud   = $connType === 'cloud';
$hasWallet = ($record['wallet_path'] ?? '') !== '' && is_dir($record['wallet_path']);
$aliases   = $hasWallet ? DemoOracleWallet::aliases($record['wallet_path']) : [];
?>

    <div class="form-group">
        <label><?= t('demo_oracle.conn_type') ?></label>
        <div style="display:flex;gap:1.25rem;flex-wrap:wrap">
            <label style="display:flex;align-items:center;gap:.35rem;cursor:pointer">
                <input type="radio" name="conn_type" value="standard" id="conn-standard"
                       <?= $isCloud ? '' : 'checked' ?>>
                <?= t('demo_oracle.conn_standard') ?>
            </label>
            <label style="display:flex;align-items:center;gap:.35rem;cursor:pointer">
                <input type="radio" name="conn_type" value="cloud" id="conn-cloud"
                       <?= $isCloud ? 'checked' : '' ?>>
                <?= t('demo_oracle.conn_cloud') ?>
            </label>
        </div>
    </div>

    <?php /* Connexion directe : hote, port, service. */ ?>
    <div id="section-standard" class="form-row"<?= $isCloud ? ' style="display:none"' : '' ?>>
        <div class="form-group">
            <label for="host"><?= t('demo_oracle.db_host') ?></label>
            <input type="text" id="host" name="host"
                   value="<?= htmlspecialchars((string)$val('host')) ?>">
        </div>
        <div class="form-group">
            <label for="port"><?= t('demo_oracle.db_port') ?></label>
            <input type="number" id="port" name="port" min="1" max="65535"
                   value="<?= htmlspecialchars((string)$val('port', 1521)) ?>">
        </div>
        <div class="form-group">
            <label for="service_name"><?= t('demo_oracle.db_service') ?></label>
            <input type="text" id="service_name" name="service_name"
                   value="<?= htmlspecialchars((string)$val('service_name')) ?>">
        </div>
    </div>

    <?php /* Connexion Oracle Cloud : portefeuille et alias TNS.
             Les champs ne portent pas `required` : le navigateur refuserait
             l'envoi sur une section masquee. La verification est cote
             serveur, ou elle depend du type reellement choisi. */ ?>
    <div id="section-cloud"<?= $isCloud ? '' : ' style="display:none"' ?>>
        <div class="form-row">
            <div class="form-group">
                <label for="wallet"><?= t('demo_oracle.wallet') ?><?= $hasWallet ? '' : ' *' ?></label>
                <input type="file" id="wallet" name="wallet" accept=".zip">
                <p style="margin:.3rem 0 0;font-size:.82rem;color:var(--color-text-muted)">
                    <?php if ($hasWallet): ?>
                    &#9989; <?= t('demo_oracle.wallet_current') ?> &mdash; <?= t('demo_oracle.wallet_replace') ?>
                    <?php else: ?>
                    <?= t('demo_oracle.wallet_hint') ?>
                    <?php endif; ?>
                </p>
            </div>
            <div class="form-group">
                <label for="tns_alias"><?= t('demo_oracle.tns_alias') ?></label>
                <?php if ($aliases): ?>
                <?php /* Les alias d'une base Autonomous sont prefixes du nom de
                         la base : les proposer evite une faute de frappe que
                         seul un ORA-12154 revelerait. */ ?>
                <input type="text" id="tns_alias" name="tns_alias" list="tns-aliases"
                       value="<?= htmlspecialchars((string)$val('tns_alias')) ?>">
                <datalist id="tns-aliases">
                    <?php foreach ($aliases as $a): ?>
                    <option value="<?= htmlspecialchars($a) ?>"></option>
                    <?php endforeach; ?>
                </datalist>
                <?php else: ?>
                <input type="text" id="tns_alias" name="tns_alias" placeholder="madb_high"
                       value="<?= htmlspecialchars((string)$val('tns_alias')) ?>">
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="form-row">
        <div class="form-group">
            <label for="username"><?= t('demo_oracle.db_user') ?></label>
            <input type="text" id="username" name="username" autocomplete="off"
                   value="<?= htmlspecialchars((string)$val('username')) ?>">
        </div>
        <div class="form-group">
            <label for="password"><?= t('demo_oracle.db_password') ?></label>
            <input type="password" id="password" name="password" autocomplete="new-password"
                   placeholder="<?= $action === 'edit' ? '&bull;&bull;&bull;&bull;&bull; &mdash; ' . htmlspecialchars(t('auth.password_keep')) : '' ?>">
        </div>
        <div class="form-group">
            <label for="sysdba"><?= t('demo_oracle.db_sysdba') ?></label>
            <input type="checkbox" id="sysdba" name="sysdba" value="1"
                   <?= !empty($val('sysdba')) ? 'checked' : '' ?>>
        </div>
    </div>

    <div style="display:flex;gap:.5rem;align-items:center;flex-wrap:wrap">
        <button type="submit" class="btn btn-primary"><?= t('demo_oracle.save') ?></button>
        <button type="button" id="demo-test-btn" class="btn btn-secondary">
            <?= t('demo_oracle.test_connection') ?>
        </button>
        <a href="<?= demo_oracle_url('db.list') ?>" class="btn btn-secondary"><?= t('demo_oracle.cancel') ?></a>
    </div>

    <?php /* Le test lit la base, il n'y ecrit rien — c'est la seule requete
             Oracle que ce module declenche hors des rapports. Le resultat
             s'affiche ici meme, sans quitter le formulaire ni perdre la
             saisie en cours. */ ?>
    <div id="demo-test-result" style="margin-top:.6rem;font-size:.9rem"></div>
</form>

<script>
/* Bascule des deux sections selon le type de connexion. Sans JavaScript, les
   deux restent visibles : le formulaire fonctionne quand meme, c'est le
   serveur qui tranche. */
(function () {
    var std   = document.getElementById('section-standard');
    var cloud = document.getElementById('section-cloud');
    if (!std || !cloud) return;
    function sync() {
        var isCloud = document.getElementById('conn-cloud').checked;
        std.style.display   = isCloud ? 'none' : '';
        cloud.style.display = isCloud ? '' : 'none';
    }
    document.getElementById('conn-standard').addEventListener('change', sync);
    document.getElementById('conn-cloud').addEventListener('change', sync);
    sync();
})();

window.DemoOracleDatabases = {
    testUrl: <?= json_encode(demo_oracle_url('test')) ?>,
    csrf:    <?= json_encode($csrfToken) ?>,
    dbId:    <?= (int)($record['id'] ?? 0) ?>,
    i18n: {
        testing:        <?= json_encode(t('demo_oracle.test_testing')) ?>,
        fail:           <?= json_encode(t('demo_oracle.test_failed')) ?>,
        diagPack:       <?= json_encode(t('demo_oracle.test_diag_pack')) ?>,
        bashSnap:       <?= json_encode(t('demo_oracle.test_bash_snapper')) ?>,
        dbaRole:        <?= json_encode(t('demo_oracle.test_dba_role')) ?>,
        licensed:       <?= json_encode(t('demo_oracle.test_licensed')) ?>,
        notLicensed:    <?= json_encode(t('demo_oracle.test_not_licensed')) ?>,
        installed:      <?= json_encode(t('demo_oracle.test_installed')) ?>,
        notInstalled:   <?= json_encode(t('demo_oracle.test_not_installed')) ?>,
        present:        <?= json_encode(t('demo_oracle.test_present')) ?>,
        absentReadOnly: <?= json_encode(t('demo_oracle.test_absent_readonly')) ?>,
        noAshSource:    <?= json_encode(t('demo_oracle.test_no_ash_source')) ?>
    }
};
</script>
<script src="/modules/demo_oracle/assets/js/databases-test.js?v=<?= filemtime(__DIR__ . '/../assets/js/databases-test.js') ?>"></script>

<?php endif; ?>

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