<?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 filter parameters
$search = $_GET['search'] ?? '';
$branch_filter = $_GET['branch'] ?? '';
$status_filter = $_GET['status'] ?? '';
$role_filter = $_GET['role'] ?? '';

// Build query with filters
$where_conditions = ["u.agent_code IS NOT NULL"];
$params = [];
$param_types = "";

if (!empty($search)) {
    $where_conditions[] = "(u.full_name LIKE ? OR u.agent_code LIKE ? OR u.email LIKE ? OR u.phone_number LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    $param_types .= "ssss";
}

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

if (!empty($status_filter)) {
    $where_conditions[] = "u.status = ?";
    $params[] = $status_filter;
    $param_types .= "s";
}

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

// Main query for agents
$sql = "SELECT 
    u.user_id,
    u.agent_code,
    u.full_name,
    u.email,
    u.phone_number,
    u.license_number,
    u.license_expiry,
    u.commission_rate,
    u.target_monthly,
    u.status,
    u.hire_date,
    u.last_login,
    ur.role_name,
    b.branch_name,
    b.branch_code,
    supervisor.full_name as supervisor_name,
    -- Performance metrics
    COUNT(DISTINCT p.policy_id) as total_policies,
    COUNT(DISTINCT CASE WHEN p.status = 'ACTIVE' THEN p.policy_id END) as active_policies,
    COALESCE(SUM(CASE WHEN p.status = 'ACTIVE' THEN p.premium_amount END), 0) as total_premium,
    COUNT(DISTINCT p.customer_id) as unique_customers,
    -- This month performance
    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
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
LEFT JOIN policies p ON u.user_id = p.agent_id
WHERE " . implode(" AND ", $where_conditions) . "
GROUP BY u.user_id, u.agent_code, u.full_name, u.email, u.phone_number, u.license_number, 
         u.license_expiry, u.commission_rate, u.target_monthly, u.status, u.hire_date, 
         u.last_login, ur.role_name, b.branch_name, b.branch_code, supervisor.full_name
ORDER BY u.full_name ASC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$agents_result = $stmt->get_result();

// 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 roles for filter
$roles_sql = "SELECT role_id, role_name FROM user_roles WHERE role_name LIKE '%Agent%' ORDER BY role_name";
$roles_result = $conn->query($roles_sql);

// Get summary statistics
$stats_sql = "SELECT 
    COUNT(*) as total_agents,
    COUNT(CASE WHEN status = 'ACTIVE' THEN 1 END) as active_agents,
    COUNT(CASE WHEN status = 'INACTIVE' THEN 1 END) as inactive_agents,
    COUNT(CASE WHEN status = 'SUSPENDED' THEN 1 END) as suspended_agents,
    COUNT(CASE WHEN license_expiry < CURRENT_DATE() THEN 1 END) as expired_licenses,
    COUNT(CASE WHEN license_expiry BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 30 DAY) THEN 1 END) as expiring_soon
FROM users u 
WHERE u.agent_code IS NOT NULL";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Agent Management - 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">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    <style>
        .agent-status-badge {
            font-size: 0.75rem;
            padding: 0.35rem 0.65rem;
        }
        .performance-indicator {
            width: 100%;
            height: 8px;
            border-radius: 4px;
            overflow: hidden;
        }
        .license-expiry-warning {
            color: #e74c3c;
            font-weight: 600;
        }
        .license-expiry-soon {
            color: #f39c12;
            font-weight: 600;
        }
        .stats-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
        }
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        }
        .agent-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        .agent-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: white;
        }
        .table-actions .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
    </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 Management</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 active">Agent Management</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="card stats-card bg-primary text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="mb-1 text-white-50">Total Agents</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['total_agents']); ?></h4>
                                        </div>
                                        <div>
                                            <i class="ri-team-line fs-2"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="card stats-card bg-success text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="mb-1 text-white-50">Active</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['active_agents']); ?></h4>
                                        </div>
                                        <div>
                                            <i class="ri-user-check-line fs-2"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="card stats-card bg-secondary text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="mb-1 text-white-50">Inactive</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['inactive_agents']); ?></h4>
                                        </div>
                                        <div>
                                            <i class="ri-user-unfollow-line fs-2"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="card stats-card bg-danger text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="mb-1 text-white-50">Suspended</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['suspended_agents']); ?></h4>
                                        </div>
                                        <div>
                                            <i class="ri-user-forbid-line fs-2"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="card stats-card bg-warning text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="mb-1 text-white-50">License Expired</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['expired_licenses']); ?></h4>
                                        </div>
                                        <div>
                                            <i class="ri-alert-line fs-2"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="card stats-card bg-info text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="mb-1 text-white-50">Expiring Soon</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['expiring_soon']); ?></h4>
                                        </div>
                                        <div>
                                            <i class="ri-time-line fs-2"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters and Actions -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card agent-card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label">Search Agents</label>
                                            <input type="text" class="form-control" name="search" 
                                                   placeholder="Name, Code, Email, Phone..." 
                                                   value="<?php echo htmlspecialchars($search); ?>">
                                        </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">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="ACTIVE" <?php echo $status_filter == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                                <option value="INACTIVE" <?php echo $status_filter == 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                                <option value="SUSPENDED" <?php echo $status_filter == 'SUSPENDED' ? 'selected' : ''; ?>>Suspended</option>
                                                <option value="PENDING" <?php echo $status_filter == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Role</label>
                                            <select class="form-select" name="role">
                                                <option value="">All Roles</option>
                                                <?php while($role = $roles_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $role['role_id']; ?>" 
                                                            <?php echo $role_filter == $role['role_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($role['role_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3 d-flex align-items-end gap-2">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-search-line me-1"></i> Filter
                                            </button>
                                            <a href="list_agents.php" class="btn btn-secondary">
                                                <i class="ri-refresh-line me-1"></i> Reset
                                            </a>
                                            <a href="add_agent.php" class="btn btn-success">
                                                <i class="ri-user-add-line me-1"></i> Add Agent
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Agents Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card agent-card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-team-line me-2"></i>Insurance Agents
                                    </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')">
                                                <i class="ri-file-text-line me-2"></i>CSV
                                            </a></li>
                                            <li><a class="dropdown-item" href="#" onclick="exportTable('excel')">
                                                <i class="ri-file-excel-line me-2"></i>Excel
                                            </a></li>
                                            <li><a class="dropdown-item" href="#" onclick="exportTable('pdf')">
                                                <i class="ri-file-pdf-line me-2"></i>PDF
                                            </a></li>
                                        </ul>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="agentsTable" class="table table-hover align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Agent Details</th>
                                                    <th>Branch & Role</th>
                                                    <th>License</th>
                                                    <th>Performance (MTD)</th>
                                                    <th>Target Achievement</th>
                                                    <th>Last Login</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while($agent = $agents_result->fetch_assoc()): 
                                                    // Calculate achievement percentage
                                                    $achievement_percentage = $agent['target_monthly'] > 0 ? 
                                                        round(($agent['monthly_premium'] / $agent['target_monthly']) * 100, 1) : 0;
                                                    
                                                    // License status
                                                    $license_status = '';
                                                    $license_class = '';
                                                    if ($agent['license_expiry']) {
                                                        $expiry_date = new DateTime($agent['license_expiry']);
                                                        $now = new DateTime();
                                                        $diff = $now->diff($expiry_date);
                                                        
                                                        if ($expiry_date < $now) {
                                                            $license_status = 'Expired';
                                                            $license_class = 'license-expiry-warning';
                                                        } elseif ($diff->days <= 30) {
                                                            $license_status = $diff->days . ' days left';
                                                            $license_class = 'license-expiry-soon';
                                                        } else {
                                                            $license_status = 'Valid';
                                                            $license_class = 'text-success';
                                                        }
                                                    }
                                                ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="agent-avatar bg-primary me-3">
                                                                <?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>
                                                                <p class="text-muted mb-1 small">
                                                                    <strong>Code:</strong> <?php echo htmlspecialchars($agent['agent_code']); ?>
                                                                </p>
                                                                <p class="text-muted mb-0 small">
                                                                    <i class="ri-mail-line me-1"></i><?php echo htmlspecialchars($agent['email']); ?>
                                                                </p>
                                                                <?php if($agent['phone_number']): ?>
                                                                <p class="text-muted mb-0 small">
                                                                    <i class="ri-phone-line me-1"></i><?php echo htmlspecialchars($agent['phone_number']); ?>
                                                                </p>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <span class="badge bg-soft-info text-info mb-1">
                                                                <?php echo htmlspecialchars($agent['branch_name'] ?: 'Head Office'); ?>
                                                            </span><br>
                                                            <small class="text-muted"><?php echo htmlspecialchars($agent['role_name']); ?></small>
                                                            <?php if($agent['supervisor_name']): ?>
                                                                <br><small class="text-muted">
                                                                    <i class="ri-user-line me-1"></i><?php echo htmlspecialchars($agent['supervisor_name']); ?>
                                                                </small>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php if($agent['license_number']): ?>
                                                            <div>
                                                                <small class="text-muted">License:</small><br>
                                                                <strong><?php echo htmlspecialchars($agent['license_number']); ?></strong><br>
                                                                <span class="<?php echo $license_class; ?>">
                                                                    <?php echo $license_status; ?>
                                                                </span>
                                                            </div>
                                                        <?php else: ?>
                                                            <span class="text-muted">Not provided</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <strong class="text-success">
                                                                KSH <?php echo number_format($agent['monthly_premium'], 2); ?>
                                                            </strong><br>
                                                            <small class="text-muted">
                                                                <?php echo number_format($agent['monthly_policies']); ?> policies
                                                            </small><br>
                                                            <small class="text-muted">
                                                                <?php echo number_format($agent['unique_customers']); ?> customers (total)
                                                            </small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php if($agent['target_monthly'] > 0): ?>
                                                            <div class="d-flex align-items-center mb-1">
                                                                <div class="performance-indicator bg-light me-2">
                                                                    <div class="bg-<?php echo $achievement_percentage >= 100 ? 'success' : ($achievement_percentage >= 70 ? 'warning' : 'danger'); ?>" 
                                                                         style="width: <?php echo min($achievement_percentage, 100); ?>%; height: 100%;"></div>
                                                                </div>
                                                                <span class="text-<?php echo $achievement_percentage >= 100 ? 'success' : ($achievement_percentage >= 70 ? 'warning' : 'danger'); ?> fw-medium">
                                                                    <?php echo $achievement_percentage; ?>%
                                                                </span>
                                                            </div>
                                                            <small class="text-muted">
                                                                Target: KSH <?php echo number_format($agent['target_monthly'], 2); ?>
                                                            </small>
                                                        <?php else: ?>
                                                            <span class="text-muted">No target set</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if($agent['last_login']): ?>
                                                            <span data-bs-toggle="tooltip" title="<?php echo date('M j, Y H:i', strtotime($agent['last_login'])); ?>">
                                                                <?php
                                                                $last_login = new DateTime($agent['last_login']);
                                                                $now = new DateTime();
                                                                $diff = $now->diff($last_login);
                                                                
                                                                if ($diff->days == 0) {
                                                                    echo "Today";
                                                                } elseif ($diff->days == 1) {
                                                                    echo "Yesterday";
                                                                } elseif ($diff->days < 7) {
                                                                    echo $diff->days . " days ago";
                                                                } else {
                                                                    echo date('M j, Y', strtotime($agent['last_login']));
                                                                }
                                                                ?>
                                                            </span>
                                                        <?php else: ?>
                                                            <span class="text-muted">Never</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        $status_class = match($agent['status']) {
                                                            'ACTIVE' => 'success',
                                                            'INACTIVE' => 'secondary',
                                                            'SUSPENDED' => 'danger',
                                                            'PENDING' => 'warning',
                                                            default => 'info'
                                                        };
                                                        ?>
                                                        <span class="badge bg-<?php echo $status_class; ?> agent-status-badge">
                                                            <?php echo ucfirst(strtolower($agent['status'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="table-actions">
                                                            <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="edit_agent.php?id=<?php echo $agent['user_id']; ?>" 
                                                               class="btn btn-sm btn-soft-warning" data-bs-toggle="tooltip" title="Edit Agent">
                                                                <i class="ri-edit-line"></i>
                                                            </a>
                                                            <button type="button" class="btn btn-sm btn-soft-info" 
                                                                    data-bs-toggle="tooltip" title="Send Message"
                                                                    onclick="sendMessage(<?php echo $agent['user_id']; ?>)">
                                                                <i class="ri-message-line"></i>
                                                            </button>
                                                            <div class="btn-group">
                                                                <button type="button" class="btn btn-sm btn-soft-secondary dropdown-toggle" 
                                                                        data-bs-toggle="dropdown">
                                                                    <i class="ri-more-line"></i>
                                                                </button>
                                                                <ul class="dropdown-menu dropdown-menu-end">
                                                                    <li><a class="dropdown-item" href="agent_performance.php?id=<?php echo $agent['user_id']; ?>">
                                                                        <i class="ri-line-chart-line me-2"></i>Performance Report
                                                                    </a></li>
                                                                    <li><a class="dropdown-item" href="agent_commissions.php?id=<?php echo $agent['user_id']; ?>">
                                                                        <i class="ri-money-dollar-circle-line me-2"></i>Commission History
                                                                    </a></li>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <?php if($agent['status'] == 'ACTIVE'): ?>
                                                                        <li><a class="dropdown-item text-warning" href="#" 
                                                                               onclick="changeAgentStatus(<?php echo $agent['user_id']; ?>, 'INACTIVE')">
                                                                            <i class="ri-pause-circle-line me-2"></i>Deactivate
                                                                        </a></li>
                                                                        <li><a class="dropdown-item text-danger" href="#" 
                                                                               onclick="changeAgentStatus(<?php echo $agent['user_id']; ?>, 'SUSPENDED')">
                                                                            <i class="ri-forbid-line me-2"></i>Suspend
                                                                        </a></li>
                                                                    <?php elseif($agent['status'] == 'INACTIVE'): ?>
                                                                        <li><a class="dropdown-item text-success" href="#" 
                                                                               onclick="changeAgentStatus(<?php echo $agent['user_id']; ?>, 'ACTIVE')">
                                                                            <i class="ri-play-circle-line me-2"></i>Activate
                                                                        </a></li>
                                                                    <?php elseif($agent['status'] == 'SUSPENDED'): ?>
                                                                        <li><a class="dropdown-item text-success" href="#" 
                                                                               onclick="changeAgentStatus(<?php echo $agent['user_id']; ?>, 'ACTIVE')">
                                                                            <i class="ri-play-circle-line me-2"></i>Reactivate
                                                                        </a></li>
                                                                    <?php endif; ?>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <li><a class="dropdown-item text-danger" href="#" 
                                                                           onclick="resetPassword(<?php echo $agent['user_id']; ?>)">
                                                                        <i class="ri-lock-unlock-line me-2"></i>Reset Password
                                                                    </a></li>
                                                                </ul>
                                                            </div>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </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 Agent</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="messageForm">
                    <div class="modal-body">
                        <input type="hidden" id="messageAgentId" name="agent_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.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.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
    $(document).ready(function() {
        // Initialize DataTable
        $('#agentsTable').DataTable({
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'csv',
                    className: 'd-none'
                },
                {
                    extend: 'excel',
                    className: 'd-none'
                },
                {
                    extend: 'pdf',
                    className: 'd-none',
                    orientation: 'landscape',
                    pageSize: 'A4'
                }
            ],
            responsive: true,
            pageLength: 25,
            order: [[0, 'asc']],
            columnDefs: [
                { orderable: false, targets: [7] } // Actions column
            ]
        });

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

        // 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.'
                    });
                }
            });
        });
    });

    // Export functions
    function exportTable(format) {
        const table = $('#agentsTable').DataTable();
        
        switch(format) {
            case 'csv':
                table.button('.buttons-csv').trigger();
                break;
            case 'excel':
                table.button('.buttons-excel').trigger();
                break;
            case 'pdf':
                table.button('.buttons-pdf').trigger();
                break;
        }
    }

    // Send message function
    function sendMessage(agentId) {
        $('#messageAgentId').val(agentId);
        $('#messageModal').modal('show');
    }

    // Change agent status
    function changeAgentStatus(agentId, newStatus) {
        const statusText = newStatus.toLowerCase();
        const actionText = newStatus === 'ACTIVE' ? 'activate' : 
                          newStatus === 'INACTIVE' ? 'deactivate' : 'suspend';
        
        Swal.fire({
            title: `${actionText.charAt(0).toUpperCase() + actionText.slice(1)} Agent?`,
            text: `Are you sure you want to ${actionText} this agent?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: `Yes, ${actionText}!`
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'ajax/change_agent_status.php',
                    method: 'POST',
                    data: {
                        agent_id: agentId,
                        status: newStatus
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Status Changed',
                                text: `Agent has been ${statusText}d successfully.`,
                                timer: 2000,
                                showConfirmButton: false
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: response.message || 'Failed to change agent status.'
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'An error occurred while changing the agent status.'
                        });
                    }
                });
            }
        });
    }

    // Reset password function
    function resetPassword(agentId) {
        Swal.fire({
            title: 'Reset Password?',
            text: 'This will generate a new temporary password and send it to the agent.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, reset password!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'ajax/reset_agent_password.php',
                    method: 'POST',
                    data: {
                        agent_id: agentId
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Password Reset',
                                text: 'A new temporary password has been sent to the agent.',
                                timer: 3000,
                                showConfirmButton: false
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: response.message || 'Failed to reset password.'
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'An error occurred while resetting the password.'
                        });
                    }
                });
            }
        });
    }
    </script>

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