<?php
NexoraRbac::requirePermission('accounts.view');

$realmIds = NexoraRealm::registrationRealms();
if(count($realmIds) < 2) {
    echo '<div class="alert alert-warning">La conciliación necesita al menos dos realms configurados.</div>';
    return;
}

$datasets = array();
foreach($realmIds as $realmId) {
    $db = Connection::Database('Me_MuOnline', $realmId);
    $rows = $db->query_fetch('SELECT '._CLMN_USERNM_.' AS username, '._CLMN_EMAIL_.' AS email, '._CLMN_BLOCCODE_.' AS blocked FROM '._TBL_MI_.' ORDER BY '._CLMN_USERNM_);
    $datasets[$realmId] = array();
    if(is_array($rows)) foreach($rows as $row) $datasets[$realmId][strtolower($row['username'])] = $row;
}

$primary = $realmIds[0];
$secondary = $realmIds[1];
$all = array_values(array_unique(array_merge(array_keys($datasets[$primary]), array_keys($datasets[$secondary]))));
sort($all, SORT_STRING);
$stats = array('both'=>0,'only_primary'=>0,'only_secondary'=>0,'email_mismatch'=>0,'block_mismatch'=>0);
$differences = array();
foreach($all as $key) {
    $a = isset($datasets[$primary][$key]) ? $datasets[$primary][$key] : null;
    $b = isset($datasets[$secondary][$key]) ? $datasets[$secondary][$key] : null;
    if($a && $b) {
        $stats['both']++;
        $emailMismatch = strcasecmp(trim((string)$a['email']), trim((string)$b['email'])) !== 0;
        $blockMismatch = (string)$a['blocked'] !== (string)$b['blocked'];
        if($emailMismatch) $stats['email_mismatch']++;
        if($blockMismatch) $stats['block_mismatch']++;
        if($emailMismatch || $blockMismatch) $differences[] = array('username'=>$a['username'],'status'=>'Diferencia','a'=>$a,'b'=>$b);
    } elseif($a) {
        $stats['only_primary']++;
        $differences[] = array('username'=>$a['username'],'status'=>'Solo '.$primary,'a'=>$a,'b'=>null);
    } else {
        $stats['only_secondary']++;
        $differences[] = array('username'=>$b['username'],'status'=>'Solo '.$secondary,'a'=>null,'b'=>$b);
    }
}
?>
<div class="row"><div class="col-lg-12"><h1 class="page-header">Account Reconciliation</h1></div></div>
<div class="alert alert-info">Informe de solo lectura. No copia, elimina ni modifica cuentas. Compara identidad entre <strong><?php echo htmlspecialchars(NexoraRealm::label($primary), ENT_QUOTES, 'UTF-8'); ?></strong> y <strong><?php echo htmlspecialchars(NexoraRealm::label($secondary), ENT_QUOTES, 'UTF-8'); ?></strong>.</div>
<div class="row">
<?php
$cards = array(
    array('Coinciden en ambos',$stats['both'],'success'),
    array('Solo '.NexoraRealm::label($primary),$stats['only_primary'],'warning'),
    array('Solo '.NexoraRealm::label($secondary),$stats['only_secondary'],'warning'),
    array('Email distinto',$stats['email_mismatch'],'danger'),
    array('Bloqueo distinto',$stats['block_mismatch'],'danger'),
);
foreach($cards as $card) echo '<div class="col-sm-4 col-md-2"><div class="panel panel-'.$card[2].'"><div class="panel-heading"><div style="font-size:26px;font-weight:bold">'.(int)$card[1].'</div><div>'.$card[0].'</div></div></div></div>';
?>
</div>
<div class="panel panel-default"><div class="panel-heading"><strong>Casos que requieren decisión</strong></div><div class="panel-body table-responsive">
<table class="table table-striped table-condensed" id="nexora-reconciliation"><thead><tr><th>Cuenta</th><th>Estado</th><th><?php echo htmlspecialchars(NexoraRealm::label($primary), ENT_QUOTES, 'UTF-8'); ?> email</th><th><?php echo htmlspecialchars(NexoraRealm::label($secondary), ENT_QUOTES, 'UTF-8'); ?> email</th><th>Bloqueo A/B</th></tr></thead><tbody>
<?php foreach($differences as $row) { ?>
<tr>
<td><?php echo htmlspecialchars($row['username'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlspecialchars($row['status'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlspecialchars($row['a'] ? (string)$row['a']['email'] : '—', ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlspecialchars($row['b'] ? (string)$row['b']['email'] : '—', ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlspecialchars(($row['a'] ? (string)$row['a']['blocked'] : '—').' / '.($row['b'] ? (string)$row['b']['blocked'] : '—'), ENT_QUOTES, 'UTF-8'); ?></td>
</tr>
<?php } ?>
</tbody></table></div></div>
