<?php
/**
 * Admin Customers - FIXED VERSION
 * Digital Product Store
 */

require_once __DIR__ . '/includes/header.php';

$page_title = 'Customers';

// Handle actions
if (isset($_GET['action']) && isset($_GET['id'])) {
    $customer_id = (int)$_GET['id'];
    $action = sanitize($_GET['action']);
    
    switch ($action) {
        case 'delete':
            try {
                // Delete customer orders first
                $stmt = $pdo->prepare("DELETE FROM orders WHERE customer_email = (SELECT email FROM users WHERE id = ?)");
                $stmt->execute([$customer_id]);
                
                // Delete customer
                $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND role = 'customer'");
                $stmt->execute([$customer_id]);
                
                set_flash_message('success', 'Customer deleted successfully.');
            } catch (PDOException $e) {
                set_flash_message('error', 'Failed to delete customer: ' . $e->getMessage());
            }
            header('Location: ' . ADMIN_URL . '/customers.php');
            exit;
            
        case 'status':
            $new_status = sanitize($_GET['status'] ?? 'active');
            try {
                $stmt = $pdo->prepare("UPDATE users SET status = ? WHERE id = ? AND role = 'customer'");
                $stmt->execute([$new_status, $customer_id]);
                set_flash_message('success', 'Customer status updated.');
            } catch (PDOException $e) {
                set_flash_message('error', 'Failed to update status.');
            }
            header('Location: ' . ADMIN_URL . '/customers.php');
            exit;
    }
}

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Filters
$status_filter = isset($_GET['status']) ? sanitize($_GET['status']) : '';
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

// Build query
$where = ["role = 'customer'"];
$params = [];

if ($status_filter) {
    $where[] = "status = ?";
    $params[] = $status_filter;
}

if ($search) {
    $where[] = "(name LIKE ? OR email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Get total count
try {
    $count_sql = "SELECT COUNT(*) FROM users $where_clause";
    $stmt = $pdo->prepare($count_sql);
    $stmt->execute($params);
    $total_customers = $stmt->fetchColumn();
} catch (PDOException $e) {
    $total_customers = 0;
}

$total_pages = ceil($total_customers / $per_page);

// Get customers - FIXED: Use users table instead of customers table
try {
    $sql = "SELECT u.*, 
            (SELECT COUNT(*) FROM orders WHERE customer_email = u.email) as order_count,
            (SELECT SUM(total) FROM orders WHERE customer_email = u.email AND payment_status = 'completed') as total_spent
            FROM users u 
            $where_clause 
            ORDER BY u.created_at DESC 
            LIMIT ? OFFSET ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array_merge($params, [$per_page, $offset]));
    $customers = $stmt->fetchAll();
} catch (PDOException $e) {
    $customers = [];
}

// Get customer counts by status
$status_counts = [];
try {
    $stmt = $pdo->query("SELECT status, COUNT(*) as count FROM users WHERE role = 'customer' GROUP BY status");
    while ($row = $stmt->fetch()) {
        $status_counts[$row['status']] = $row['count'];
    }
} catch (PDOException $e) {
    // Silently fail
}
?>

<div class="page-header">
    <div>
        <h1>Customers</h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?php echo ADMIN_URL; ?>/index.php">Dashboard</a></li>
                <li class="breadcrumb-item active">Customers</li>
            </ol>
        </nav>
    </div>
</div>

<?php echo get_flash_message(); ?>

<!-- Stats Cards -->
<div class="row mb-4">
    <div class="col-md-4">
        <div class="card stat-card primary">
            <div class="stat-label">Total Customers</div>
            <div class="stat-value"><?php echo number_format($total_customers); ?></div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card stat-card success">
            <div class="stat-label">Active</div>
            <div class="stat-value"><?php echo number_format($status_counts['active'] ?? 0); ?></div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card stat-card secondary">
            <div class="stat-label">Inactive</div>
            <div class="stat-value"><?php echo number_format($status_counts['inactive'] ?? 0); ?></div>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-5">
                <input type="text" name="search" class="form-control" placeholder="Search customers..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <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>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-search"></i> Filter
                </button>
            </div>
            <div class="col-md-2">
                <a href="<?php echo ADMIN_URL; ?>/customers.php" class="btn btn-outline-secondary w-100">
                    <i class="fas fa-times"></i> Clear
                </a>
            </div>
        </form>
    </div>
</div>

<!-- Customers Table -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span>All Customers</span>
        <span class="text-muted"><?php echo number_format($total_customers); ?> customers found</span>
    </div>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>Customer</th>
                    <th>Email</th>
                    <th>Joined</th>
                    <th>Orders</th>
                    <th>Total Spent</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($customers)): ?>
                <tr>
                    <td colspan="7" class="text-center py-4">
                        <i class="fas fa-users fa-3x text-muted mb-3"></i>
                        <p>No customers found.</p>
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($customers as $customer): ?>
                <tr>
                    <td>
                        <div class="d-flex align-items-center">
                            <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 40px; height: 40px;">
                                <?php echo strtoupper(substr($customer['name'] ?? '', 0, 1)); ?>
                            </div>
                            <div>
                                <div class="fw-bold"><?php echo htmlspecialchars($customer['name'] ?? ''); ?></div>
                            </div>
                        </div>
                    </td>
                    <td><?php echo htmlspecialchars($customer['email'] ?? ''); ?></td>
                    <td><?php echo format_date($customer['created_at'] ?? ''); ?></td>
                    <td><?php echo number_format($customer['order_count'] ?? 0); ?></td>
                    <td class="fw-bold"><?php echo format_price($customer['total_spent'] ?? 0); ?></td>
                    <td>
                        <?php 
                        $status_class = ($customer['status'] ?? 'active') === 'active' ? 'success' : 'secondary';
                        ?>
                        <span class="badge bg-<?php echo $status_class; ?>"><?php echo ucfirst($customer['status'] ?? 'active'); ?></span>
                    </td>
                    <td>
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-primary dropdown-toggle" data-bs-toggle="dropdown">
                                <i class="fas fa-cog"></i>
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="?action=status&id=<?php echo $customer['id']; ?>&status=active">Activate</a></li>
                                <li><a class="dropdown-item" href="?action=status&id=<?php echo $customer['id']; ?>&status=inactive">Deactivate</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item text-danger" href="?action=delete&id=<?php echo $customer['id']; ?>" onclick="return confirm('Are you sure you want to delete this customer?')">Delete</a></li>
                            </ul>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Pagination -->
<?php if ($total_pages > 1): ?>
<nav class="mt-4">
    <ul class="pagination justify-content-center">
        <?php if ($page > 1): ?>
        <li class="page-item">
            <a class="page-link" href="?page=<?php echo $page - 1; ?>&status=<?php echo $status_filter; ?>&search=<?php echo $search; ?>">Previous</a>
        </li>
        <?php endif; ?>
        
        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
            <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status_filter; ?>&search=<?php echo $search; ?>"><?php echo $i; ?></a>
        </li>
        <?php endfor; ?>
        
        <?php if ($page < $total_pages): ?>
        <li class="page-item">
            <a class="page-link" href="?page=<?php echo $page + 1; ?>&status=<?php echo $status_filter; ?>&search=<?php echo $search; ?>">Next</a>
        </li>
        <?php endif; ?>
    </ul>
</nav>
<?php endif; ?>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
