<?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(?, 'agents_view') 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 agent ID from URL
$agent_id = $_GET['id'] ?? 0;
if (!$agent_id) {
    header('Location: list_agents.php');
    exit();
}

// Get agent details
$agent_sql = "SELECT 
    u.*,
    ur.role_name,
    b.branch_name,
    b.branch_code,
    supervisor.full_name as supervisor_name,
    supervisor.agent_code as supervisor_code
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 users supervisor ON u.supervisor_id = supervisor.user_id
WHERE u.user_id = ? AND u.agent_code IS NOT NULL";

$agent_stmt = $conn->prepare($agent_sql);
$agent_stmt->bind_param("i", $agent_id);
$agent_stmt->execute();
$agent = $agent_stmt->get_result()->fetch_assoc();

if (!$agent) {
    header('Location: list_agents.php?error=agent_not_found');
    exit();
}

// Get performance metrics (last 12 months)
$performance_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.customer_id) as customers
FROM policies p
WHERE p.agent_id = ? 
    AND p.inception_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
GROUP BY DATE_FORMAT(p.inception_date, '%Y-%m')
ORDER BY month";

$performance_stmt = $conn->prepare($performance_sql);
$performance_stmt->bind_param("i", $agent_id);
$performance_stmt->execute();
$performance_data = [];
while ($row = $performance_stmt->get_result()->fetch_assoc()) {
    $performance_data[] = $row;
}

// Get overall statistics
$stats_sql = "SELECT 
    COUNT(DISTINCT p.policy_id) as total_policies,
    COUNT(DISTINCT CASE WHEN p.status = 'ACTIVE' THEN p.policy_id END) as active_policies,
    COUNT(DISTINCT p.customer_id) as total_customers,
    COALESCE(SUM(CASE WHEN p.status = 'ACTIVE' THEN p.premium_amount END), 0) as total_premium,
    COALESCE(AVG(p.premium_amount), 0) as avg_policy_value,
    
    -- Current month stats
    COUNT(DISTINCT CASE WHEN MONTH(p.inception_date) = MONTH(CURRENT_DATE()) AND YEAR(p.inception_date) = YEAR(CURRENT_DATE()) THEN p.policy_id END) as monthly_policies,
    COALESCE(SUM(CASE WHEN MONTH(p.inception_date) = MONTH(CURRENT_DATE()) AND YEAR(p.inception_date) = YEAR(CURRENT_DATE()) THEN p.premium_amount END), 0) as monthly_premium,
    
    -- Commission stats
    COALESCE(SUM(cc.commission_amount), 0) as total_commission,
    COALESCE(SUM(CASE WHEN cc.status = 'PAID' THEN cc.commission_amount END), 0) as paid_commission,
    
    -- Claims stats
    COUNT(DISTINCT c.claim_id) as total_claims,
    COALESCE(SUM(c.claimed_amount), 0) as total_claimed_amount
    
FROM policies p
LEFT JOIN commission_calculations cc ON p.policy_id = cc.policy_id
LEFT JOIN claims c ON p.policy_id = c.policy_id
WHERE p.agent_id = ?";

$stats_stmt = $conn->prepare($stats_sql);
$stats_stmt->bind_param("i", $agent_id);
$stats_stmt->execute();
$stats = $stats_stmt->get_result()->fetch_assoc();

// Get recent activities
$activities_sql = "SELECT 
    al.action,
    al.module,
    al.logged_at,
    al.new_values
FROM activity_log al
WHERE al.user_id = ?
ORDER BY al.logged_at DESC
LIMIT 10";

$activities_stmt = $conn->prepare($activities_sql);
$activities_stmt->bind_param("i", $agent_id);
$activities_stmt->execute();
$activities_result = $activities_stmt->get_result();

// Get recent policies
$recent_policies_sql = "SELECT 
    p.policy_number,
    p.inception_date,
    p.premium_amount,
    p.status,
    c.first_name,
    c.last_name,
    ip.product_name
FROM policies p
LEFT JOIN customers c ON p.customer_id = c.customer_id
LEFT JOIN insurance_products ip ON p.product_id = ip.product_id
WHERE p.agent_id = ?
ORDER BY p.created_at DESC
LIMIT 5";

$recent_policies_stmt = $conn->prepare($recent_policies_sql);
$recent_policies_stmt->bind_param("i", $agent_id);
$recent_policies_stmt->execute();
$recent_policies_result = $recent_policies_stmt->get_result();

$conn->close();

// Calculate target achievement
$target_achievement = $agent['target_monthly'] > 0 ? 
    round(($stats['monthly_premium'] / $agent['target_monthly']) * 100, 1) : 0;
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Agent Details - 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">
    <style>
        .agent-profile-card {
            border: none;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .agent-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px 30px;
            text-align: center;
        }
        .agent-avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 3rem;
            font-weight: 700;
            margin: 0 auto 20px;
            border: 4px solid rgba(255,255,255,0.3);
        }
        .info-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 20px;
        }
        .metric-box {
            text-align: center;
            padding: 20px;
            border-radius: 15px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            margin-bottom: 15px;
        }
        .metric-value {
            font-size: 2rem;
            font-weight: 700;
            color: #495057;
            margin-bottom: 5px;
        }
        .metric-label {
            font-size: 0.9rem;
            color: #6c757d;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .status-badge {
            font-size: 0.8rem;
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: 600;
        }
        .achievement-bar {
            height: 12px;
            border-radius: 6px;
            overflow: hidden;
            background: #e9ecef;
            margin: 10px 0;
        }
        .achievement-fill {
            height: 100%;
            transition: width 0.5s ease;
            border-radius: 6px;
        }
        .activity-item {
            padding: 15px;
            border-left: 4px solid #e9ecef;
            margin-bottom: 10px;
            background: #f8f9fa;
            border-radius: 0 10px 10px 0;
        }
        .activity-item.success { border-color: #28a745; }
        .activity-item.info { border-color: #17a2b8; }
        .activity-item.warning { border-color: #ffc107; }
        .activity-item.danger { border-color: #dc3545; }
    </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 Profile</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">Profile</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Agent Profile Card -->
                        <div class="col-xl-4 col-lg-5">
                            <div class="agent-profile-card">
                                <div class="agent-header">
                                    <div class="agent-avatar">
                                        <?php echo strtoupper(substr($agent['full_name'], 0, 1)); ?>
                                    </div>
                                    <h4 class="mb-2"><?php echo htmlspecialchars($agent['full_name']); ?></h4>
                                    <p class="mb-3 opacity-75">
                                        Agent Code: <?php echo htmlspecialchars($agent['agent_code']); ?>
                                    </p>
                                    <?php 
                                    $status_class = match($agent['status']) {
                                        'ACTIVE' => 'bg-success',
                                        'INACTIVE' => 'bg-secondary',
                                        'SUSPENDED' => 'bg-danger',
                                        'PENDING' => 'bg-warning',
                                        default => 'bg-info'
                                    };
                                    ?>
                                    <span class="status-badge <?php echo $status_class; ?> text-white">
                                        <?php echo ucfirst(strtolower($agent['status'])); ?>
                                    </span>
                                </div>
                                
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-6">
                                            <div class="metric-box">
                                                <div class="metric-value"><?php echo number_format($stats['total_policies']); ?></div>
                                                <div class="metric-label">Total Policies</div>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="metric-box">
                                                <div class="metric-value"><?php echo number_format($stats['total_customers']); ?></div>
                                                <div class="metric-label">Customers</div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Contact Information -->
                                    <h6 class="mb-3 mt-4">Contact Information</h6>
                                    <div class="table-responsive">
                                        <table class="table table-borderless table-sm">
                                            <tbody>
                                                <tr>
                                                    <td><i class="ri-mail-line text-muted me-2"></i>Email:</td>
                                                    <td><a href="mailto:<?php echo $agent['email']; ?>"><?php echo htmlspecialchars($agent['email']); ?></a></td>
                                                </tr>
                                                <?php if($agent['phone_number']): ?>
                                                <tr>
                                                    <td><i class="ri-phone-line text-muted me-2"></i>Phone:</td>
                                                    <td><a href="tel:<?php echo $agent['phone_number']; ?>"><?php echo htmlspecialchars($agent['phone_number']); ?></a></td>
                                                </tr>
                                                <?php endif; ?>
                                                <tr>
                                                    <td><i class="ri-building-line text-muted me-2"></i>Branch:</td>
                                                    <td><?php echo htmlspecialchars($agent['branch_name'] ?: 'Head Office'); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><i class="ri-shield-line text-muted me-2"></i>Role:</td>
                                                    <td><?php echo htmlspecialchars($agent['role_name']); ?></td>
                                                </tr>
                                                <?php if($agent['supervisor_name']): ?>
                                                <tr>
                                                    <td><i class="ri-user-line text-muted me-2"></i>Supervisor:</td>
                                                    <td><?php echo htmlspecialchars($agent['supervisor_name']); ?></td>
                                                </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Professional Details -->
                                    <h6 class="mb-3 mt-4">Professional Details</h6>
                                    <div class="table-responsive">
                                        <table class="table table-borderless table-sm">
                                            <tbody>
                                                <tr>
                                                    <td><i class="ri-calendar-line text-muted me-2"></i>Hire Date:</td>
                                                    <td><?php echo $agent['hire_date'] ? date('M j, Y', strtotime($agent['hire_date'])) : 'N/A'; ?></td>
                                                </tr>
                                                <?php if($agent['license_number']): ?>
                                                <tr>
                                                    <td><i class="ri-award-line text-muted me-2"></i>License:</td>
                                                    <td><?php echo htmlspecialchars($agent['license_number']); ?></td>
                                                </tr>
                                                <?php endif; ?>
                                                <tr>
                                                    <td><i class="ri-percent-line text-muted me-2"></i>Commission:</td>
                                                    <td><?php echo $agent['commission_rate']; ?>%</td>
                                                </tr>
                                                <tr>
                                                    <td><i class="ri-time-line text-muted me-2"></i>Last Login:</td>
                                                    <td><?php echo $agent['last_login'] ? date('M j, Y H:i', strtotime($agent['last_login'])) : 'Never'; ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Action Buttons -->
                                    <div class="d-grid gap-2 mt-4">
                                        <a href="edit_agent.php?id=<?php echo $agent['user_id']; ?>" class="btn btn-primary">
                                            <i class="ri-edit-line me-2"></i>Edit Profile
                                        </a>
                                        <button type="button" class="btn btn-success" onclick="sendMessage(<?php echo $agent['user_id']; ?>)">
                                            <i class="ri-message-line me-2"></i>Send Message
                                        </button>
                                        <a href="agent_detailed_report.php?id=<?php echo $agent['user_id']; ?>" class="btn btn-info">
                                            <i class="ri-file-chart-line me-2"></i>Detailed Report
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Performance and Details -->
                        <div class="col-xl-8 col-lg-7">
                            
                            <!-- Target Achievement -->
                            <div class="info-card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-target-line me-2"></i>Monthly Target Achievement
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-8">
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Target: KSH <?php echo number_format($agent['target_monthly']); ?></span>
                                                <span>Achieved: KSH <?php echo number_format($stats['monthly_premium']); ?></span>
                                            </div>
                                            <div class="achievement-bar">
                                                <div class="achievement-fill bg-<?php echo $target_achievement >= 100 ? 'success' : ($target_achievement >= 80 ? 'warning' : 'danger'); ?>" 
                                                     style="width: <?php echo min($target_achievement, 100); ?>%;"></div>
                                            </div>
                                            <small class="text-muted">
                                                <?php echo $target_achievement; ?>% of monthly target achieved
                                            </small>
                                        </div>
                                        <div class="col-md-4 text-center">
                                            <div class="metric-value text-<?php echo $target_achievement >= 100 ? 'success' : ($target_achievement >= 80 ? 'warning' : 'danger'); ?>">
                                                <?php echo $target_achievement; ?>%
                                            </div>
                                            <div class="metric-label">Achievement</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Performance Statistics -->
                            <div class="row mb-4">
                                <div class="col-md-3 col-6">
                                    <div class="info-card text-center">
                                        <div class="card-body">
                                            <div class="metric-value text-primary"><?php echo number_format($stats['monthly_policies']); ?></div>
                                            <div class="metric-label">This Month</div>
                                            <small class="text-muted">Policies</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 col-6">
                                    <div class="info-card text-center">
                                        <div class="card-body">
                                            <div class="metric-value text-success">KSH <?php echo number_format($stats['monthly_premium'] / 1000, 0); ?>K</div>
                                            <div class="metric-label">Premium</div>
                                            <small class="text-muted">This Month</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 col-6">
                                    <div class="info-card text-center">
                                        <div class="card-body">
                                            <div class="metric-value text-info">KSH <?php echo number_format($stats['avg_policy_value'] / 1000, 0); ?>K</div>
                                            <div class="metric-label">Average</div>
                                            <small class="text-muted">Policy Value</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 col-6">
                                    <div class="info-card text-center">
                                        <div class="card-body">
                                            <div class="metric-value text-warning">KSH <?php echo number_format($stats['total_commission'] / 1000, 0); ?>K</div>
                                            <div class="metric-label">Total</div>
                                            <small class="text-muted">Commission</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Performance Chart -->
                            <div class="info-card mb-4">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-line-chart-line me-2"></i>Performance Trend (Last 12 Months)
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div id="performanceChart" style="height: 300px;"></div>
                                </div>
                            </div>
                            
                            <!-- Recent Policies and Activities -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="info-card">
                                        <div class="card-header">
                                            <h6 class="card-title mb-0">
                                                <i class="ri-file-list-line me-2"></i>Recent Policies
                                            </h6>
                                        </div>
                                        <div class="card-body">
                                            <?php while($policy = $recent_policies_result->fetch_assoc()): ?>
                                                <div class="d-flex justify-content-between align-items-center mb-3 pb-2 border-bottom">
                                                    <div>
                                                        <h6 class="mb-1"><?php echo htmlspecialchars($policy['policy_number']); ?></h6>
                                                        <small class="text-muted">
                                                            <?php echo htmlspecialchars($policy['first_name'] . ' ' . $policy['last_name']); ?>
                                                        </small>
                                                    </div>
                                                    <div class="text-end">
                                                        <div class="fw-bold text-success">KSH <?php echo number_format($policy['premium_amount']); ?></div>
                                                        <small class="text-muted"><?php echo date('M j', strtotime($policy['inception_date'])); ?></small>
                                                    </div>
                                                </div>
                                            <?php endwhile; ?>
                                            <div class="text-center mt-3">
                                                <a href="policies/list_policies.php?agent=<?php echo $agent['user_id']; ?>" class="btn btn-sm btn-soft-primary">
                                                    View All Policies
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="info-card">
                                        <div class="card-header">
                                            <h6 class="card-title mb-0">
                                                <i class="ri-history-line me-2"></i>Recent Activities
                                            </h6>
                                        </div>
                                        <div class="card-body">
                                            <?php while($activity = $activities_result->fetch_assoc()): 
                                                $activity_class = match($activity['action']) {
                                                    'LOGIN' => 'success',
                                                    'CREATE', 'ISSUE_POLICY' => 'info',
                                                    'UPDATE', 'EDIT' => 'warning',
                                                    'FAILED_LOGIN' => 'danger',
                                                    default => ''
                                                };
                                                $activity_icon = match($activity['action']) {
                                                    'LOGIN' => 'ri-login-circle-line',
                                                    'CREATE' => 'ri-add-circle-line',
                                                    'UPDATE' => 'ri-edit-line',
                                                    'ISSUE_POLICY' => 'ri-file-add-line',
                                                    default => 'ri-information-line'
                                                };
                                            ?>
                                                <div class="activity-item <?php echo $activity_class; ?>">
                                                    <div class="d-flex justify-content-between">
                                                        <div>
                                                            <i class="<?php echo $activity_icon; ?> me-2"></i>
                                                            <?php echo ucfirst(str_replace('_', ' ', strtolower($activity['action']))); ?>
                                                            <small class="text-muted">in <?php echo ucfirst($activity['module']); ?></small>
                                                        </div>
                                                        <small class="text-muted">
                                                            <?php echo date('M j, H:i', strtotime($activity['logged_at'])); ?>
                                                        </small>
                                                    </div>
                                                </div>
                                            <?php endwhile; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <!-- Send Message Modal -->
    <div class="modal fade" id="messageModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Send Message to <?php echo htmlspecialchars($agent['full_name']); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="messageForm">
                    <div class="modal-body">
                        <input type="hidden" name="agent_id" value="<?php echo $agent['user_id']; ?>">
                        <div class="mb-3">
                            <label class="form-label">Message Type</label>
                            <select class="form-select" name="message_type" required>
                                <option value="">Select Type</option>
                                <option value="EMAIL">Email</option>
                                <option value="SMS">SMS</option>
                                <option value="WHATSAPP">WhatsApp</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">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 Message</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.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
    $(document).ready(function() {
        // Render performance chart
        renderPerformanceChart();
        
        // Message form submission
        $('#messageForm').on('submit', function(e) {
            e.preventDefault();
            
            $.ajax({
                url: 'ajax/send_agent_message.php',
                method: 'POST',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        $('#messageModal').modal('hide');
                        Swal.fire({
                            icon: 'success',
                            title: 'Message Sent',
                            text: 'Your message has been sent successfully.',
                            timer: 2000,
                            showConfirmButton: false
                        });
                        $('#messageForm')[0].reset();
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message || 'Failed to send message.'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while sending the message.'
                    });
                }
            });
        });
    });

    function renderPerformanceChart() {
        const performanceData = <?php echo json_encode($performance_data); ?>;
        
        const options = {
            series: [{
                name: 'Premium (KSH)',
                type: 'column',
                data: performanceData.map(item => parseFloat(item.premium))
            }, {
                name: 'Policies',
                type: 'line',
                data: performanceData.map(item => parseInt(item.policies))
            }],
            chart: {
                height: 300,
                type: 'line',
                toolbar: {
                    show: false
                }
            },
            stroke: {
                width: [0, 4]
            },
            plotOptions: {
                bar: {
                    columnWidth: '50%'
                }
            },
            colors: ['#667eea', '#764ba2'],
            dataLabels: {
                enabled: true,
                enabledOnSeries: [1]
            },
            labels: performanceData.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 / 1000).toFixed(0) + 'K';
                    }
                }
            }, {
                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("#performanceChart"), options);
        chart.render();
    }

    function sendMessage(agentId) {
        $('#messageModal').modal('show');
    }

    // Auto-update last seen time
    function updateLastSeen() {
        const lastLogin = '<?php echo $agent['last_login']; ?>';
        if (lastLogin) {
            const lastLoginDate = new Date(lastLogin);
            const now = new Date();
            const diffTime = Math.abs(now - lastLoginDate);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            
            // Update display based on time difference
            // This would be implemented for real-time updates
        }
    }

    // Call updateLastSeen every minute
    setInterval(updateLastSeen, 60000);
    </script>

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