<?php
/**
 * Buyers List
 * LandSales Pro - Manage buyers/customers
 */
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();

$userId = $_SESSION['user_id'];

// Search
$search = $_GET['search'] ?? '';

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

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

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

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

$buyers = db_fetch_all("SELECT b.*,
    (SELECT COUNT(*) FROM sales WHERE buyer_id = b.id AND status = 'active') as total_purchases,
    (SELECT COALESCE(SUM(total_price), 0) FROM sales WHERE buyer_id = b.id AND status = 'active') as total_value
    FROM buyers b
    {$whereClause}
    ORDER BY b.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>Buyers - <?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">
        <?php
        $pageTitle = 'Buyers';
        $headerActions = '<a href="create.php" class="btn btn-primary"><i class="fas fa-plus"></i> Add Buyer</a>';
        include '../includes/header.php';
        ?>

        <div class="content-wrapper">
            <!-- Search -->
            <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>
                    <button type="submit" class="btn btn-primary">Search</button>
                    <?php if ($search): ?>
                    <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>Buyer</th>
                                <th>Phone</th>
                                <th>Purchases</th>
                                <th>Total Value</th>
                                <th>Added</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($buyers)): ?>
                            <tr>
                                <td colspan="6" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-users"></i>
                                        <p>No buyers found</p>
                                        <a href="create.php" class="btn btn-primary btn-sm">Add First Buyer</a>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($buyers as $buyer): ?>
                            <tr>
                                <td>
                                    <div class="user-cell">
                                        <div class="user-avatar">
                                            <?php echo strtoupper(substr($buyer['full_name'], 0, 1)); ?>
                                        </div>
                                        <div>
                                            <div class="user-name"><?php echo htmlspecialchars($buyer['full_name']); ?></div>
                                            <div class="user-email"><?php echo htmlspecialchars($buyer['email'] ?? '-'); ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td><?php echo htmlspecialchars($buyer['phone']); ?></td>
                                <td>
                                    <span class="badge"><?php echo $buyer['total_purchases']; ?> plots</span>
                                </td>
                                <td>TZS <?php echo number_format($buyer['total_value']); ?></td>
                                <td><?php echo date('M j, Y', strtotime($buyer['created_at'])); ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="view.php?id=<?php echo $buyer['id']; ?>" class="btn-icon" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="../sales/create.php?buyer_id=<?php echo $buyer['id']; ?>" class="btn-icon success" title="New Sale">
                                            <i class="fas fa-handshake"></i>
                                        </a>
                                        <a href="edit.php?id=<?php echo $buyer['id']; ?>" class="btn-icon" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                    </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); ?>" 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); ?>"
                           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); ?>" 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; align-items: center; }
        .search-input { position: relative; flex: 1; min-width: 200px; max-width: 400px; }
        .search-input i { position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: #94a3b8; z-index: 1; }
        .search-input input { width: 100%; padding: 0.625rem 1rem 0.625rem 2.5rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.875rem; box-sizing: border-box; }
        .search-input input:focus { outline: none; border-color: #667eea; }

        @media (max-width: 576px) {
            .search-form { flex-direction: column; }
            .search-input { max-width: 100%; width: 100%; }
            .search-form .btn { width: 100%; justify-content: center; }
        }

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

        .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; }
        .btn-icon.success:hover { background: #22c55e; }

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