<?php
// admin/customers.php - Customers List
require_once '../src/Database.php';
require_once '../src/Auth.php';

$auth = new Auth();
$auth->requireLogin();

$db = new Database();
$conn = $db->getConnection();

// Pagination settings
$items_per_page = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
if ($page < 1) $page = 1;

// Get search/filter parameters
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';

// Get total count
$total_count = 0;
try {
    if ($search_query) {
        $search_term = '%' . $search_query . '%';
        $stmt = $conn->prepare('SELECT COUNT(*) as count FROM contacts WHERE phone_number LIKE ? OR name LIKE ?');
        $stmt->execute([$search_term, $search_term]);
    } else {
        $stmt = $conn->query('SELECT COUNT(*) as count FROM contacts');
    }
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $total_count = $result['count'] ?? 0;
} catch (Exception $e) {
    $total_count = 0;
}

// Calculate pagination
$total_pages = ceil($total_count / $items_per_page);
if ($page > $total_pages && $total_pages > 0) {
    $page = $total_pages;
}

$offset = ($page - 1) * $items_per_page;

// Get paginated contacts
$customers = [];
try {
    if ($search_query) {
        $search_term = '%' . $search_query . '%';
        $stmt = $conn->prepare('SELECT id, phone_number, name, created_at FROM contacts WHERE phone_number LIKE ? OR name LIKE ? ORDER BY created_at DESC LIMIT :limit OFFSET :offset');
        $stmt->bindValue(':limit', $items_per_page, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(1, $search_term, PDO::PARAM_STR);
        $stmt->bindValue(2, $search_term, PDO::PARAM_STR);
        $stmt->execute();
    } else {
        $stmt = $conn->prepare('SELECT id, phone_number, name, created_at FROM contacts ORDER BY created_at DESC LIMIT :limit OFFSET :offset');
        $stmt->bindValue(':limit', $items_per_page, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
    }
    $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $customers = [];
    error_log('Error fetching customers: ' . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customers - USSD System</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <?php include 'sidebar.php'; ?>
    <div class="md:ml-64 min-h-screen">
        <!-- Header -->
        <div class="bg-white shadow-md p-4 md:p-6 border-b border-gray-200">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">Customers</h1>
                <p class="text-gray-600 text-sm mt-1">Manage uploaded contacts and customer information</p>
            </div>
        </div>

        <!-- Content -->
        <div class="p-4 md:p-8">
            <!-- Statistics Card -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Total Contacts</p>
                            <p class="text-3xl font-bold text-blue-600 mt-2"><?php echo number_format($total_count); ?></p>
                        </div>
                        <svg class="w-12 h-12 text-blue-100" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3zM6 8a2 2 0 11-4 0 2 2 0 014 0zM16 18v-3a5.972 5.972 0 00-.75-2.906A3.005 3.005 0 0119 15v3h-3zM4.75 12.094A5.973 5.973 0 004 15v3H1v-3a3 3 0 013.75-2.906z"></path>
                        </svg>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Current Page</p>
                            <p class="text-3xl font-bold text-green-600 mt-2"><?php echo $page; ?></p>
                            <p class="text-xs text-gray-500">of <?php echo $total_pages > 0 ? $total_pages : 1; ?></p>
                        </div>
                        <svg class="w-12 h-12 text-green-100" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M5 2a1 1 0 011-1h8a1 1 0 011 1v14a1 1 0 11-2 0V4H7v12a1 1 0 11-2 0V2z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Per Page</p>
                            <p class="text-3xl font-bold text-purple-600 mt-2"><?php echo count($customers); ?></p>
                            <p class="text-xs text-gray-500"><?php echo $total_count > 0 ? 'max ' . $items_per_page : 'no items'; ?></p>
                        </div>
                        <svg class="w-12 h-12 text-purple-100" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm0 6a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1v-2zm0 6a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1v-2z"></path>
                        </svg>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Status</p>
                            <p class="text-lg font-bold text-indigo-600 mt-2">Active</p>
                            <p class="text-xs text-gray-500">System ready</p>
                        </div>
                        <svg class="w-12 h-12 text-indigo-100" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Search Section -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                <form method="GET" class="flex gap-2">
                    <input type="text" name="search" placeholder="Search by phone number or name..." value="<?php echo htmlspecialchars($search_query); ?>" class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg font-semibold transition">Search</button>
                    <?php if ($search_query): ?>
                    <a href="customers.php" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg font-semibold transition">Clear</a>
                    <?php endif; ?>
                </form>
            </div>

            <!-- Contacts Table -->
            <div class="bg-white rounded-lg shadow-md overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Phone Number</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Name</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Date Added</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($customers as $customer): ?>
                            <tr class="border-b border-gray-200 hover:bg-gray-50 transition">
                                <td class="px-6 py-3 text-sm font-mono text-gray-900"><?php echo htmlspecialchars($customer['phone_number']); ?></td>
                                <td class="px-6 py-3 text-sm text-gray-700"><?php echo htmlspecialchars($customer['name'] ?? '-'); ?></td>
                                <td class="px-6 py-3 text-sm text-gray-600"><?php echo date('M d, Y H:i', strtotime($customer['created_at'])); ?></td>
                                <td class="px-6 py-3 text-sm">
                                    <span class="px-3 py-1 bg-green-100 text-green-800 rounded-full text-xs font-semibold">Active</span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php if (empty($customers)): ?>
                    <div class="text-center text-gray-500 py-12">
                        <svg class="w-12 h-12 mx-auto mb-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.856-1.487M15 10a3 3 0 11-6 0 3 3 0 016 0zM6 20h12a6 6 0 00-6-6 6 6 0 00-6 6z"></path>
                        </svg>
                        <p class="text-lg">No customers found</p>
                        <?php if ($search_query): ?>
                        <p class="text-sm">No results for "<?php echo htmlspecialchars($search_query); ?>"</p>
                        <?php else: ?>
                        <p class="text-sm">Upload contacts in the Whitelist section to get started</p>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="mt-6 flex justify-between items-center">
                <div class="text-sm text-gray-600">
                    Showing <strong><?php echo (($page - 1) * $items_per_page) + 1; ?></strong> to <strong><?php echo min($page * $items_per_page, $total_count); ?></strong> of <strong><?php echo number_format($total_count); ?></strong> customers
                </div>
                <nav class="flex gap-2">
                    <?php if ($page > 1): ?>
                    <a href="?page=1<?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>" class="px-3 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">First</a>
                    <a href="?page=<?php echo $page - 1; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>" class="px-3 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">Previous</a>
                    <?php endif; ?>

                    <?php
                    $start_page = max(1, $page - 2);
                    $end_page = min($total_pages, $page + 2);
                    
                    if ($start_page > 1): ?>
                    <span class="px-3 py-2">...</span>
                    <?php endif; ?>

                    <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                    <?php if ($i === $page): ?>
                    <button class="px-3 py-2 bg-blue-600 text-white rounded-lg font-semibold"><?php echo $i; ?></button>
                    <?php else: ?>
                    <a href="?page=<?php echo $i; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>" class="px-3 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition"><?php echo $i; ?></a>
                    <?php endif; ?>
                    <?php endfor; ?>

                    <?php if ($end_page < $total_pages): ?>
                    <span class="px-3 py-2">...</span>
                    <?php endif; ?>

                    <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>" class="px-3 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">Next</a>
                    <a href="?page=<?php echo $total_pages; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>" class="px-3 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">Last</a>
                    <?php endif; ?>
                </nav>
            </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
