<?php
/* =============================================
   DASHBOARD — index.php (Final Complete Code)
   ✅ Date Range REMOVED
   ✅ Super Distributor REMOVED
   ✅ API Overview → Add API + View All buttons
   ✅ Legend names → Clickable links
   ✅ Recent Txn → User Sales Report (full width)
   ✅ API Sales Overview REMOVED
   ✅ Member Cards Row REMOVED
   ✅ Compact spacing
   ✅ Exact gradients
============================================= */

$today    = date('Y-m-d');
$url_date = "date=" . $today;

// ── Stats ─────────────────────────────────────
$sql_success = "SELECT COUNT(*) quantity, COALESCE(SUM(amount),0) amount
                FROM wallet WHERE status='Success'
                AND transaction_type='Recharge'
                AND DATE(created_at)='$today'";
$success = getXbyY($sql_success)[0] ?? ['quantity'=>0,'amount'=>0];

$sql_failed = "SELECT COUNT(*) quantity, COALESCE(SUM(amount),0) amount
               FROM wallet WHERE status='Failed'
               AND transaction_type='Recharge'
               AND DATE(created_at)='$today'";
$failed = getXbyY($sql_failed)[0] ?? ['quantity'=>0,'amount'=>0];

$sql_pending = "SELECT COUNT(*) quantity, COALESCE(SUM(amount),0) amount
                FROM wallet WHERE status='Pending'
                AND transaction_type='Recharge'";
$pending = getXbyY($sql_pending)[0] ?? ['quantity'=>0,'amount'=>0];

$sql_refunds = "SELECT COUNT(*) quantity, COALESCE(SUM(amount),0) amount
                FROM wallet WHERE status='Refund'";
$res_refunds = getXbyY($sql_refunds)[0] ?? ['quantity'=>0,'amount'=>0];

// ── Users (grouped by type) ────────────────────
$rt_users        = "SELECT user_type, COUNT(*) as total, SUM(amount_balance) as amount
                    FROM users WHERE 1 GROUP BY user_type";
$rtres_users     = getXbyY($rt_users);
$rtres_users_total  = array_column($rtres_users, 'total',  'user_type');
$rtres_users_amount = array_column($rtres_users, 'amount', 'user_type');
?>

<!-- =============================================
     STYLES
============================================= -->
<style>

/* ── Base ─────────────────────────────────── */
* { box-sizing: border-box; }
body { background: #f4f7fb; }
.container-fluid { padding: 12px 18px; }

/* ── STAT CARDS ──────────────────────────── */
.stats-row {
    display: flex;
    gap: 10px;
    margin-bottom: 14px;
    flex-wrap: nowrap;
}
.stat-card-new {
    flex: 1;
    min-width: 0;
    min-height: 92px;
    border-radius: 14px;
    padding: 14px 16px;
    color: white;
    display: flex;
    align-items: center;
    gap: 14px;
    cursor: pointer;
    transition: transform .22s, box-shadow .22s;
    box-shadow: 0 4px 18px rgba(0,0,0,.13);
    overflow: hidden;
    position: relative;
}
.stat-card-new:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 26px rgba(0,0,0,.18);
}
.stat-card-new.green  { background: linear-gradient(135deg,#1fb96d,#32d97f); }
.stat-card-new.red    { background: linear-gradient(135deg,#ff4b5c,#f62d42); }
.stat-card-new.orange { background: linear-gradient(135deg,#ffb100,#ff9300); }
.stat-card-new.blue   { background: linear-gradient(135deg,#1e88e5,#42a5f5); }
.stat-card-new.purple { background: linear-gradient(135deg,#7b4dff,#8e44ad); }

.card-icon {
    width: 50px; height: 50px;
    border-radius: 50%;
    background: rgba(255,255,255,.22);
    display: flex; align-items: center; justify-content: center;
    font-size: 22px; flex-shrink: 0;
}
.card-body-text .label { font-size: 12px; font-weight: 600; opacity: .9; margin-bottom: 1px; }
.card-body-text .number { font-size: 26px; font-weight: 800; line-height: 1; margin-bottom: 2px; }
.card-body-text .sub { font-size: 12px; opacity: .88; font-weight: 600; }

/* ── SECTION CARDS ───────────────────────── */
.section-card {
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 3px 14px rgba(0,0,0,.07);
    overflow: hidden;
    margin-bottom: 15px;
}

/* ── SECTION HEADERS ─────────────────────── */
.section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 16px;
    color: white;
}
.section-header h5 {
    font-size: 14px;
    font-weight: 700;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

/* ✅ Exact gradients */
.green-hdr  { background: linear-gradient(90deg,#16a085,#2ecc71,#2962ff); }
.purple-hdr { background: linear-gradient(90deg,#6a5cff,#8e44ad,#ff2f73); }
.blue-hdr   { background: linear-gradient(90deg,#0288d1,#00acc1,#43a047); }

/* ── HEADER BUTTONS ──────────────────────── */
.btn-group-hdr {
    display: flex;
    align-items: center;
    gap: 8px;
}
.view-all-btn {
    background: rgba(255,255,255,.18);
    color: white;
    border: 1.5px solid rgba(255,255,255,.55);
    border-radius: 20px;
    padding: 5px 14px;
    font-size: 12.5px;
    font-weight: 700;
    text-decoration: none;
    transition: background .2s;
    white-space: nowrap;
    display: inline-flex;
    align-items: center;
    gap: 5px;
}
.view-all-btn:hover {
    background: rgba(255,255,255,.28);
    color: white;
    text-decoration: none;
}
.add-btn {
    background: white;
    border: none;
    border-radius: 20px;
    padding: 5px 14px;
    font-size: 12.5px;
    font-weight: 700;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    transition: opacity .2s;
    white-space: nowrap;
}
.add-btn.green-add  { color: #16a085; }
.add-btn.purple-add { color: #8e44ad; }
.add-btn:hover { opacity: .85; text-decoration: none; }

/* ── SECTION BODY ────────────────────────── */
.section-body     { padding: 0; }
.section-body.p12 { padding: 12px 16px; }

/* ── TABLES ──────────────────────────────── */
.mod-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
}
.mod-table thead tr { background: #f8f9fc; }
.mod-table th {
    padding: 9px 14px;
    font-weight: 700;
    color: #555;
    font-size: 12px;
    border-bottom: 1px solid #eee;
    white-space: nowrap;
}
.mod-table td {
    padding: 9px 14px;
    border-bottom: 1px solid #f2f2f2;
    color: #333;
    vertical-align: middle;
    font-size: 13px;
}
.mod-table tbody tr:last-child td { border-bottom: none; }
.mod-table tbody tr:hover { background: #f9fbff; }

/* View All footer link */
.tbl-footer {
    text-align: center;
    padding: 10px;
    border-top: 1px solid #f0f0f0;
}
.tbl-footer a {
    color: #1548D5;
    font-weight: 700;
    font-size: 13px;
    text-decoration: none;
}
.tbl-footer a:hover { text-decoration: underline; }

/* API/User Avatar */
.av-circle {
    width: 34px; height: 34px;
    border-radius: 50%;
    color: white;
    font-size: 12px;
    font-weight: 800;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin-right: 8px;
    vertical-align: middle;
    flex-shrink: 0;
}

/* ── STATUS BADGES ───────────────────────── */
.bs { padding: 3px 12px; border-radius: 20px; font-size: 12px; font-weight: 700; display:inline-block; }
.bs-success { background:#e8faf1; color:#1fb96d; }
.bs-danger  { background:#fef0f1; color:#f62d42; }
.bs-warning { background:#fff8e1; color:#ff9300; }
.bs-purple  { background:#f3f0ff; color:#7b4dff; }

/* ── DONUT CHART ─────────────────────────── */
.donut-wrap {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}
.donut-center {
    position: absolute;
    top: 50%; left: 50%;
    transform: translate(-50%,-50%);
    text-align: center;
    pointer-events: none;
}
.donut-center .dc-lbl { font-size: 11px; color: #888; font-weight: 600; }
.donut-center .dc-num { font-size: 22px; font-weight: 800; color: #333; line-height: 1; }

/* ── DONUT LEGEND ────────────────────────── */
.donut-legend { display: flex; flex-direction: column; gap: 4px; }
.donut-legend-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 7px 0;
    border-bottom: 1px solid #f5f5f5;
}
.donut-legend-item:last-child { border-bottom: none; }
.donut-legend-dot {
    width: 13px; height: 13px;
    border-radius: 50%;
    flex-shrink: 0;
}
.donut-legend-label { flex: 1; }

/* ✅ Clickable link style */
.donut-link {
    color: #444;
    font-weight: 600;
    font-size: 13px;
    text-decoration: none;
    transition: color .2s;
}
.donut-link:hover {
    color: #1565d8;
    text-decoration: none;
}

.donut-legend-count {
    font-size: 14px;
    font-weight: 800;
    color: #333;
    min-width: 36px;
    text-align: right;
}
.donut-legend-pct {
    font-size: 13px;
    font-weight: 700;
    min-width: 52px;
    text-align: right;
}
.donut-total {
    border-top: 2px solid #f0f0f0;
    padding-top: 10px;
    margin-top: 6px;
    font-weight: 800;
    font-size: 14px;
    color: #333;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* ── ROW TWEAKS ──────────────────────────── */
.row { margin-left: -8px; margin-right: -8px; }
.row > [class*="col-"] { padding-left: 8px; padding-right: 8px; }
.mb-3 { margin-bottom: 14px !important; }

/* ── FOOTER ──────────────────────────────── */
.dash-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 2px 4px;
    font-size: 12px;
    color: #999;
    border-top: 1px solid #e8e8e8;
    margin-top: 4px;
}
</style>

<!-- =============================================
     DASHBOARD — BEGIN
============================================= -->
<div class="container-fluid">

<!-- ══════════════════════════════════════════
     ROW 1 — 5 STAT CARDS
     ❌ Date Range removed — cards direct start
══════════════════════════════════════════ -->
<div class="stats-row">

    <!-- Total Success -->
    <div class="stat-card-new green"
         onclick="location.href='recharges.php?status=Success&<?= $url_date; ?>'">
        <div class="card-icon"><i class="fas fa-check"></i></div>
        <div class="card-body-text">
            <div class="label">Total Success</div>
            <div class="number"><?= $success['quantity']; ?></div>
            <div class="sub">₹ <?= number_format($success['amount'],2); ?></div>
        </div>
    </div>

    <!-- Total Failed -->
    <div class="stat-card-new red"
         onclick="location.href='recharges.php?status=Failed&<?= $url_date; ?>'">
        <div class="card-icon"><i class="fas fa-times"></i></div>
        <div class="card-body-text">
            <div class="label">Total Failed</div>
            <div class="number"><?= $failed['quantity']; ?></div>
            <div class="sub">₹ <?= number_format($failed['amount'],2); ?></div>
        </div>
    </div>

    <!-- Total Pending -->
    <div class="stat-card-new orange"
         onclick="location.href='recharges.php?status=Pending'">
        <div class="card-icon"><i class="fas fa-clock"></i></div>
        <div class="card-body-text">
            <div class="label">Total Pending</div>
            <div class="number"><?= $pending['quantity']; ?></div>
            <div class="sub">₹ <?= number_format($pending['amount'],2); ?></div>
        </div>
    </div>

    <!-- Total Refund -->
    <div class="stat-card-new blue"
         onclick="location.href='recharges.php?status=Refund'">
        <div class="card-icon"><i class="fas fa-undo"></i></div>
        <div class="card-body-text">
            <div class="label">Total Refund</div>
            <div class="number"><?= $res_refunds['quantity']; ?></div>
            <div class="sub">₹ <?= number_format($res_refunds['amount'],2); ?></div>
        </div>
    </div>

    <!-- Total User -->
    <div class="stat-card-new purple"
         onclick="location.href='disputes.php'">
        <div class="card-icon"><i class="fas fa-ticket-alt"></i></div>
        <div class="card-body-text">
            <div class="label">Complaints</div>
            <div class="number"><?= $rtres_users_total['Complaints'] ?? 0; ?></div>
        
        </div>
    </div>

</div><!-- end stats-row -->

<!-- ══════════════════════════════════════════
     ROW 2 — API Overview (7) | All User Donut (5)
══════════════════════════════════════════ -->
<div class="row">

    <!-- ── API OVERVIEW ─────────────────── -->
    <div class="col-xl-7 mb-3">
        <div class="section-card">
            <div class="section-header green-hdr">
                <h5><i class="fas fa-plug"></i> API Overview</h5>
                <!-- ✅ Add API + View All -->
                <div class="btn-group-hdr">
                    <a href="api_details.php" class="add-btn green-add">
                        <i class="fas fa-plus"></i> Add API
                    </a>
                    <a href="apis.php" class="view-all-btn">
                        View All
                    </a>
                </div>
            </div>
            <div class="section-body">
                <table class="mod-table">
                    <thead>
                        <tr>
                            <th>API Name</th>
                            <th>API Balance</th>
                            <th>Today's Sale</th>
                            <th>Pending</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $api_colors = ['#11998e','#667eea','#f7971e','#eb3349','#2980b9','#764ba2','#ff2f73'];
                    $sql_api    = "SELECT a.api_id, a.api_name, a.api_balance, a.is_active,
                        (SELECT COALESCE(SUM(amount),0) FROM wallet w
                         WHERE w.api_id=a.api_id
                         AND w.status='Success'
                         AND w.transaction_type='Recharge'
                         AND DATE(w.created_at)='$today') as today_sale,
                        (SELECT COUNT(*) FROM wallet w
                         WHERE w.api_id=a.api_id
                         AND w.status='Pending') as pending_count
                        FROM api a LIMIT 8";
                    $res_api = getXbyY($sql_api);
                    $ci = 0;
                    foreach ($res_api as $api):
                        $initials = strtoupper(substr($api['api_name'],0,2));
                        $acolor   = $api_colors[$ci % count($api_colors)]; $ci++;
                        $isActive = $api['is_active'] == 1;
                    ?>
                    <tr>
                        <td>
                            <span class="av-circle" style="background:<?= $acolor; ?>;">
                                <?= $initials; ?>
                            </span>
                            <strong><?= $api['api_name']; ?></strong>
                        </td>
                        <td style="color:#11998e; font-weight:700;">
                            ₹<?= number_format($api['api_balance'],2); ?>
                        </td>
                        <td style="color:#667eea; font-weight:700;">
                            ₹<?= number_format($api['today_sale'],2); ?>
                        </td>
                        <td>
                            <span class="bs bs-warning">
                                <?= $api['pending_count']; ?>
                            </span>
                        </td>
                        <td>
                            <?php if ($isActive): ?>
                                <span class="bs bs-success">Active</span>
                            <?php else: ?>
                                <span class="bs bs-danger">Inactive</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="apis.php?edit=<?= $api['api_id']; ?>"
                               style="color:#667eea; font-size:18px;">
                                <i class="fas fa-ellipsis-v"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
               
            </div>
        </div>
    </div>

    <!-- ── ALL USER DONUT ────────────────── -->
    <div class="col-xl-5 mb-3">
        <div class="section-card">
            <div class="section-header purple-hdr">
                <h5><i class="fas fa-users"></i> All User</h5>
                <a href="team_details.php" class="add-btn purple-add">
                    <i class="fas fa-plus"></i> Add Member
                </a>
            </div>
            <div class="section-body p12">
                <div class="row align-items-center">

                    <!-- Donut -->
                    <div class="col-5 text-center">
                        <div class="donut-wrap">
                            <canvas id="userDonutChart" width="180" height="180"></canvas>
                            <div class="donut-center">
                                <div class="dc-lbl">Total</div>
                                <div class="dc-num">
                                    <?= array_sum($rtres_users_total); ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- ✅ Legend — 4 types, Super Distributor REMOVED, names clickable -->
                    <div class="col-7">
                        <div class="donut-legend">
                        <?php
                        // ✅ Super Distributor REMOVED
                        $type_colors = [
                            'Master Distributor' => '#11998e',
                            'Distributor'        => '#f7971e',
                            'Retailer'           => '#667eea',
                            'API User'           => '#eb3349',
                        ];
                        $total_users = array_sum($rtres_users_total);

                        foreach ($type_colors as $type => $col):
                            $cnt = $rtres_users_total[$type] ?? 0;
                            $pct = $total_users > 0 ? round(($cnt / $total_users) * 100, 2) : 0;

                            // ✅ Link per type
                            switch($type) {
                                case 'Master Distributor': $link = 'admin_md_list.php';           break;
                                case 'Distributor':        $link = 'admin_distributers_list.php';  break;
                                case 'Retailer':           $link = 'admin_retailer_list.php';      break;
                                case 'API User':           $link = 'admin_apiuser_list.php';       break;
                                default:                   $link = '#';
                            }
                        ?>
                        <div class="donut-legend-item">
                            <div class="donut-legend-dot" style="background:<?= $col; ?>;"></div>
                            <div class="donut-legend-label">
                                <!-- ✅ Clickable name -->
                                <a href="<?= $link; ?>" class="donut-link">
                                    <?= $type; ?>
                                </a>
                            </div>
                            <div class="donut-legend-count"><?= $cnt; ?></div>
                            <div class="donut-legend-pct" style="color:<?= $col; ?>;">
                                <?= $pct; ?>%
                            </div>
                        </div>
                        <?php endforeach; ?>

                        <!-- Total row -->
                        <div class="donut-total">
                            <span>Total</span>
                            <span><?= $total_users; ?></span>
                        </div>

                        </div><!-- end donut-legend -->
                    </div>

                </div>
            </div>
        </div>
    </div>

</div><!-- end row 2 -->

<!-- ══════════════════════════════════════════
     ROW 3 — USER SALES REPORT (full width)
     ✅ Recent Transactions replaced
     ✅ API Sales Overview REMOVED
══════════════════════════════════════════ -->
<div class="row">
    <div class="col-12 mb-3">
        <div class="section-card">
            <div class="section-header blue-hdr">
                <!-- ✅ New heading -->
                <h5><i class="fas fa-chart-bar"></i> User Sales Report</h5>
                <a href="business_user.php" class="view-all-btn">View All</a>
            </div>
            <div class="section-body">
                <table class="mod-table">
                    <thead>
                        <tr>
                            <th>User</th>
                            <th>Mobile</th>
                            <th>Today's Sale</th>
                            <th>Total Sale</th>
                            <th>Fund Received</th>
                            <th>Balance</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $u_colors = ['#11998e','#667eea','#f7971e','#eb3349','#2980b9','#764ba2','#ff2f73','#e67e22','#2ecc71','#e74c3c'];
                    $sql_user_sales = "
                        SELECT
                            u.user_id,
                            u.name,
                            u.mobile,
                            u.amount_balance,
                            u.user_type,
                            u.is_active,
                            (SELECT COALESCE(SUM(w.amount),0)
                             FROM wallet w
                             WHERE w.user_id=u.user_id
                             AND w.transaction_type='Recharge'
                             AND w.status='Success'
                             AND DATE(w.created_at)='$today') as today_sale,
                            (SELECT COALESCE(SUM(w.amount),0)
                             FROM wallet w
                             WHERE w.user_id=u.user_id
                             AND w.transaction_type='Recharge'
                             AND w.status='Success') as total_sale,
                            (SELECT COALESCE(SUM(w.amount),0)
                             FROM wallet w
                             WHERE w.user_id=u.user_id
                             AND w.transaction_type='Recieve Money') as fund_received
                        FROM users u
                        WHERE u.user_type != 'Admin'
                        AND u.is_active = 1
                        ORDER BY today_sale DESC
                        LIMIT 10";
                    $res_user_sales = getXbyY($sql_user_sales);
                    $uc = 0;
                    foreach ($res_user_sales as $usr):
                        $initials = strtoupper(substr($usr['name'],0,1));
                        $uc_clr   = $u_colors[$uc % count($u_colors)]; $uc++;
                    ?>
                    <tr>
                        <td>
                            <span class="av-circle" style="background:<?= $uc_clr; ?>; width:30px; height:30px; font-size:12px;">
                                <?= $initials; ?>
                            </span>
                            <strong><?= $usr['name']; ?></strong>
                            <small style="color:#999; font-size:11px;"> (<?= $usr['user_type']; ?>)</small>
                        </td>
                        <td style="color:#555;">
                            <?= $usr['mobile']; ?>
                        </td>
                        <td style="color:#11998e; font-weight:700;">
                            ₹<?= number_format($usr['today_sale'],2); ?>
                        </td>
                        <td style="color:#667eea; font-weight:700;">
                            ₹<?= number_format($usr['total_sale'],2); ?>
                        </td>
                        <td style="color:#f7971e; font-weight:700;">
                            ₹<?= number_format($usr['fund_received'],2); ?>
                        </td>
                        <td style="color:#7b4dff; font-weight:700;">
                            ₹<?= number_format($usr['amount_balance'],2); ?>
                        </td>
                        <td>
                            <?php if ($usr['is_active'] == 1): ?>
                                <span class="bs bs-success">Active</span>
                            <?php else: ?>
                                <span class="bs bs-danger">Inactive</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div><!-- end row 3 -->

<!-- ❌ MEMBER STATS ROW — REMOVED COMPLETELY -->



</div><!-- end container-fluid -->

<!-- =============================================
     CHARTS — Only Donut
     ❌ Line Chart (API Sales) REMOVED
============================================= -->
<script>
// ✅ Donut Chart — 4 types only (Super Distributor REMOVED)
(function(){
    var ctx = document.getElementById('userDonutChart');
    if (!ctx) return;
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: [
                'Master Distributor',
                'Distributor',
                'Retailer',
                'API User'
            ],
            datasets: [{
                data: [
                    <?= $rtres_users_total['Master Distributor'] ?? 0; ?>,
                    <?= $rtres_users_total['Distributor']        ?? 0; ?>,
                    <?= $rtres_users_total['Retailer']           ?? 0; ?>,
                    <?= $rtres_users_total['API User']           ?? 0; ?>
                ],
                backgroundColor: [
                    '#11998e',
                    '#f7971e',
                    '#667eea',
                    '#eb3349'
                ],
                borderWidth: 3,
                borderColor: '#fff'
            }]
        },
        options: {
            cutoutPercentage: 70,
            legend:   { display: false },
            tooltips: { enabled: true },
            maintainAspectRatio: true
        }
    });
})();
</script>
