<?php
/**
 * Agents List
 * LandSales Pro - Manage sales agents
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();
requireViewPermission('agents');

$userId = $_SESSION['user_id'];

// Search and filter
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';

// Build query
$whereClause = "WHERE a.user_id = ?";
$params = [$userId];
$types = 'i';

if ($search) {
    $whereClause .= " AND (a.full_name LIKE ? OR a.email LIKE ? OR a.phone LIKE ?)";
    $searchTerm = "%{$search}%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $types .= 'sss';
}

if ($status) {
    $whereClause .= " AND a.status = ?";
    $params[] = $status;
    $types .= 's';
}

// Pagination
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$total = db_fetch_one("SELECT COUNT(*) as count FROM agents a {$whereClause}", $types, $params)['count'];
$totalPages = ceil($total / $perPage);

$agents = db_fetch_all("SELECT a.*,
    (SELECT COUNT(*) FROM sales WHERE agent_id = a.id AND status IN ('active', 'completed')) as total_sales,
    (SELECT COALESCE(SUM(total_price), 0) FROM sales WHERE agent_id = a.id AND status IN ('active', 'completed')) as total_value,
    (SELECT COALESCE(SUM(total_price * a.commission_rate / 100), 0) FROM sales WHERE agent_id = a.id AND status IN ('active', 'completed')) as total_commission
    FROM agents a
    {$whereClause}
    ORDER BY a.created_at DESC
    LIMIT {$perPage} OFFSET {$offset}", $types, $params);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Agents - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Sales Agents</h1>
            <div class="header-actions">
                <?php if (canManage('agents')): ?>
                <a href="create.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add Agent
                </a>
                <?php endif; ?>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Filters -->
            <div class="filters-card">
                <form class="search-form" method="GET">
                    <div class="search-input">
                        <i class="fas fa-search"></i>
                        <input type="text" name="search" placeholder="Search by name, email or phone..."
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <select name="status" class="form-control-sm">
                        <option value="">All Status</option>
                        <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo $status === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                    <button type="submit" class="btn btn-primary">Filter</button>
                    <?php if ($search || $status): ?>
                    <a href="index.php" class="btn btn-outline">Clear</a>
                    <?php endif; ?>
                </form>
            </div>

            <!-- Table -->
            <div class="card">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Agent</th>
                                <th>Phone</th>
                                <th>Commission</th>
                                <th>Sales</th>
                                <th>Total Earned</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($agents)): ?>
                            <tr>
                                <td colspan="7" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-user-tie"></i>
                                        <p>No agents found</p>
                                        <?php if (canManage('agents')): ?>
                                        <a href="create.php" class="btn btn-primary btn-sm">Add First Agent</a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($agents as $agent): ?>
                            <tr>
                                <td>
                                    <div class="user-cell">
                                        <div class="user-avatar">
                                            <?php echo strtoupper(substr($agent['full_name'], 0, 1)); ?>
                                        </div>
                                        <div>
                                            <div class="user-name"><?php echo htmlspecialchars($agent['full_name']); ?></div>
                                            <div class="user-email"><?php echo htmlspecialchars($agent['email'] ?? '-'); ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td><?php echo htmlspecialchars($agent['phone']); ?></td>
                                <td>
                                    <span class="badge badge-info"><?php echo number_format($agent['commission_rate'], 1); ?>%</span>
                                </td>
                                <td>
                                    <span class="badge"><?php echo $agent['total_sales']; ?> sales</span>
                                </td>
                                <td>
                                    <span class="text-success">TZS <?php echo number_format($agent['total_commission']); ?></span>
                                </td>
                                <td>
                                    <span class="status-badge status-<?php echo $agent['status']; ?>">
                                        <?php echo ucfirst($agent['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="view.php?id=<?php echo $agent['id']; ?>" class="btn-icon" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <?php if (canManage('agents')): ?>
                                        <a href="edit.php?id=<?php echo $agent['id']; ?>" class="btn-icon" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                <div class="pagination-wrapper">
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>" class="page-link">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        <?php endif; ?>

                        <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                        <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>"
                           class="page-link <?php echo $i === $page ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                        <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>" class="page-link">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-sm { padding: 0.5rem 0.875rem; font-size: 0.8rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .filters-card { background: white; border-radius: 10px; padding: 1rem; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .search-form { display: flex; gap: 0.75rem; flex-wrap: wrap; }
        .search-input { position: relative; flex: 1; min-width: 200px; }
        .search-input i { position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: #94a3b8; }
        .search-input input { width: 100%; padding: 0.625rem 1rem 0.625rem 2.5rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.875rem; }
        .search-input input:focus { outline: none; border-color: #667eea; }
        .form-control-sm { padding: 0.625rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.875rem; min-width: 130px; }

        .card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .table-responsive { overflow-x: auto; }
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 1rem; text-align: left; border-bottom: 1px solid #f1f5f9; }
        .data-table th { background: #f8fafc; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; }
        .data-table tbody tr:hover { background: #f8fafc; }

        .user-cell { display: flex; align-items: center; gap: 0.75rem; }
        .user-avatar { width: 40px; height: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; color: white; display: flex; align-items: center; justify-content: center; font-weight: 600; }
        .user-name { font-weight: 500; color: #1e293b; }
        .user-email { font-size: 0.8rem; color: #64748b; }

        .badge { padding: 0.25rem 0.5rem; background: #f1f5f9; border-radius: 4px; font-size: 0.75rem; color: #64748b; }
        .badge-info { background: #e0f2fe; color: #0369a1; }

        .status-badge { padding: 0.25rem 0.625rem; border-radius: 20px; font-size: 0.75rem; font-weight: 500; }
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }

        .text-success { color: #16a34a; font-weight: 500; }

        .action-buttons { display: flex; gap: 0.5rem; }
        .btn-icon { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: #64748b; background: #f1f5f9; text-decoration: none; transition: all 0.2s; }
        .btn-icon:hover { background: #667eea; color: white; }

        .empty-row td { padding: 3rem; }
        .empty-state { text-align: center; color: #94a3b8; }
        .empty-state i { font-size: 2rem; margin-bottom: 0.5rem; }

        .pagination-wrapper { padding: 1rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: center; }
        .pagination { display: flex; gap: 0.25rem; }
        .page-link { padding: 0.5rem 0.75rem; border-radius: 6px; text-decoration: none; color: #64748b; font-weight: 500; }
        .page-link:hover { background: #f1f5f9; }
        .page-link.active { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
    </style>
</body>
</html>
