<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check permissions
/*$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT HasPermission(?, 'agent_performance') as has_permission");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$permission_result = $stmt->get_result()->fetch_assoc();

if (!$permission_result['has_permission']) {
    header('Location: index.php?error=no_permission');
    exit();
}*/

// Get filter parameters
$agent_filter = $_GET['agent'] ?? '';
$branch_filter = $_GET['branch'] ?? '';
$period_filter = $_GET['period'] ?? 'current_month';
$year_filter = $_GET['year'] ?? date('Y');

// Calculate date range based on period
$start_date = '';
$end_date = '';
switch ($period_filter) {
    case 'current_month':
        $start_date = date('Y-m-01');
        $end_date = date('Y-m-t');
        break;
    case 'last_month':
        $start_date = date('Y-m-01', strtotime('last month'));
        $end_date = date('Y-m-t', strtotime('last month'));
        break;
    case 'current_quarter':
        $quarter = ceil(date('n') / 3);
        $start_date = date('Y') . '-' . str_pad(($quarter - 1) * 3 + 1, 2, '0', STR_PAD_LEFT) . '-01';
        $end_date = date('Y-m-t', strtotime($start_date . ' +2 months'));
        break;
    case 'current_year':
        $start_date = $year_filter . '-01-01';
        $end_date = $year_filter . '-12-31';
        break;
    case 'custom':
        $start_date = $_GET['start_date'] ?? date('Y-m-01');
        $end_date = $_GET['end_date'] ?? date('Y-m-t');
        break;
}

// Build filter conditions
$where_conditions = ["u.agent_code IS NOT NULL", "u.status = 'ACTIVE'"];
$params = [];
$param_types = "";

if (!empty($agent_filter)) {
    $where_conditions[] = "u.user_id = ?";
    $params[] = $agent_filter;
    $param_types .= "i";
}

if (!empty($branch_filter)) {
    $where_conditions[] = "u.branch_id = ?";
    $params[] = $branch_filter;
    $param_types .= "i";
}

// Agent performance query
$performance_sql = "SELECT 
    u.user_id,
    u.agent_code,
    u.full_name,
    u.commission_rate,
    u.target_monthly,
    u.hire_date,
    b.branch_name,
    ur.role_name,
    
    -- Policy metrics
    COUNT(DISTINCT p.policy_id) as total_policies,
    COUNT(DISTINCT CASE WHEN p.inception_date BETWEEN ? AND ? THEN p.policy_id END) as period_policies,
    COUNT(DISTINCT CASE WHEN p.status = 'ACTIVE' THEN p.policy_id END) as active_policies,
    COUNT(DISTINCT p.customer_id) as unique_customers,
    
    -- Premium metrics
    COALESCE(SUM(CASE WHEN p.inception_date BETWEEN ? AND ? THEN p.premium_amount END), 0) as period_premium,
    COALESCE(SUM(CASE WHEN p.status = 'ACTIVE' THEN p.premium_amount END), 0) as total_active_premium,
    COALESCE(AVG(CASE WHEN p.inception_date BETWEEN ? AND ? THEN p.premium_amount END), 0) as avg_policy_value,
    
    -- Commission metrics
    COALESCE(SUM(CASE WHEN cc.calculation_period BETWEEN ? AND ? THEN cc.commission_amount END), 0) as period_commission,
    COALESCE(SUM(CASE WHEN cc.status = 'PAID' AND cc.calculation_period BETWEEN ? AND ? THEN cc.commission_amount END), 0) as paid_commission,
    
    -- Renewal metrics
    COUNT(DISTINCT pr.renewal_id) as renewals_processed,
    COUNT(DISTINCT CASE WHEN pr.processed_at BETWEEN ? AND ? THEN pr.renewal_id END) as period_renewals,
    
    -- Claims metrics
    COUNT(DISTINCT c.claim_id) as claims_submitted,
    COUNT(DISTINCT CASE WHEN c.reported_date BETWEEN ? AND ? THEN c.claim_id END) as period_claims,
    
    -- Customer acquisition
    COUNT(DISTINCT CASE WHEN cust.created_at BETWEEN ? AND ? THEN cust.customer_id END) as new_customers,
    
    -- Activity metrics
    COUNT(DISTINCT CASE WHEN q.created_at BETWEEN ? AND ? THEN q.quote_id END) as quotes_generated,
    
    -- Performance scores
    CASE 
        WHEN u.target_monthly > 0 THEN 
            (COALESCE(SUM(CASE WHEN p.inception_date BETWEEN ? AND ? THEN p.premium_amount END), 0) / u.target_monthly) * 100
        ELSE 0 
    END as target_achievement_pct

FROM users u
INNER JOIN user_roles ur ON u.role_id = ur.role_id
LEFT JOIN branches b ON u.branch_id = b.branch_id
LEFT JOIN policies p ON u.user_id = p.agent_id
LEFT JOIN commission_calculations cc ON u.user_id = cc.agent_id
LEFT JOIN policy_renewals pr ON p.policy_id = pr.policy_id
LEFT JOIN claims c ON p.policy_id = c.policy_id
LEFT JOIN customers cust ON u.user_id = cust.referring_agent_id
LEFT JOIN quotes q ON u.user_id = q.agent_id
WHERE " . implode(" AND ", $where_conditions) . "
GROUP BY u.user_id, u.agent_code, u.full_name, u.commission_rate, u.target_monthly, 
         u.hire_date, b.branch_name, ur.role_name
ORDER BY period_premium DESC";

$stmt = $conn->prepare($performance_sql);
// Bind date parameters multiple times for different metrics
$date_params = array_merge(
    [$start_date, $end_date], // period_policies
    [$start_date, $end_date], // period_premium
    [$start_date, $end_date], // avg_policy_value
    [$start_date, $end_date], // period_commission
    [$start_date, $end_date], // paid_commission
    [$start_date, $end_date], // period_renewals
    [$start_date, $end_date], // period_claims
    [$start_date, $end_date], // new_customers
    [$start_date, $end_date], // quotes_generated
    [$start_date, $end_date]  // target_achievement_pct
);
$all_params = array_merge($date_params, $params);
$all_param_types = str_repeat("ss", 10) . $param_types;

if (!empty($all_params)) {
    $stmt->bind_param($all_param_types, ...$all_params);
}
$stmt->execute();
$performance_result = $stmt->get_result();

// Get summary statistics
$summary_sql = "SELECT 
    COUNT(DISTINCT u.user_id) as total_agents,
    COUNT(DISTINCT CASE WHEN p.inception_date BETWEEN ? AND ? THEN p.policy_id END) as total_period_policies,
    COALESCE(SUM(CASE WHEN p.inception_date BETWEEN ? AND ? THEN p.premium_amount END), 0) as total_period_premium,
    COALESCE(SUM(CASE WHEN cc.calculation_period BETWEEN ? AND ? THEN cc.commission_amount END), 0) as total_period_commission,
    COALESCE(AVG(CASE WHEN p.inception_date BETWEEN ? AND ? THEN p.premium_amount END), 0) as avg_policy_value,
    COUNT(DISTINCT CASE WHEN cust.created_at BETWEEN ? AND ? THEN cust.customer_id END) as total_new_customers
FROM users u
LEFT JOIN policies p ON u.user_id = p.agent_id
LEFT JOIN commission_calculations cc ON u.user_id = cc.agent_id
LEFT JOIN customers cust ON u.user_id = cust.referring_agent_id
WHERE u.agent_code IS NOT NULL AND u.status = 'ACTIVE'";

$summary_stmt = $conn->prepare($summary_sql);
$summary_stmt->bind_param("ssssssssss", $start_date, $end_date, $start_date, $end_date, 
                         $start_date, $end_date, $start_date, $end_date, $start_date, $end_date);
$summary_stmt->execute();
$summary = $summary_stmt->get_result()->fetch_assoc();

// Get top performers
$top_performers_sql = "SELECT 
    u.user_id,
    u.full_name,
    u.agent_code,
    b.branch_name,
    COALESCE(SUM(CASE WHEN p.inception_date BETWEEN ? AND ? THEN p.premium_amount END), 0) as period_premium,
    COUNT(DISTINCT CASE WHEN p.inception_date BETWEEN ? AND ? THEN p.policy_id END) as period_policies
FROM users u
LEFT JOIN branches b ON u.branch_id = b.branch_id
LEFT JOIN policies p ON u.user_id = p.agent_id
WHERE u.agent_code IS NOT NULL AND u.status = 'ACTIVE'
GROUP BY u.user_id, u.full_name, u.agent_code, b.branch_name
HAVING period_premium > 0
ORDER BY period_premium DESC
LIMIT 5";

$top_stmt = $conn->prepare($top_performers_sql);
$top_stmt->bind_param("ssss", $start_date, $end_date, $start_date, $end_date);
$top_stmt->execute();
$top_performers = $top_stmt->get_result();

// Get monthly trends (last 12 months)
$trends_sql = "SELECT 
    DATE_FORMAT(p.inception_date, '%Y-%m') as month,
    COUNT(DISTINCT p.policy_id) as policies,
    COALESCE(SUM(p.premium_amount), 0) as premium,
    COUNT(DISTINCT p.agent_id) as active_agents
FROM policies p
INNER JOIN users u ON p.agent_id = u.user_id
WHERE p.inception_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
    AND u.agent_code IS NOT NULL
GROUP BY DATE_FORMAT(p.inception_date, '%Y-%m')
ORDER BY month";

$trends_result = $conn->query($trends_sql);
$trends_data = [];
while ($row = $trends_result->fetch_assoc()) {
    $trends_data[] = $row;
}

// Get branches for filter
$branches_sql = "SELECT branch_id, branch_name FROM branches WHERE is_active = 1 ORDER BY branch_name";
$branches_result = $conn->query($branches_sql);

// Get agents for filter
$agents_sql = "SELECT user_id, full_name, agent_code FROM users WHERE agent_code IS NOT NULL AND status = 'ACTIVE' ORDER BY full_name";
$agents_result = $conn->query($agents_sql);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Agent Performance - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <style>
        .performance-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
        }
        .performance-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        }
        .metric-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            text-align: center;
        }
        .metric-value {
            font-size: 2rem;
            font-weight: 700;
            margin: 10px 0;
        }
        .metric-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        .performance-indicator {
            width: 100%;
            height: 10px;
            border-radius: 5px;
            overflow: hidden;
            background: #e9ecef;
        }
        .performance-bar {
            height: 100%;
            transition: width 0.5s ease;
        }
        .top-performer-card {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
        }
        .rank-badge {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
        }
        .chart-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        .filter-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .performance-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        .performance-excellent { background: #d4edda; color: #155724; }
        .performance-good { background: #d1ecf1; color: #0c5460; }
        .performance-average { background: #fff3cd; color: #856404; }
        .performance-poor { background: #f8d7da; color: #721c24; }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Agent Performance Analytics</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_agents.php">Agents</a></li>
                                        <li class="breadcrumb-item active">Performance</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="filter-card">
                                <form method="GET" class="row g-3">
                                    <div class="col-md-3">
                                        <label class="form-label">Agent</label>
                                        <select class="form-select" name="agent">
                                            <option value="">All Agents</option>
                                            <?php while($agent = $agents_result->fetch_assoc()): ?>
                                                <option value="<?php echo $agent['user_id']; ?>" 
                                                        <?php echo $agent_filter == $agent['user_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($agent['full_name']); ?> 
                                                    (<?php echo htmlspecialchars($agent['agent_code']); ?>)
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Branch</label>
                                        <select class="form-select" name="branch">
                                            <option value="">All Branches</option>
                                            <?php while($branch = $branches_result->fetch_assoc()): ?>
                                                <option value="<?php echo $branch['branch_id']; ?>" 
                                                        <?php echo $branch_filter == $branch['branch_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($branch['branch_name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Period</label>
                                        <select class="form-select" name="period" id="periodSelect">
                                            <option value="current_month" <?php echo $period_filter == 'current_month' ? 'selected' : ''; ?>>Current Month</option>
                                            <option value="last_month" <?php echo $period_filter == 'last_month' ? 'selected' : ''; ?>>Last Month</option>
                                            <option value="current_quarter" <?php echo $period_filter == 'current_quarter' ? 'selected' : ''; ?>>Current Quarter</option>
                                            <option value="current_year" <?php echo $period_filter == 'current_year' ? 'selected' : ''; ?>>Current Year</option>
                                            <option value="custom" <?php echo $period_filter == 'custom' ? 'selected' : ''; ?>>Custom Range</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2" id="customDateRange" style="display: <?php echo $period_filter == 'custom' ? 'block' : 'none'; ?>;">
                                        <label class="form-label">Start Date</label>
                                        <input type="date" class="form-control" name="start_date" 
                                               value="<?php echo htmlspecialchars($_GET['start_date'] ?? ''); ?>">
                                    </div>
                                    <div class="col-md-2" id="customDateRange2" style="display: <?php echo $period_filter == 'custom' ? 'block' : 'none'; ?>;">
                                        <label class="form-label">End Date</label>
                                        <input type="date" class="form-control" name="end_date" 
                                               value="<?php echo htmlspecialchars($_GET['end_date'] ?? ''); ?>">
                                    </div>
                                    <div class="col-md-1 d-flex align-items-end">
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-search-line"></i>
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Statistics -->
                    <div class="row mb-4">
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="metric-card bg-primary">
                                <div class="metric-label">Total Agents</div>
                                <div class="metric-value"><?php echo number_format($summary['total_agents']); ?></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="metric-card bg-success">
                                <div class="metric-label">Policies Sold</div>
                                <div class="metric-value"><?php echo number_format($summary['total_period_policies']); ?></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="metric-card bg-info">
                                <div class="metric-label">Premium Generated</div>
                                <div class="metric-value">
                                    <small>KSH</small> <?php echo number_format($summary['total_period_premium'] / 1000000, 1); ?>M
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="metric-card bg-warning">
                                <div class="metric-label">Total Commission</div>
                                <div class="metric-value">
                                    <small>KSH</small> <?php echo number_format($summary['total_period_commission'] / 1000, 0); ?>K
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="metric-card bg-secondary">
                                <div class="metric-label">Avg Policy Value</div>
                                <div class="metric-value">
                                    <small>KSH</small> <?php echo number_format($summary['avg_policy_value'] / 1000, 0); ?>K
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="metric-card bg-dark">
                                <div class="metric-label">New Customers</div>
                                <div class="metric-value"><?php echo number_format($summary['total_new_customers']); ?></div>
                            </div>
                        </div>
                    </div>

                    <!-- Top Performers and Charts -->
                    <div class="row mb-4">
                        <div class="col-xl-4 mb-4">
                            <div class="performance-card h-100">
                                <div class="card-header border-0 pb-0">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-trophy-line me-2 text-warning"></i>Top Performers
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php 
                                    $rank = 1;
                                    while($performer = $top_performers->fetch_assoc()): 
                                        $card_class = $rank == 1 ? 'bg-warning' : ($rank == 2 ? 'bg-success' : 'bg-info');
                                    ?>
                                        <div class="top-performer-card <?php echo $card_class; ?>">
                                            <div class="d-flex align-items-center">
                                                <div class="rank-badge me-3">
                                                    <?php echo $rank; ?>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-1 text-white">
                                                        <?php echo htmlspecialchars($performer['full_name']); ?>
                                                    </h6>
                                                    <p class="mb-1 text-white-50 small">
                                                        Code: <?php echo htmlspecialchars($performer['agent_code']); ?> | 
                                                        <?php echo htmlspecialchars($performer['branch_name'] ?: 'Head Office'); ?>
                                                    </p>
                                                    <div class="d-flex justify-content-between text-white">
                                                        <span>KSH <?php echo number_format($performer['period_premium'], 2); ?></span>
                                                        <span><?php echo $performer['period_policies']; ?> policies</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php 
                                    $rank++;
                                    endwhile; 
                                    ?>
                                    
                                    <div class="text-center mt-3">
                                        <a href="leaderboards.php" class="btn btn-soft-primary btn-sm">
                                            <i class="ri-list-check me-1"></i>View Full Leaderboard
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-8 mb-4">
                            <div class="chart-container">
                                <h5 class="mb-3">
                                    <i class="ri-line-chart-line me-2"></i>Performance Trends (Last 12 Months)
                                </h5>
                                <div id="performanceTrends" style="height: 350px;"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Agent Performance Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="performance-card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-user-star-line me-2"></i>Agent Performance Details
                                    </h5>
                                    <div class="dropdown">
                                        <button class="btn btn-soft-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                            <i class="ri-download-line me-1"></i> Export
                                        </button>
                                        <ul class="dropdown-menu">
                                            <li><a class="dropdown-item" href="#" onclick="exportTable('csv')">CSV</a></li>
                                            <li><a class="dropdown-item" href="#" onclick="exportTable('excel')">Excel</a></li>
                                            <li><a class="dropdown-item" href="#" onclick="exportTable('pdf')">PDF</a></li>
                                        </ul>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="performanceTable" class="table table-hover align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Agent</th>
                                                    <th>Branch</th>
                                                    <th>Policies</th>
                                                    <th>Premium</th>
                                                    <th>Commission</th>
                                                    <th>Target Achievement</th>
                                                    <th>Customers</th>
                                                    <th>Performance</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while($agent = $performance_result->fetch_assoc()): 
                                                    // Determine performance level
                                                    $achievement = $agent['target_achievement_pct'];
                                                    if ($achievement >= 100) {
                                                        $perf_class = 'performance-excellent';
                                                        $perf_text = 'Excellent';
                                                    } elseif ($achievement >= 80) {
                                                        $perf_class = 'performance-good';
                                                        $perf_text = 'Good';
                                                    } elseif ($achievement >= 60) {
                                                        $perf_class = 'performance-average';
                                                        $perf_text = 'Average';
                                                    } else {
                                                        $perf_class = 'performance-poor';
                                                        $perf_text = 'Needs Improvement';
                                                    }
                                                ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="avatar-sm bg-primary text-white rounded-circle me-2 d-flex align-items-center justify-content-center">
                                                                <?php echo strtoupper(substr($agent['full_name'], 0, 1)); ?>
                                                            </div>
                                                            <div>
                                                                <h6 class="mb-1">
                                                                    <a href="view_agent.php?id=<?php echo $agent['user_id']; ?>" 
                                                                       class="text-decoration-none">
                                                                        <?php echo htmlspecialchars($agent['full_name']); ?>
                                                                    </a>
                                                                </h6>
                                                                <small class="text-muted">
                                                                    Code: <?php echo htmlspecialchars($agent['agent_code']); ?>
                                                                </small>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-soft-info text-info">
                                                            <?php echo htmlspecialchars($agent['branch_name'] ?: 'Head Office'); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <strong class="text-primary"><?php echo number_format($agent['period_policies']); ?></strong>
                                                            <small class="text-muted d-block">
                                                                Total: <?php echo number_format($agent['total_policies']); ?>
                                                            </small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <strong class="text-success">
                                                                KSH <?php echo number_format($agent['period_premium'], 2); ?>
                                                            </strong>
                                                            <small class="text-muted d-block">
                                                                Avg: KSH <?php echo number_format($agent['avg_policy_value'], 2); ?>
                                                            </small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <strong class="text-warning">
                                                                KSH <?php echo number_format($agent['period_commission'], 2); ?>
                                                            </strong>
                                                            <small class="text-muted d-block">
                                                                Rate: <?php echo $agent['commission_rate']; ?>%
                                                            </small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php if($agent['target_monthly'] > 0): ?>
                                                            <div class="performance-indicator mb-1">
                                                                <div class="performance-bar bg-<?php echo $achievement >= 100 ? 'success' : ($achievement >= 80 ? 'warning' : 'danger'); ?>" 
                                                                     style="width: <?php echo min($achievement, 100); ?>%;"></div>
                                                            </div>
                                                            <small class="text-muted">
                                                                <?php echo number_format($achievement, 1); ?>% 
                                                                (Target: KSH <?php echo number_format($agent['target_monthly'], 0); ?>)
                                                            </small>
                                                        <?php else: ?>
                                                            <span class="text-muted">No target set</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <strong><?php echo number_format($agent['unique_customers']); ?></strong>
                                                            <small class="text-muted d-block">
                                                                New: <?php echo number_format($agent['new_customers']); ?>
                                                            </small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="performance-badge <?php echo $perf_class; ?>">
                                                            <?php echo $perf_text; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="d-flex gap-1">
                                                            <a href="view_agent.php?id=<?php echo $agent['user_id']; ?>" 
                                                               class="btn btn-sm btn-soft-primary" 
                                                               data-bs-toggle="tooltip" title="View Details">
                                                                <i class="ri-eye-line"></i>
                                                            </a>
                                                            <a href="agent_detailed_report.php?id=<?php echo $agent['user_id']; ?>&period=<?php echo $period_filter; ?>" 
                                                               class="btn btn-sm btn-soft-info" 
                                                               data-bs-toggle="tooltip" title="Detailed Report">
                                                                <i class="ri-file-chart-line"></i>
                                                            </a>
                                                            <button type="button" class="btn btn-sm btn-soft-success" 
                                                                    data-bs-toggle="tooltip" title="Send Feedback"
                                                                    onclick="sendFeedback(<?php echo $agent['user_id']; ?>)">
                                                                <i class="ri-message-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Send Feedback Modal -->
    <div class="modal fade" id="feedbackModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Send Performance Feedback</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="feedbackForm">
                    <div class="modal-body">
                        <input type="hidden" id="feedbackAgentId" name="agent_id">
                        <div class="mb-3">
                            <label class="form-label">Feedback Type</label>
                            <select class="form-select" name="feedback_type" required>
                                <option value="">Select Type</option>
                                <option value="RECOGNITION">Recognition/Praise</option>
                                <option value="IMPROVEMENT">Areas for Improvement</option>
                                <option value="COACHING">Coaching/Training</option>
                                <option value="GOAL_SETTING">Goal Setting</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Subject</label>
                            <input type="text" class="form-control" name="subject" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Feedback Message</label>
                            <textarea class="form-control" name="message" rows="4" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Send Feedback</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
    $(document).ready(function() {
        // Initialize DataTable
        $('#performanceTable').DataTable({
            responsive: true,
            pageLength: 25,
            order: [[3, 'desc']], // Order by premium descending
            columnDefs: [
                { orderable: false, targets: [8] } // Actions column
            ]
        });

        // Period change handler
        $('#periodSelect').change(function() {
            const customFields = ['#customDateRange', '#customDateRange2'];
            if ($(this).val() === 'custom') {
                customFields.forEach(field => $(field).show());
            } else {
                customFields.forEach(field => $(field).hide());
            }
        });

        // Initialize tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });

        // Performance trends chart
        renderPerformanceChart();
        
        // Feedback form submission
        $('#feedbackForm').on('submit', function(e) {
            e.preventDefault();
            
            $.ajax({
                url: 'ajax/send_performance_feedback.php',
                method: 'POST',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        $('#feedbackModal').modal('hide');
                        Swal.fire({
                            icon: 'success',
                            title: 'Feedback Sent',
                            text: 'Your feedback has been sent successfully.',
                            timer: 2000,
                            showConfirmButton: false
                        });
                        $('#feedbackForm')[0].reset();
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message || 'Failed to send feedback.'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while sending feedback.'
                    });
                }
            });
        });
    });

    function renderPerformanceChart() {
        const trendsData = <?php echo json_encode($trends_data); ?>;
        
        const options = {
            series: [{
                name: 'Premium (KSH)',
                type: 'column',
                data: trendsData.map(item => parseFloat(item.premium))
            }, {
                name: 'Policies',
                type: 'line',
                data: trendsData.map(item => parseInt(item.policies))
            }],
            chart: {
                height: 350,
                type: 'line',
                toolbar: {
                    show: true
                }
            },
            stroke: {
                width: [0, 4]
            },
            plotOptions: {
                bar: {
                    columnWidth: '50%'
                }
            },
            colors: ['#667eea', '#764ba2'],
            dataLabels: {
                enabled: true,
                enabledOnSeries: [1]
            },
            labels: trendsData.map(item => {
                const date = new Date(item.month + '-01');
                return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
            }),
            xaxis: {
                type: 'category'
            },
            yaxis: [{
                title: {
                    text: 'Premium (KSH)',
                },
                labels: {
                    formatter: function (val) {
                        return 'KSH ' + (val / 1000000).toFixed(1) + 'M';
                    }
                }
            }, {
                opposite: true,
                title: {
                    text: 'Number of Policies'
                }
            }],
            tooltip: {
                shared: true,
                intersect: false,
                y: [{
                    formatter: function (y) {
                        if(typeof y !== "undefined") {
                            return "KSH " + y.toLocaleString();
                        }
                        return y;
                    }
                }, {
                    formatter: function (y) {
                        if(typeof y !== "undefined") {
                            return y + " policies";
                        }
                        return y;
                    }
                }]
            }
        };

        const chart = new ApexCharts(document.querySelector("#performanceTrends"), options);
        chart.render();
    }

    // Export functions
    function exportTable(format) {
        const table = $('#performanceTable').DataTable();
        
        switch(format) {
            case 'csv':
                // Create CSV export
                let csvContent = "data:text/csv;charset=utf-8,";
                const headers = ["Agent", "Branch", "Policies", "Premium", "Commission", "Target Achievement", "Customers", "Performance"];
                csvContent += headers.join(",") + "\n";
                
                table.rows().data().each(function(row) {
                    // Extract data from HTML elements
                    const agentName = $(row[0]).find('h6 a').text().trim();
                    const branch = $(row[1]).find('.badge').text().trim();
                    const policies = $(row[2]).find('strong').text().trim();
                    const premium = $(row[3]).find('strong').text().trim();
                    const commission = $(row[4]).find('strong').text().trim();
                    const achievement = $(row[5]).find('small').text().trim();
                    const customers = $(row[6]).find('strong').text().trim();
                    const performance = $(row[7]).find('.performance-badge').text().trim();
                    
                    const rowData = [agentName, branch, policies, premium, commission, achievement, customers, performance];
                    csvContent += rowData.map(field => `"${field}"`).join(",") + "\n";
                });
                
                const encodedUri = encodeURI(csvContent);
                const link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", "agent_performance_report.csv");
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                break;
                
            case 'excel':
                // For Excel export, you'd typically use a library like SheetJS
                Swal.fire({
                    icon: 'info',
                    title: 'Excel Export',
                    text: 'Excel export functionality would be implemented with SheetJS library.'
                });
                break;
                
            case 'pdf':
                // For PDF export, you'd typically use a library like jsPDF
                Swal.fire({
                    icon: 'info',
                    title: 'PDF Export',
                    text: 'PDF export functionality would be implemented with jsPDF library.'
                });
                break;
        }
    }

    // Send feedback function
    function sendFeedback(agentId) {
        $('#feedbackAgentId').val(agentId);
        $('#feedbackModal').modal('show');
    }

    // Auto-refresh data every 5 minutes
    setInterval(function() {
        if (document.visibilityState === 'visible') {
            location.reload();
        }
    }, 300000); // 5 minutes
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>