<?php
include('includes/header.php');

/* =======================
   SECURITY
======================= */
if (!isset($_SESSION['loggedin'], $_SESSION['name'], $_SESSION['role'])) {
    header("Location: index.php");
    exit;
}

$username = $_SESSION['name'];
$role     = $_SESSION['role'];

/* =======================
   CREDIT INFO
======================= */
// Fetch current balance for session update
$userData = $db->select(
    'menualuser',
    'credits',
    'username = :username',
    '',
    [':username' => $username]
);

if (!empty($userData)) {
    $_SESSION['credits'] = $userData[0]['credits'] ?? 0;
}

/* =======================
   STATISTICS FUNCTIONS
======================= */

function getUserCount($db, $role, $username) {
    if ($role === 'master') {
        $rows = $db->select('menualuser', 'COUNT(*) AS total', 'role IN ("super-reseller","reseller")');
        return (int)($rows[0]['total'] ?? 0);
    }
    if ($role === 'super-reseller') {
        $rows = $db->select('menualuser', 'COUNT(*) AS total', 'parent = :p AND role = "reseller"', '', [':p' => $username]);
        return (int)($rows[0]['total'] ?? 0);
    }
    return 0;
}

function getTotalCredits($db, $role, $username) {
    if ($role === 'master') {
        $rows = $db->select('menualuser', 'credits', 'role IN ("super-reseller","reseller")');
    } elseif ($role === 'super-reseller') {
        $rows = $db->select('menualuser', 'credits', 'parent = :p AND role = "reseller"', '', [':p' => $username]);
    } else {
        return 0;
    }
    $total = 0;
    foreach ($rows as $row) {
        if (is_unlimited_credits($row['credits'] ?? 0)) {
            return 999999;
        }
        $total += (int)($row['credits'] ?? 0);
    }
    return $total;
}

function getMyCredits($db, $role, $username) {
    if ($role === 'master') return '∞';
    $result = $db->select('menualuser', 'credits', 'username = :username', '', [':username' => $username]);
    return $result[0]['credits'] ?? 0;
}

function getActiveUsers($db, $role, $username) {
    if ($role === 'master') {
        $rows = $db->select('menualuser', 'COUNT(*) AS total', 'status = "active" AND role IN ("super-reseller","reseller")');
        return (int)($rows[0]['total'] ?? 0);
    }
    if ($role === 'super-reseller') {
        $rows = $db->select('menualuser', 'COUNT(*) AS total', 'status = "active" AND parent = :p AND role = "reseller"', '', [':p' => $username]);
        return (int)($rows[0]['total'] ?? 0);
    }
    return 0;
}

function safe_html($value) {
    return ($value === null || $value === '') ? '-' : htmlspecialchars($value);
}

$userCount = getUserCount($db, $role, $username);
$totalCredits = getTotalCredits($db, $role, $username);
$myCredits = getMyCredits($db, $role, $username);
$activeUsers = getActiveUsers($db, $role, $username);

$parentName = 'N/A';
if ($role === 'reseller') {
    $parentInfo = $db->select('menualuser', 'username', 'username = (SELECT parent FROM menualuser WHERE username = :username)', '', [':username' => $username]);
    $parentName = $parentInfo[0]['username'] ?? 'N/A';
}

$clientRows = [];
$expiringSoonClients = [];
$expiredClientsList = [];
$activeClientsList = [];
$clientStats = [
    'active' => 0,
    'expiring' => 0,
    'expired' => 0,
];

$dbFile = __DIR__ . '/api/.db.db';
ensure_codes_schema($dbFile);
if (file_exists($dbFile)) {
    $sqlite = new SQLite3($dbFile);
    if ($role === 'master') {
        $ownerWhere = "owner != 'trial'";
    } elseif ($role === 'super-reseller') {
        $owners = get_visible_client_owners($db, $role, $username);
        $quoted = array_map(function($item) use ($sqlite){ return "'" . SQLite3::escapeString($item) . "'"; }, $owners);
        $ownerWhere = $quoted ? "owner IN (" . implode(',', $quoted) . ") AND owner != 'trial'" : '1=0';
    } else {
        $ownerWhere = "owner = '" . SQLite3::escapeString($username) . "' AND owner != 'trial'";
    }

    $sql = "SELECT id, code, owner, client_name, client_whatsapp, expires_at, status, created_at FROM codes WHERE " . $ownerWhere . " ORDER BY expires_at ASC";
    $result = @$sqlite->query($sql);

    if ($result) {
        $nowTs = time();
        $soonTs = $nowTs + (3 * 86400);
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $expRaw = $row['expires_at'] ?? '';
            $expTs = $expRaw ? strtotime($expRaw) : 0;
            $status = $row['status'] ?? 'active';
            $isExpired = ($expTs && $expTs < $nowTs) || $status === 'expired';
            $daysLeft = $expTs ? floor(($expTs - $nowTs) / 86400) : null;

            $row['days_left'] = $daysLeft;
            $row['safe_name'] = htmlspecialchars($row['client_name'] ?? 'Sin nombre');
            $row['safe_phone'] = htmlspecialchars($row['client_whatsapp'] ?? '');
            $row['safe_code'] = htmlspecialchars($row['code'] ?? '');
            $row['safe_expire'] = htmlspecialchars($expRaw ?: '-');

            if ($status === 'blocked') {
                continue;
            }

            if ($isExpired) {
                $clientStats['expired']++;
                if (count($expiredClientsList) < 8) $expiredClientsList[] = $row;
            } elseif ($expTs && $expTs <= $soonTs) {
                $clientStats['expiring']++;
                if (count($expiringSoonClients) < 8) $expiringSoonClients[] = $row;
            } else {
                $clientStats['active']++;
                if (count($activeClientsList) < 8) $activeClientsList[] = $row;
            }
        }
    }
}
?>

<style>
.dashboard-card { border-radius: 5px; border: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2); margin-bottom: 20px; }
.dashboard-card .card-header { background: rgba(220, 53, 69, 0.2); border-bottom: 1px solid rgba(220, 53, 69, 0.3); padding: 15px 20px; }
.stat-number { font-size: 2.5rem; font-weight: 700; margin: 10px 0; color: #dc3545; }
.stat-number-master { font-size: 3rem; font-weight: 800; }
.stat-label { font-size: 0.9rem; color: #aaa; text-transform: uppercase; letter-spacing: 1px; }
.infinity-symbol { font-size: 3.5rem; font-weight: bold; line-height: 1; color: #dc3545; }
.info-box { background: rgba(255,255,255,0.05); border-left: 4px solid #dc3545; padding: 15px; margin-bottom: 10px; border-radius: 3px; }
.info-box h6 { color: #fff; margin-bottom: 5px; }
.info-box p { color: #aaa; margin: 0; font-size: 0.9rem; }
.action-btn { background: rgba(220, 53, 69, 0.1); border: 1px solid rgba(220, 53, 69, 0.3); color: #fff; padding: 12px; border-radius: 5px; text-align: left; display: block; width: 100%; margin-bottom: 10px; transition: all 0.3s; }
.action-btn:hover { background: rgba(220, 53, 69, 0.2); border-color: #dc3545; text-decoration: none; transform: translateY(-2px); }
.action-btn i { color: #dc3545; margin-right: 10px; }
.client-mini-list { list-style: none; padding-left: 0; margin: 0; }
.client-mini-list li { display: flex; justify-content: space-between; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px solid rgba(255,255,255,0.08); }
.client-mini-list li:last-child { border-bottom: 0; }
.client-name { font-weight: 600; color: #fff; }
.client-meta { font-size: 0.85rem; color: #aaa; }
.dashboard-pill { display: inline-block; padding: 3px 10px; border-radius: 999px; font-size: 0.8rem; font-weight: 700; }
.pill-active { background: rgba(40,167,69,0.2); color: #5dd47a; }
.pill-expiring { background: rgba(255,193,7,0.18); color: #ffd45b; }
.pill-expired { background: rgba(220,53,69,0.2); color: #ff7d8d; }
</style>

<div class="col-md-12 mx-auto">
    
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card dashboard-card">
                <div class="card-header">
                    <h3 class="mb-0"><i class="fa fa-tachometer-alt"></i> Panel</h3>
                    <p class="mb-0 text-muted">Usuario: <?=htmlspecialchars($username)?> | Rol: <?=role_label_ptbr($role)?></p>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-lg-3 col-md-6">
            <div class="card dashboard-card">
                <div class="card-body text-center">
                    <i class="fa fa-coins fa-2x mb-3" style="color: #dc3545;"></i>
                    <div class="stat-number <?= $role === 'master' ? 'stat-number-master' : '' ?>">
                        <?= ($role === 'master' || is_unlimited_credits($myCredits)) ? '<div class="infinity-symbol">∞</div>' : number_format((int)$myCredits, 0, ',', '.') ?>
                    </div>
                    <div class="stat-label">Créditos Disponibles</div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6">
            <div class="card dashboard-card">
                <div class="card-body text-center">
                    <i class="fa fa-users fa-2x mb-3" style="color: #dc3545;"></i>
                    <div class="stat-number"><?=$userCount?></div>
                    <div class="stat-label">Total de Usuarios</div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6">
            <div class="card dashboard-card">
                <div class="card-body text-center">
                    <i class="fa fa-chart-line fa-2x mb-3" style="color: #dc3545;"></i>
                    <div class="stat-number"><?= $totalCredits >= 999999 ? '∞' : number_format($totalCredits, 0, ',', '.') ?></div>
                    <div class="stat-label">Créditos de la Red</div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6">
            <div class="card dashboard-card">
                <div class="card-body text-center">
                    <i class="fa fa-check-circle fa-2x mb-3" style="color: #dc3545;"></i>
                    <div class="stat-number"><?=$activeUsers?></div>
                    <div class="stat-label">Usuarios Activos</div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card dashboard-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fa fa-info-circle"></i> Detalles de la Cuenta</h5>
                </div>
                <div class="card-body">
                    <div class="info-box">
                        <h6><i class="fa fa-user-circle"></i> Información del Perfil</h6>
                        <p>Nombre de Usuario: <strong><?=htmlspecialchars($username)?></strong></p>
                        <p>Nivel de Acceso: <span class="badge badge-danger"><?=role_label_ptbr($role)?></span></p>
                        <?php if($role === 'reseller'): ?>
                            <p>Administrado por: <?=safe_html($parentName)?></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card dashboard-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fa fa-bolt"></i> Acciones</h5>
                </div>
                <div class="card-body">
                    <?php if ($role !== 'reseller'): ?>
                        <a href="myteam.php" class="action-btn"><i class="fa fa-users"></i> Administrar Revendedores</a>
                    <?php endif; ?>
                    <a href="user.php" class="action-btn"><i class="fa fa-user-cog"></i> Editar Perfil</a>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-lg-4 col-md-6">
            <div class="card dashboard-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fa fa-check-circle"></i> Clientes Activos</h5>
                </div>
                <div class="card-body">
                    <div class="stat-number"><?=$clientStats['active']?></div>
                    <div class="stat-label">Más de 3 días vigentes</div>
                    <?php if ($activeClientsList): ?>
                        <ul class="client-mini-list mt-3">
                            <?php foreach ($activeClientsList as $item): ?>
                                <li>
                                    <div>
                                        <div class="client-name"><?=$item['safe_name']?></div>
                                        <div class="client-meta">Código: <?=$item['safe_code']?> · Vence: <?=$item['safe_expire']?></div>
                                    </div>
                                    <span class="dashboard-pill pill-active">Activo</span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php else: ?>
                        <p class="text-muted mt-3 mb-0">No hay clientes activos para mostrar.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="col-lg-4 col-md-6">
            <div class="card dashboard-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fa fa-exclamation-triangle"></i> Por Vencer</h5>
                </div>
                <div class="card-body">
                    <div class="stat-number"><?=$clientStats['expiring']?></div>
                    <div class="stat-label">Vencen en 3 días o menos</div>
                    <?php if ($expiringSoonClients): ?>
                        <ul class="client-mini-list mt-3">
                            <?php foreach ($expiringSoonClients as $item): ?>
                                <li>
                                    <div>
                                        <div class="client-name"><?=$item['safe_name']?></div>
                                        <div class="client-meta">Código: <?=$item['safe_code']?> · Vence: <?=$item['safe_expire']?></div>
                                    </div>
                                    <span class="dashboard-pill pill-expiring"><?=max(0, (int)$item['days_left'])?> d</span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php else: ?>
                        <p class="text-muted mt-3 mb-0">No hay clientes por vencer.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="col-lg-4 col-md-12">
            <div class="card dashboard-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fa fa-times-circle"></i> Vencidos</h5>
                </div>
                <div class="card-body">
                    <div class="stat-number"><?=$clientStats['expired']?></div>
                    <div class="stat-label">Necesitan renovación</div>
                    <?php if ($expiredClientsList): ?>
                        <ul class="client-mini-list mt-3">
                            <?php foreach ($expiredClientsList as $item): ?>
                                <li>
                                    <div>
                                        <div class="client-name"><?=$item['safe_name']?></div>
                                        <div class="client-meta">Código: <?=$item['safe_code']?> · Venció: <?=$item['safe_expire']?></div>
                                    </div>
                                    <span class="dashboard-pill pill-expired">Vencido</span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php else: ?>
                        <p class="text-muted mt-3 mb-0">No hay clientes vencidos.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

</div>

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