<?php
/**
 * Clone master tree across verticals (SysAdmin ONLY).  clone-tree-v1
 *
 * Master data (client»process»facility»provider) is otherwise SHARED across verticals. This page implements the
 * "separate per-vertical copies" choice (Option B): copy a SOURCE client's processes → facilities → billing-provider
 * links INTO one or more TARGET clients (typically the same practice's record in another vertical, e.g. CDG_01 → AR_01).
 *
 * Providers are GLOBAL and are RE-LINKED, never duplicated. The clone is idempotent (find-or-create by name), so
 * re-running only fills gaps. A Preview (dry-run) always runs first; nothing is written until "Clone now".
 *
 * Route gate: __sysadmin__ (a cross-vertical bulk write).
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

/** Resolve the target client ids for a source + mode (never includes the source itself). */
$resolveTargets = function (int $srcId, string $mode, int $singleId) use ($pdo): array {
    if ($mode === 'single') return ($singleId > 0 && $singleId !== $srcId) ? [$singleId] : [];
    // by-name: every other active client that shares this one's name, in ANY vertical
    $s = $pdo->prepare("SELECT name FROM clients WHERE id=? AND deleted_at IS NULL"); $s->execute([$srcId]);
    $name = $s->fetchColumn();
    if ($name === false) return [];
    $q = $pdo->prepare("SELECT id FROM clients WHERE LOWER(name)=LOWER(?) AND id<>? AND deleted_at IS NULL ORDER BY name");
    $q->execute([$name, $srcId]);
    return array_map('intval', $q->fetchAll(PDO::FETCH_COLUMN));
};
$clientLabel = function (int $id) use ($pdo): string {
    $r = $pdo->prepare("SELECT c.code,c.name,v.name vn FROM clients c LEFT JOIN verticals v ON v.id=c.vertical_id WHERE c.id=?");
    $r->execute([$id]); $r = $r->fetch();
    return $r ? ($r['name'] . ' · ' . $r['code'] . ' (' . ($r['vn'] ?: 'no vertical') . ')') : ('#' . $id);
};

$preview = null;   // populated on a Preview POST: ['src'=>id, 'mode'=>.., 'single'=>id, 'rows'=>[ [tid,label,counts] ]]

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $do     = (string) input('do');
    $srcId  = (int) input('source_id');
    $mode   = input('mode') === 'single' ? 'single' : 'byname';
    $single = (int) input('target_id');

    if ($srcId <= 0) { flash('error', 'Pick a source client to copy from.'); redirect('/admin/clone-tree.php'); }
    $targets = $resolveTargets($srcId, $mode, $single);
    if (!$targets) { flash('error', $mode === 'single' ? 'Pick a target client different from the source.' : 'No other client shares the source\'s name to copy into.'); redirect('/admin/clone-tree.php'); }

    if ($do === 'execute') {
        $tot = ['proc_new'=>0,'fac_new'=>0,'link_new'=>0]; $done = 0;
        $pdo->beginTransaction();
        try {
            foreach ($targets as $tid) {
                $r = coding_clone_tree($pdo, $srcId, $tid, $uid, false);
                $tot['proc_new'] += $r['proc_new']; $tot['fac_new'] += $r['fac_new']; $tot['link_new'] += $r['link_new']; $done++;
            }
            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            flash('error', 'Clone failed: ' . (defined('APP_DEBUG') && APP_DEBUG ? $e->getMessage() : 'server error') . ' — nothing was changed.');
            redirect('/admin/clone-tree.php');
        }
        flash('success', "Cloned into $done client(s): created {$tot['proc_new']} process(es), {$tot['fac_new']} facility(ies), {$tot['link_new']} provider link(s). Existing items were left as-is.");
        redirect('/admin/clone-tree.php');
    }

    // Preview (dry-run)
    $rows = [];
    foreach ($targets as $tid) $rows[] = ['tid'=>$tid, 'label'=>$clientLabel($tid), 'c'=>coding_clone_tree($pdo, $srcId, $tid, $uid, true)];
    $preview = ['src'=>$srcId, 'srcLabel'=>$clientLabel($srcId), 'mode'=>$mode, 'single'=>$single, 'rows'=>$rows];
}

$clients = $pdo->query("SELECT c.id,c.code,c.name,c.vertical_id, v.name vname,
        (SELECT COUNT(*) FROM coding_facilities f JOIN processes pr ON pr.id=f.process_id WHERE pr.client_id=c.id) nf
    FROM clients c LEFT JOIN verticals v ON v.id=c.vertical_id WHERE c.deleted_at IS NULL ORDER BY c.name, v.name")->fetchAll();

$pageTitle = 'Clone tree across verticals';
require __DIR__ . '/../includes/header.php';
?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/css/tom-select.bootstrap5.min.css">
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/js/tom-select.complete.min.js"></script>

<div class="page-header"><div class="container-xl">
    <h2 class="page-title"><i class="ti ti-copy me-2 text-primary"></i>Clone tree across verticals</h2>
    <div class="text-secondary small">Copy a source client's <strong>processes → facilities → billing-provider links</strong> into another vertical's client. Providers are global, so they're re-linked (not duplicated). Idempotent — re-running only fills gaps.</div>
</div></div>
<div class="page-body"><div class="container-xl">

    <div class="card mb-3"><div class="card-body">
        <form method="POST" class="row g-3 align-items-end">
            <?= csrf_field() ?><input type="hidden" name="do" value="preview">
            <div class="col-md-5">
                <label class="form-label required">Source client (copy FROM)</label>
                <select name="source_id" id="src" class="form-select" required>
                    <option value="">— choose source —</option>
                    <?php foreach ($clients as $c): ?>
                        <option value="<?= (int)$c['id'] ?>" <?= ($preview && $preview['src']===(int)$c['id'])?'selected':'' ?>>
                            <?= e($c['name']) ?> · <?= e($c['code']) ?> (<?= e($c['vname'] ?: 'no vertical') ?>) — <?= (int)$c['nf'] ?> facility(ies)</option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label">Copy INTO</label>
                <div>
                    <label class="form-check form-check-inline"><input type="radio" name="mode" value="byname" class="form-check-input" <?= (!$preview || $preview['mode']==='byname')?'checked':'' ?> onchange="document.getElementById('singleWrap').style.display='none'"><span class="form-check-label">All same-name clients (other verticals)</span></label>
                    <label class="form-check form-check-inline"><input type="radio" name="mode" value="single" class="form-check-input" <?= ($preview && $preview['mode']==='single')?'checked':'' ?> onchange="document.getElementById('singleWrap').style.display=''"><span class="form-check-label">One specific client</span></label>
                </div>
                <div id="singleWrap" class="mt-2" style="<?= ($preview && $preview['mode']==='single')?'':'display:none' ?>">
                    <select name="target_id" id="tgt" class="form-select">
                        <option value="">— choose target —</option>
                        <?php foreach ($clients as $c): ?>
                            <option value="<?= (int)$c['id'] ?>" <?= ($preview && $preview['single']===(int)$c['id'])?'selected':'' ?>><?= e($c['name']) ?> · <?= e($c['code']) ?> (<?= e($c['vname'] ?: 'no vertical') ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-3">
                <button class="btn btn-outline-primary w-100"><i class="ti ti-eye me-1"></i>Preview</button>
                <div class="form-hint mt-1">A dry-run runs first — nothing is written until you confirm.</div>
            </div>
        </form>
    </div></div>

    <?php if ($preview): $any = false; foreach ($preview['rows'] as $r) { if ($r['c']['proc_new']+$r['c']['fac_new']+$r['c']['link_new'] > 0) { $any = true; break; } } ?>
    <div class="card">
        <div class="card-header"><h3 class="card-title mb-0">Preview — copying from <strong><?= e($preview['srcLabel']) ?></strong></h3></div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>Target client</th><th class="text-center">Processes (new / exists)</th><th class="text-center">Facilities (new / exists)</th><th class="text-center">Provider links (new / exists)</th></tr></thead>
            <tbody>
            <?php foreach ($preview['rows'] as $r): $c = $r['c']; ?>
                <tr>
                    <td><strong><?= e($r['label']) ?></strong><?php if ($c['errors']): ?><div class="text-danger small"><?= e(implode('; ', $c['errors'])) ?></div><?php endif; ?></td>
                    <td class="text-center"><span class="badge bg-green-lt"><?= (int)$c['proc_new'] ?> new</span> <span class="text-secondary small"><?= (int)$c['proc_existing'] ?> exist</span></td>
                    <td class="text-center"><span class="badge bg-green-lt"><?= (int)$c['fac_new'] ?> new</span> <span class="text-secondary small"><?= (int)$c['fac_existing'] ?> exist</span></td>
                    <td class="text-center"><span class="badge bg-green-lt"><?= (int)$c['link_new'] ?> new</span> <span class="text-secondary small"><?= (int)$c['link_existing'] ?> exist</span></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table></div>
        <div class="card-footer d-flex justify-content-between align-items-center">
            <div class="text-secondary small"><?= $any ? 'Review the “new” counts above, then confirm.' : 'Nothing new to create — the target(s) already have everything from the source.' ?></div>
            <?php if ($any): ?>
            <form method="POST" onsubmit="return confirm('Clone the source tree into the target client(s) now? Existing items are left as-is.');">
                <?= csrf_field() ?>
                <input type="hidden" name="do" value="execute">
                <input type="hidden" name="source_id" value="<?= (int)$preview['src'] ?>">
                <input type="hidden" name="mode" value="<?= e($preview['mode']) ?>">
                <input type="hidden" name="target_id" value="<?= (int)$preview['single'] ?>">
                <button class="btn btn-primary"><i class="ti ti-copy me-1"></i>Clone now</button>
            </form>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

</div></div>
<script>
(function(){ if (typeof TomSelect === 'undefined') return;
    new TomSelect('#src', {maxOptions:5000, persist:false});
    new TomSelect('#tgt', {maxOptions:5000, persist:false});
})();
</script>
<?php require __DIR__ . '/../includes/footer.php'; ?>
