<?php
/**
 * Manage Users (SQL Error Fixed & Mobile Responsive)
 */
require_once 'header.php';

$success = '';
$error = '';

// ==========================================
// ১. ইউজার ডিলিট করার লজিক (Status লজিক বাদ দেওয়া হয়েছে)
// ==========================================
if (isset($_GET['action']) && isset($_GET['id'])) {
    $action = $_GET['action'];
    $target_user_id = (int)$_GET['id'];
    $current_admin_id = $_SESSION['user_id'] ?? 0;

    // অ্যাডমিন যাতে নিজেকে নিজে ডিলিট করতে না পারে
    if ($target_user_id === $current_admin_id && $current_admin_id !== 0) {
        $error = "You cannot delete your own admin account.";
    } else {
        try {
            if ($action === 'delete') {
                // অ্যাডমিন অ্যাকাউন্ট ডিলিট করা যাবে না
                $pdo->prepare("DELETE FROM users WHERE id = ? AND role != 'admin'")->execute([$target_user_id]);
                $success = "User account permanently deleted.";
            }
        } catch (PDOException $e) {
            $error = "An error occurred: " . $e->getMessage();
        }
    }
}

// ==========================================
// ২. সব ইউজারের লিস্ট ফেচ করা (u.status কলাম রিমুভ করা হয়েছে)
// ==========================================
try {
    $stmt = $pdo->query("
        SELECT 
            u.id, u.name, u.email, u.role, u.created_at,
            (SELECT COUNT(*) FROM orders WHERE user_id = u.id AND status = 'approved') as total_purchases
        FROM users u
        ORDER BY u.created_at DESC
    ");
    $users = $stmt->fetchAll();
} catch (PDOException $e) {
    $error = "Failed to load users: " . $e->getMessage();
    $users = [];
}
?>

<style>
    /* ================= Header & Alerts ================= */
    .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; flex-wrap: wrap; gap: 15px; }
    .page-title { font-size: 1.5rem; font-weight: 800; color: var(--text-dark); margin: 0; }
    
    .alert-box { padding: 15px 20px; border-radius: 8px; margin-bottom: 25px; font-weight: 600; font-size: 0.95rem; }
    .alert-success { background: #ecfdf5; border: 1px solid #a7f3d0; color: #065f46; }
    .alert-danger { background: #fee2e2; border: 1px solid #fecaca; color: #991b1b; }

    /* ================= Responsive Table Design ================= */
    .table-card { background: var(--bg-white); border: 1px solid var(--border-color); border-radius: 12px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.03); margin-bottom: 30px; }
    
    .table-responsive { width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; }
    .data-table { width: 100%; border-collapse: collapse; text-align: left; min-width: 700px; }
    
    .data-table th { padding: 15px 12px; font-size: 0.8rem; color: var(--text-gray); font-weight: 700; border-bottom: 1px solid var(--border-color); text-transform: uppercase; white-space: nowrap; background: #f9fafb; }
    .data-table td { padding: 15px 12px; border-bottom: 1px solid #f3f4f6; font-size: 0.9rem; color: var(--text-dark); font-weight: 500; vertical-align: middle; }
    .data-table tr:last-child td { border-bottom: none; }
    .data-table tr:hover { background: #fdfdfd; }

    /* ================= Typography & Badges ================= */
    .user-name { font-weight: 700; color: var(--text-dark); font-size: 1rem; margin-bottom: 3px; }
    .user-email { font-size: 0.8rem; color: var(--text-gray); font-family: monospace; }
    
    .role-badge { font-size: 0.7rem; font-weight: 800; padding: 3px 8px; border-radius: 4px; border: 1px solid var(--primary-orange); color: var(--primary-orange); display: inline-block; }

    /* ================= Buttons ================= */
    .action-btns { display: flex; gap: 8px; align-items: center; }
    .btn-sm { font-size: 0.8rem; font-weight: 700; padding: 6px 12px; border-radius: 6px; text-decoration: none; transition: 0.2s; display: inline-block; }
    
    .btn-delete { color: #ef4444; border: 1px solid #fecaca; background: #fff5f5; }
    .btn-delete:hover { background: #fee2e2; color: #dc2626; }

    /* ================= Mobile View ================= */
    @media (max-width: 768px) {
        .page-header { flex-direction: column; align-items: flex-start; }
        .table-card { padding: 15px 10px; }
        .data-table th, .data-table td { padding: 12px 10px; }
    }
</style>

<div class="page-header">
    <h1 class="page-title">User Management</h1>
</div>

<?php if($success): ?> <div class="alert-box alert-success">✓ <?php echo $success; ?></div> <?php endif; ?>
<?php if($error): ?> <div class="alert-box alert-danger">⚠ <?php echo $error; ?></div> <?php endif; ?>

<div class="table-card">
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>Customer Info</th>
                    <th>Role</th>
                    <th>Joined Date</th>
                    <th>Total Purchases</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($users as $u): ?>
                <tr>
                    <td>
                        <div class="user-name"><?php echo htmlspecialchars($u['name']); ?></div>
                        <div class="user-email"><?php echo htmlspecialchars($u['email']); ?></div>
                    </td>
                    
                    <td>
                        <?php if ($u['role'] === 'admin'): ?>
                            <span class="role-badge">ADMIN</span>
                        <?php else: ?>
                            <span style="color: var(--text-gray); font-size: 0.85rem; font-weight: 600;">User</span>
                        <?php endif; ?>
                    </td>
                    
                    <td style="font-size: 0.85rem; color: var(--text-gray);">
                        <?php echo date('d M, Y', strtotime($u['created_at'])); ?>
                    </td>
                    
                    <td style="font-weight: 800; color: var(--primary-orange); font-size: 1rem;">
                        <?php echo $u['total_purchases']; ?> <span style="font-size: 0.7rem; color: var(--text-muted); font-weight: 600;">Orders</span>
                    </td>
                    
                    <td>
                        <?php 
                            $sess_id = $_SESSION['user_id'] ?? 0;
                        ?>
                        <?php if ($u['id'] != $sess_id): ?>
                            <div class="action-btns">
                                <?php if ($u['role'] !== 'admin'): ?>
                                    <a href="?action=delete&id=<?php echo $u['id']; ?>" class="btn-sm btn-delete" onclick="return confirm('Are you sure you want to permanently delete this user? All their history will be lost.');">
                                        Delete User
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <span style="font-size: 0.8rem; color: var(--text-muted); font-weight: 600; background: #f3f4f6; padding: 4px 8px; border-radius: 4px;">(It's You)</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                
                <?php if(count($users) == 0): ?>
                    <tr><td colspan="5" style="text-align: center; padding: 40px; color: var(--text-muted); font-weight: 600;">No users found in the system.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php echo '</div></div></body></html>'; ?>