<?php
if (session_status() === PHP_SESSION_NONE) session_start();

require_once '../config.php';

set_exception_handler(function (Throwable $e) {
    error_log("Dashboard exception: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
    if (!headers_sent()) header('Content-Type: text/html; charset=utf-8');
    $detail = (defined('DEBUG') && DEBUG) ? '<br><small>' . htmlspecialchars($e->getMessage()) . '</small>' : '';
    echo '<!DOCTYPE html><html lang="fa" dir="rtl"><head><meta charset="UTF-8"><title>خطا</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="p-5"><div class="alert alert-danger">خطا در بارگذاری داشبورد. لطفاً بعداً تلاش کنید یا با پشتیبانی تماس بگیرید.' . $detail . '</div><p><a href="../login.php" class="btn btn-primary">بازگشت به ورود</a></p></body></html>';
    exit;
});

if (!isLoggedIn()) redirect('../login.php');
if (!isRepresentative()) {
    setMessage('دسترسی غیرمجاز', 'error');
    redirect('../login.php');
}

$page_title = 'داشبورد نماینده';

$representative_id = (int)($_SESSION['user_id'] ?? 0);
$panel_id = (int)($_SESSION['panel_id'] ?? 0);

if ($representative_id < 1 || $panel_id < 1) {
    setMessage('اطلاعات نشست نامعتبر است. دوباره وارد شوید.', 'error');
    redirect('../login.php');
}

try {
    if (function_exists('updateRepresentativeActivity')) {
        updateRepresentativeActivity($pdo, $representative_id);
    }
} catch (Exception $e) { }

$stats = ['total_users' => 0, 'active_users' => 0, 'total_traffic' => 0, 'total_limit' => 0];
try {
    $stmt = $pdo->prepare("SELECT COUNT(*) as total_users, SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_users, COALESCE(SUM(total_traffic), 0) as total_traffic, COALESCE(SUM(traffic_limit), 0) as total_limit FROM reseller_users WHERE representative_id = ?");
    $stmt->execute([$representative_id]);
    $row = $stmt->fetch();
    if ($row) $stats = $row;
} catch (Exception $e) { }

$panel = null;
try {
    $stmt = $pdo->prepare("SELECT * FROM panels WHERE id = ?");
    $stmt->execute([$panel_id]);
    $panel = $stmt->fetch();
} catch (Exception $e) { }

if (!$panel) {
    setMessage('خطا: پنل یافت نشد!', 'error');
    redirect('../logout.php');
}

$panel_traffic_info = null;
require_once '../api/XrayAPI.php';
try {
    if (!empty($panel['url']) && !empty($panel['username']) && !empty($panel['password'])) {
        $proxy_config = null;
        if (!empty($panel['proxy_host'])) {
            $proxy_config = [
                'type' => $panel['proxy_type'] ?? 'socks5',
                'host' => $panel['proxy_host'],
                'port' => $panel['proxy_port'] ?? 1080,
                'username' => $panel['proxy_username'] ?? null,
                'password' => $panel['proxy_password'] ?? null,
                'use_on_error' => !empty($panel['use_proxy'])
            ];
        }
        $xrayAPI = new XrayAPI($panel['url'], $panel['username'], $panel['password'], $proxy_config);
        $panel_traffic_info = $xrayAPI->getPanelTotalTraffic();
        if ($panel_traffic_info['total'] == 0) {
            $panel_total_from_db = $pdo->prepare("SELECT SUM(total_traffic) FROM reseller_users WHERE panel_id = ?");
            $panel_total_from_db->execute([$panel_id]);
            $panel_total_from_db = $panel_total_from_db->fetchColumn() ?: 0;
            if ($panel_total_from_db > 0) {
                $panel_traffic_info['total'] = $panel_total_from_db;
                $panel_traffic_info['source'] = 'database';
            } else {
                $panel_traffic_info['source'] = 'api';
            }
        } else {
            $panel_traffic_info['source'] = 'api';
        }
    } else {
        throw new Exception("اطلاعات پنل ناقص است");
    }
} catch (Exception $e) {
    $panel_total_from_db = 0;
    try {
        $stmt = $pdo->prepare("SELECT SUM(total_traffic) FROM reseller_users WHERE panel_id = ?");
        $stmt->execute([$panel_id]);
        $panel_total_from_db = (float)($stmt->fetchColumn() ?: 0);
    } catch (Exception $e2) { }
    $panel_traffic_info = [
        'total' => $panel_total_from_db,
        'source' => 'database',
        'error' => $e->getMessage()
    ];
}

$rep_info = ['traffic_limit' => 0, 'expiry_date' => null, 'used_traffic' => 0, 'wallet_balance' => 0];
try {
    $stmt = $pdo->prepare("SELECT traffic_limit, expiry_date, used_traffic, wallet_balance FROM representatives WHERE id = ?");
    $stmt->execute([$representative_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        $rep_info = array_merge($rep_info, $row);
    }
} catch (Exception $e) {
    // Log error or handle fallback if necessary
    error_log("Could not fetch representative details: " . $e->getMessage());
}

// Fetch data for charts
$user_status_data = ['active' => 0, 'expired' => 0, 'limited' => 0, 'disabled' => 0];
$top_users_data = [];

// Representative initials and code
$rep_name = $_SESSION['username'] ?? 'نماینده';
$rep_initials = mb_substr($rep_name, 0, 1, 'UTF-8');
$rep_customer_code = "REP-" . (1000 + $representative_id);

try {
    // User status distribution
    $stmt = $pdo->prepare("SELECT status, COUNT(*) as count FROM reseller_users WHERE representative_id = ? GROUP BY status");
    $stmt->execute([$representative_id]);
    while ($row = $stmt->fetch()) {
        $user_status_data[$row['status']] = (int)$row['count'];
    }

    // Top 5 users by traffic
    $stmt = $pdo->prepare("SELECT remark, email, total_traffic FROM reseller_users WHERE representative_id = ? ORDER BY total_traffic DESC LIMIT 5");
    $stmt->execute([$representative_id]);
    while ($row = $stmt->fetch()) {
        $top_users_data[] = [
            'label' => $row['remark'] ?: $row['email'],
            'value' => round($row['total_traffic'] / (1024 * 1024 * 1024), 2) // GB
        ];
    }
} catch (Exception $e) {
    error_log("Dashboard chart data fetch failed: " . $e->getMessage());
}
?>

<?php require_once '../includes/header.php'; ?>

<div class="container-fluid">
    <!-- Profile Header Pro -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="profile-card-header-pro">
                <div class="d-md-flex align-items-center justify-content-between p-4">
                    <div class="d-flex align-items-center gap-4">
                        <div class="profile-avatar-large shadow-lg"><?= htmlspecialchars($rep_initials) ?></div>
                        <div class="profile-info-main">
                            <h3 class="text-white mb-1"><?= htmlspecialchars($rep_name) ?></h3>
                            <p class="text-white-50 mb-2"><i class="bi bi-person-badge me-1"></i> حساب نمایندگی فعال</p>
                            <span class="customer-code-pro">
                                <?= $rep_customer_code ?>
                            </span>
                        </div>
                    </div>
                    <div class="mt-4 mt-md-0 d-flex gap-2">
                        <a href="wallet.php" class="btn btn-glass-success">
                            <i class="bi bi-plus-circle me-1"></i> شارژ کیف پول
                        </a>
                        <a href="users.php" class="btn btn-glass-primary">
                            <i class="bi bi-people me-1"></i> لیست کاربران
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>



    <!-- Stat Cards -->
    <div class="row g-4">
        <div class="col-xl-3 col-md-6">
            <div class="stat-card-pro h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <p class="text-muted fw-medium mb-2">کیف پول شما</p>
                            <h4 class="mb-0"><?= number_format($rep_info['wallet_balance'] ?? 0) ?> <small>تومان</small></h4>
                        </div>
                        <div class="stat-icon bg-soft-primary text-primary">
                            <i class="bi bi-wallet2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card-pro h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <p class="text-muted fw-medium mb-2">کل کاربران شما</p>
                            <h4 class="mb-0"><?= (int)($stats['total_users'] ?? 0) ?></h4>
                        </div>
                        <div class="stat-icon bg-soft-success text-success">
                            <i class="bi bi-people"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card-pro h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <p class="text-muted fw-medium mb-2">کاربران فعال</p>
                            <h4 class="mb-0"><?= (int)($stats['active_users'] ?? 0) ?></h4>
                        </div>
                        <div class="stat-icon bg-soft-info text-info">
                            <i class="bi bi-person-check"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card-pro h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <p class="text-muted fw-medium mb-2">ترافیک مصرفی</p>
                            <h4 class="mb-0"><?= number_format(($stats['total_traffic'] ?? 0) / (1024 * 1024 * 1024), 2) ?> <small>GB</small></h4>
                        </div>
                        <div class="stat-icon bg-soft-warning text-warning">
                            <i class="bi bi-bar-chart-line"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mt-2">
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-0">توزیع وضعیت کاربران</h5>
                </div>
                <div class="card-body">
                    <div id="user_status_chart"></div>
                </div>
            </div>
        </div>
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-0">۵ کاربر پرمصرف (GB)</h5>
                </div>
                <div class="card-body">
                    <div id="top_users_chart"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mt-2">
        <div class="col-lg-7">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-0">محدودیت‌های شما</h5>
                </div>
                <div class="card-body">
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="fw-medium">ترافیک کل</span>
                            <span class="text-muted"><?= number_format(($rep_info['used_traffic'] ?? 0) / (1024 * 1024 * 1024), 2) ?> GB / <?= $rep_info['traffic_limit'] > 0 ? number_format($rep_info['traffic_limit'] / (1024 * 1024 * 1024), 2) . ' GB' : 'نامحدود' ?></span>
                        </div>
                        <?php if ($rep_info['traffic_limit'] > 0): ?>
                            <?php $percent = ($rep_info['used_traffic'] ?? 0) / $rep_info['traffic_limit'] * 100; ?>
                            <div class="progress" style="height: 10px;">
                                <div class="progress-bar <?= $percent >= 100 ? 'bg-danger' : ($percent >= 80 ? 'bg-warning' : 'bg-success') ?>" style="width: <?= min($percent, 100) ?>%"></div>
                            </div>
                        <?php else: ?>
                            <div class="progress" style="height: 10px;">
                                <div class="progress-bar bg-success" style="width: 100%"></div>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div>
                        <span class="fw-medium">اعتبار زمانی:</span>
                        <span class="text-muted"><?= $rep_info['expiry_date'] ? date('Y/m/d', strtotime($rep_info['expiry_date'])) : 'نامحدود' ?></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-0">اطلاعات پنل</h5>
                </div>
                <div class="card-body">
                    <p class="mb-2"><strong>نام پنل:</strong> <?= htmlspecialchars($panel['name']) ?></p>
                    <p class="mb-0">
                        <strong>وضعیت:</strong> 
                        <span class="badge bg-<?= $panel['status'] === 'active' ? 'success' : 'danger' ?>"><?= $panel['status'] === 'active' ? 'فعال' : 'غیرفعال' ?></span>
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* استایل‌های حرفه‌ای پروفایل و داشبورد */
.profile-card-header-pro {
    background: linear-gradient(135deg, #1e293b, #0f172a);
    border-radius: 20px;
    position: relative;
    overflow: hidden;
    border: 1px solid rgba(255,255,255,0.05);
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}
.profile-card-header-pro::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -10%;
    width: 400px;
    height: 400px;
    background: radial-gradient(circle, rgba(16, 185, 129, 0.08) 0%, transparent 70%);
    z-index: 0;
}
.profile-avatar-large {
    width: 100px;
    height: 100px;
    border-radius: 28px;
    background: linear-gradient(135deg, var(--accent-primary), #10b981);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2.8rem;
    color: white;
    font-weight: 700;
    border: 5px solid rgba(255,255,255,0.05);
    z-index: 1;
    position: relative;
}
.customer-code-pro {
    background: rgba(255,255,255,0.08);
    color: #10b981;
    padding: 4px 12px;
    border-radius: 8px;
    font-family: 'Vazirmatn', monospace;
    font-weight: 600;
    font-size: 0.9rem;
    border: 1px solid rgba(16, 185, 129, 0.2);
}
.btn-glass-primary {
    background: rgba(59, 130, 246, 0.1);
    color: #60a5fa;
    border: 1px solid rgba(59, 130, 246, 0.2);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 10px 20px;
    font-weight: 600;
    transition: all 0.3s;
}
.btn-glass-success {
    background: rgba(16, 185, 129, 0.1);
    color: #34d399;
    border: 1px solid rgba(16, 185, 129, 0.2);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 10px 20px;
    font-weight: 600;
    transition: all 0.3s;
}
.btn-glass-primary:hover, .btn-glass-success:hover {
    transform: translateY(-2px);
    background: rgba(255,255,255,0.05);
}

.stat-card-pro {
    background-color: var(--bg-card);
    border: 1px solid var(--border-subtle);
    border-radius: var(--radius);
    transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
}
.stat-card-pro:hover {
    transform: translateY(-5px);
    box-shadow: var(--shadow-card-hover);
}
.stat-card-pro .stat-icon {
    width: 48px;
    height: 48px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    font-size: 24px;
}
.bg-soft-primary { background-color: rgba(59,130,246,0.1); }
.text-primary { color: #3b82f6 !important; }
.bg-soft-success { background-color: rgba(34,197,94,0.1); }
.text-success { color: #22c55e !important; }
.bg-soft-info { background-color: rgba(14,165,233,0.1); }
.text-info { color: #0ea5e9 !important; }
.bg-soft-warning { background-color: rgba(249,115,22,0.1); }
.text-warning { color: #f97316 !important; }
</style>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    // User Status Chart
    var statusOptions = {
        series: [
            <?= $user_status_data['active'] ?>,
            <?= $user_status_data['expired'] ?>,
            <?= $user_status_data['limited'] ?>,
            <?= $user_status_data['disabled'] ?>
        ],
        chart: {
            type: 'donut',
            height: 320,
            foreColor: '#adb5bd'
        },
        labels: ['فعال', 'منقضی شده', 'محدود شده', 'غیرفعال'],
        colors: ['#22c55e', '#da3633', '#f97316', '#6c757d'],
        legend: {
            position: 'bottom'
        },
        plotOptions: {
            pie: {
                donut: {
                    size: '70%'
                }
            }
        },
        stroke: {
            show: false
        }
    };

    var statusChart = new ApexCharts(document.querySelector("#user_status_chart"), statusOptions);
    statusChart.render();

    // Top Users Chart
    var topUsersOptions = {
        series: [{
            name: 'مصرف (GB)',
            data: [<?php echo implode(',', array_column($top_users_data, 'value')); ?>]
        }],
        chart: {
            type: 'bar',
            height: 320,
            foreColor: '#adb5bd',
            toolbar: {
                show: false
            }
        },
        plotOptions: {
            bar: {
                borderRadius: 4,
                horizontal: true,
                barHeight: '40%',
            }
        },
        dataLabels: {
            enabled: true,
            formatter: function (val) {
                return val + " GB";
            },
            offsetX: -6,
            style: {
                fontSize: '12px',
                colors: ['#fff']
            }
        },
        colors: ['#3b82f6'],
        xaxis: {
            categories: [<?php echo "'" . implode("','", array_column($top_users_data, 'label')) . "'"; ?>],
        },
        tooltip: {
            theme: 'dark',
            y: {
                formatter: function (val) {
                    return val + " GB";
                }
            }
        }
    };

    var topUsersChart = new ApexCharts(document.querySelector("#top_users_chart"), topUsersOptions);
    topUsersChart.render();
});
</script>

<?php require_once '../includes/footer.php'; ?>
