<?php
/**
 * View Agent
 * LandSales Pro - View agent details and sales history
 */
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'];
$agentId = intval($_GET['id'] ?? 0);

// Get agent with stats
$agent = db_fetch_one("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 WHERE a.id = ? AND a.user_id = ?", 'ii', [$agentId, $userId]);

if (!$agent) {
    setFlashMessage('Agent not found', 'error');
    header('Location: index.php');
    exit;
}

// Get recent sales by this agent
$recentSales = db_fetch_all("SELECT s.*, p.plot_number, pr.name as project_name, b.full_name as buyer_name
    FROM sales s
    JOIN plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    JOIN buyers b ON s.buyer_id = b.id
    WHERE s.agent_id = ? AND s.user_id = ?
    ORDER BY s.sale_date DESC
    LIMIT 10", 'ii', [$agentId, $userId]);

// Flash message
$flash = getFlashMessage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($agent['full_name']); ?> - <?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">Agent Details</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <?php if (canManage('agents')): ?>
                <a href="edit.php?id=<?php echo $agentId; ?>" class="btn btn-primary">
                    <i class="fas fa-edit"></i> Edit
                </a>
                <?php endif; ?>
            </div>
        </div>

        <div class="content-wrapper">
            <?php if ($flash): ?>
            <div class="alert alert-<?php echo $flash['type'] === 'success' ? 'success' : 'danger'; ?>">
                <i class="fas fa-<?php echo $flash['type'] === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                <?php echo htmlspecialchars($flash['message']); ?>
            </div>
            <?php endif; ?>

            <div class="profile-grid">
                <!-- Agent Info Card -->
                <div class="profile-card">
                    <div class="profile-header">
                        <div class="profile-avatar">
                            <?php echo strtoupper(substr($agent['full_name'], 0, 1)); ?>
                        </div>
                        <div class="profile-info">
                            <h2><?php echo htmlspecialchars($agent['full_name']); ?></h2>
                            <span class="status-badge status-<?php echo $agent['status']; ?>">
                                <?php echo ucfirst($agent['status']); ?>
                            </span>
                        </div>
                    </div>
                    <div class="profile-details">
                        <div class="detail-item">
                            <i class="fas fa-phone"></i>
                            <span><?php echo htmlspecialchars($agent['phone']); ?></span>
                        </div>
                        <?php if ($agent['email']): ?>
                        <div class="detail-item">
                            <i class="fas fa-envelope"></i>
                            <span><?php echo htmlspecialchars($agent['email']); ?></span>
                        </div>
                        <?php endif; ?>
                        <div class="detail-item">
                            <i class="fas fa-percent"></i>
                            <span>Commission Rate: <?php echo number_format($agent['commission_rate'], 1); ?>%</span>
                        </div>
                        <div class="detail-item">
                            <i class="fas fa-calendar"></i>
                            <span>Added: <?php echo date('M j, Y', strtotime($agent['created_at'])); ?></span>
                        </div>
                    </div>
                </div>

                <!-- Stats Cards -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon blue">
                            <i class="fas fa-handshake"></i>
                        </div>
                        <div class="stat-info">
                            <span class="stat-value"><?php echo number_format($agent['total_sales']); ?></span>
                            <span class="stat-label">Total Sales</span>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon purple">
                            <i class="fas fa-coins"></i>
                        </div>
                        <div class="stat-info">
                            <span class="stat-value">TZS <?php echo number_format($agent['total_value']); ?></span>
                            <span class="stat-label">Sales Value</span>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon green">
                            <i class="fas fa-wallet"></i>
                        </div>
                        <div class="stat-info">
                            <span class="stat-value">TZS <?php echo number_format($agent['total_commission']); ?></span>
                            <span class="stat-label">Total Commission</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Sales -->
            <div class="card mt-4">
                <div class="card-header">
                    <h3><i class="fas fa-history"></i> Recent Sales</h3>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Sale #</th>
                                <th>Plot</th>
                                <th>Buyer</th>
                                <th>Amount</th>
                                <th>Commission</th>
                                <th>Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recentSales)): ?>
                            <tr>
                                <td colspan="7" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-handshake"></i>
                                        <p>No sales recorded yet</p>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($recentSales as $sale): ?>
                            <tr>
                                <td><strong><?php echo htmlspecialchars($sale['sale_number']); ?></strong></td>
                                <td>
                                    <div><?php echo htmlspecialchars($sale['plot_number']); ?></div>
                                    <small class="text-muted"><?php echo htmlspecialchars($sale['project_name']); ?></small>
                                </td>
                                <td><?php echo htmlspecialchars($sale['buyer_name']); ?></td>
                                <td>TZS <?php echo number_format($sale['total_price']); ?></td>
                                <td class="text-success">TZS <?php echo number_format($sale['total_price'] * $agent['commission_rate'] / 100); ?></td>
                                <td><?php echo date('M j, Y', strtotime($sale['sale_date'])); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $sale['status']; ?>">
                                        <?php echo ucfirst($sale['status']); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </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-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .alert { padding: 1rem 1.5rem; border-radius: 10px; margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem; }
        .alert-success { background: #dcfce7; border: 1px solid #86efac; color: #166534; }
        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }

        .profile-grid { display: grid; grid-template-columns: 350px 1fr; gap: 1.5rem; }
        .mt-4 { margin-top: 1.5rem; }

        .profile-card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .profile-header { padding: 2rem; text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .profile-avatar { width: 80px; height: 80px; background: rgba(255,255,255,0.2); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 2rem; font-weight: 700; margin: 0 auto 1rem; }
        .profile-info h2 { margin: 0 0 0.5rem 0; font-size: 1.25rem; }
        .profile-details { padding: 1.5rem; }
        .detail-item { display: flex; align-items: center; gap: 0.75rem; padding: 0.75rem 0; border-bottom: 1px solid #f1f5f9; }
        .detail-item:last-child { border-bottom: none; }
        .detail-item i { width: 20px; color: #667eea; }

        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; align-content: start; }
        .stat-card { background: white; border-radius: 14px; padding: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); display: flex; align-items: center; gap: 1rem; }
        .stat-icon { width: 50px; height: 50px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; }
        .stat-icon.blue { background: #e0f2fe; color: #0369a1; }
        .stat-icon.purple { background: #f3e8ff; color: #7c3aed; }
        .stat-icon.green { background: #dcfce7; color: #16a34a; }
        .stat-value { display: block; font-size: 1.25rem; font-weight: 700; color: #1e293b; }
        .stat-label { font-size: 0.8rem; color: #64748b; }

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

        .card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { padding: 1.25rem 1.5rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; }
        .card-header h3 { margin: 0; font-size: 1rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }

        .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; }

        .text-muted { color: #94a3b8; font-size: 0.8rem; }
        .text-success { color: #16a34a; font-weight: 500; }

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

        @media (max-width: 992px) {
            .profile-grid { grid-template-columns: 1fr; }
        }
    </style>
</body>
</html>
