<?php
/**
 * admin/users.php - Complete User Management with Working Features
 */

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

$breadcrumbs = [['title' => 'Users', 'url' => '']];

// Fetch all users
try {
    $sql = "SELECT 
                u.*,
                r.region_name,
                d.district_name,
                s.subcounty_name,
                ar.role_name,
                (SELECT COUNT(*) FROM products WHERE seller_id = u.id) as product_count,
                (SELECT COUNT(*) FROM orders WHERE buyer_id = u.id OR seller_id = u.id) as order_count
            FROM users u
            LEFT JOIN regions r ON u.region_id = r.id
            LEFT JOIN districts d ON u.district_id = d.id
            LEFT JOIN subcounties s ON u.subcounty_id = s.id
            LEFT JOIN admin_roles ar ON u.admin_role_id = ar.id
            ORDER BY u.created_at DESC";
    
    $stmt = $db->query($sql);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get statistics
    $stats = [
        'total' => count($users),
        'farmers' => count(array_filter($users, fn($u) => $u['user_type'] === 'farmer')),
        'buyers' => count(array_filter($users, fn($u) => $u['user_type'] === 'buyer')),
        'officers' => count(array_filter($users, fn($u) => $u['user_type'] === 'extension_officer')),
        'admins' => count(array_filter($users, fn($u) => $u['user_type'] === 'admin')),
        'active' => count(array_filter($users, fn($u) => $u['is_active'] == 1)),
        'verified' => count(array_filter($users, fn($u) => $u['is_verified'] == 1))
    ];
    
} catch (PDOException $e) {
    logError('Users fetch error: ' . $e->getMessage());
    $users = [];
    $stats = ['total' => 0, 'farmers' => 0, 'buyers' => 0, 'officers' => 0, 'admins' => 0, 'active' => 0, 'verified' => 0];
}

renderAdminHeader('All Users', $breadcrumbs);
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">All Users</h2>
        <p class="text-muted mb-0">Manage all platform users</p>
    </div>
    <button class="btn btn-success" onclick="exportUsers()">
        <i class="bi bi-download me-2"></i>Export CSV
    </button>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-md-4 col-lg-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="mb-1 fw-bold text-primary"><?php echo $stats['total']; ?></h4>
                <small class="text-muted">Total Users</small>
            </div>
        </div>
    </div>
    <div class="col-md-4 col-lg-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="mb-1 fw-bold text-success"><?php echo $stats['farmers']; ?></h4>
                <small class="text-muted">Farmers</small>
            </div>
        </div>
    </div>
    <div class="col-md-4 col-lg-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="mb-1 fw-bold text-info"><?php echo $stats['buyers']; ?></h4>
                <small class="text-muted">Buyers</small>
            </div>
        </div>
    </div>
    <div class="col-md-4 col-lg-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="mb-1 fw-bold text-warning"><?php echo $stats['officers']; ?></h4>
                <small class="text-muted">Officers</small>
            </div>
        </div>
    </div>
    <div class="col-md-4 col-lg-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="mb-1 fw-bold text-danger"><?php echo $stats['admins']; ?></h4>
                <small class="text-muted">Admins</small>
            </div>
        </div>
    </div>
    <div class="col-md-4 col-lg-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="mb-1 fw-bold text-success"><?php echo $stats['verified']; ?></h4>
                <small class="text-muted">Verified</small>
            </div>
        </div>
    </div>
</div>

<!-- Users Table -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold">
            <i class="bi bi-people me-2"></i>All Registered Users
        </h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0" id="usersTable">
                <thead class="table-light">
                    <tr>
                        <th>User</th>
                        <th>Type</th>
                        <th>Location</th>
                        <th>Contact</th>
                        <th>Activity</th>
                        <th>Status</th>
                        <th>Joined</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr data-user-id="<?php echo $user['id']; ?>">
                        <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-3" style="width: 40px; height: 40px;">
                                    <i class="bi bi-person"></i>
                                </div>
                                <div>
                                    <div class="fw-semibold"><?php echo htmlspecialchars($user['full_name']); ?></div>
                                    <small class="text-muted">ID: <?php echo $user['id']; ?></small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <?php
                            $typeColors = [
                                'farmer' => 'success',
                                'buyer' => 'info',
                                'extension_officer' => 'warning',
                                'admin' => 'danger'
                            ];
                            $color = $typeColors[$user['user_type']] ?? 'secondary';
                            ?>
                            <span class="badge bg-<?php echo $color; ?>">
                                <?php echo ucwords(str_replace('_', ' ', $user['user_type'])); ?>
                            </span>
                        </td>
                        <td>
                            <?php if ($user['district_name']): ?>
                                <div class="small">
                                    <?php echo htmlspecialchars($user['district_name']); ?>
                                    <?php if ($user['subcounty_name']): ?>
                                        , <?php echo htmlspecialchars($user['subcounty_name']); ?>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <span class="text-muted small">Not set</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="small">
                                <i class="bi bi-phone me-1"></i><?php echo htmlspecialchars($user['phone_number']); ?>
                                <?php if ($user['email']): ?>
                                    <br><i class="bi bi-envelope me-1"></i><?php echo htmlspecialchars($user['email']); ?>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <div class="small">
                                <?php if ($user['product_count'] > 0): ?>
                                    <i class="bi bi-box me-1 text-success"></i><?php echo $user['product_count']; ?> products<br>
                                <?php endif; ?>
                                <?php if ($user['order_count'] > 0): ?>
                                    <i class="bi bi-cart me-1 text-info"></i><?php echo $user['order_count']; ?> orders
                                <?php endif; ?>
                                <?php if ($user['product_count'] == 0 && $user['order_count'] == 0): ?>
                                    <span class="text-muted">No activity</span>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <?php if ($user['is_active']): ?>
                                <span class="badge bg-success">Active</span>
                            <?php else: ?>
                                <span class="badge bg-danger">Inactive</span>
                            <?php endif; ?>
                            <?php if ($user['is_verified']): ?>
                                <i class="bi bi-patch-check-fill text-success ms-1" title="Verified"></i>
                            <?php endif; ?>
                        </td>
                        <td>
                            <small class="text-muted"><?php echo date('M d, Y', strtotime($user['created_at'])); ?></small>
                        </td>
                        <td class="text-end">
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-info" onclick='viewUserDetails(<?php echo json_encode($user); ?>)' title="View Details">
                                    <i class="bi bi-eye"></i>
                                </button>
                                <button class="btn btn-outline-primary" onclick="editUser(<?php echo $user['id']; ?>)" title="Edit">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-outline-<?php echo $user['is_active'] ? 'warning' : 'success'; ?>" 
                                        onclick="toggleStatus(<?php echo $user['id']; ?>, <?php echo $user['is_active']; ?>)" 
                                        title="<?php echo $user['is_active'] ? 'Deactivate' : 'Activate'; ?>">
                                    <i class="bi bi-<?php echo $user['is_active'] ? 'x-circle' : 'check-circle'; ?>"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- User Details Modal -->
<div class="modal fade" id="detailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-person-circle me-2"></i>User Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="detailsContent">
                <!-- Content loaded by JavaScript -->
            </div>
        </div>
    </div>
</div>

<!-- Edit User Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-pencil me-2"></i>Edit User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editForm">
                <div class="modal-body">
                    <input type="hidden" name="user_id" id="edit_user_id">
                    
                    <div class="mb-3">
                        <label class="form-label">Full Name *</label>
                        <input type="text" class="form-control" name="full_name" id="edit_full_name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="email" id="edit_email">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Phone Number *</label>
                        <input type="text" class="form-control" name="phone_number" id="edit_phone" required readonly>
                        <small class="text-muted">Phone number cannot be changed</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">User Type</label>
                        <input type="text" class="form-control" id="edit_user_type" readonly>
                        <small class="text-muted">User type cannot be changed</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#usersTable').DataTable({
        pageLength: 25,
        order: [[6, 'desc']],
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search users..."
        }
    });
});

// View user details
function viewUserDetails(user) {
    const modal = new bootstrap.Modal(document.getElementById('detailsModal'));
    
    const location = [
        user.district_name,
        user.subcounty_name,
        user.parish,
        user.village
    ].filter(Boolean).join(', ') || 'Not set';
    
    const html = `
        <div class="row">
            <div class="col-md-4 text-center mb-3">
                <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 100px; height: 100px; font-size: 3rem;">
                    <i class="bi bi-person"></i>
                </div>
                <h5>${user.full_name}</h5>
                <span class="badge bg-${user.user_type === 'farmer' ? 'success' : (user.user_type === 'buyer' ? 'info' : (user.user_type === 'admin' ? 'danger' : 'warning'))}">${user.user_type.replace('_', ' ').toUpperCase()}</span>
            </div>
            <div class="col-md-8">
                <table class="table table-sm">
                    <tr><th width="40%">User ID:</th><td>#${user.id}</td></tr>
                    <tr><th>Phone:</th><td>${user.phone_number}</td></tr>
                    <tr><th>Email:</th><td>${user.email || 'Not provided'}</td></tr>
                    <tr><th>Location:</th><td>${location}</td></tr>
                    <tr><th>Status:</th><td>${user.is_active ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-danger">Inactive</span>'}</td></tr>
                    <tr><th>Verified:</th><td>${user.is_verified ? '<i class="bi bi-check-circle text-success"></i> Yes' : '<i class="bi bi-x-circle text-danger"></i> No'}</td></tr>
                    <tr><th>Products:</th><td>${user.product_count} listings</td></tr>
                    <tr><th>Orders:</th><td>${user.order_count} transactions</td></tr>
                    <tr><th>Joined:</th><td>${new Date(user.created_at).toLocaleDateString()}</td></tr>
                    <tr><th>Last Login:</th><td>${user.last_login ? new Date(user.last_login).toLocaleString() : 'Never'}</td></tr>
                </table>
            </div>
        </div>
    `;
    
    document.getElementById('detailsContent').innerHTML = html;
    modal.show();
}

// Edit user
function editUser(userId) {
    const row = $(`tr[data-user-id="${userId}"]`);
    const userData = {
        id: userId,
        full_name: row.find('.fw-semibold').first().text(),
        phone: row.find('td:eq(3)').text().split('\n')[0].replace(/\s/g, '').replace('☎️', ''),
        email: row.find('td:eq(3) i.bi-envelope').parent().text().trim(),
        user_type: row.find('.badge').first().text()
    };
    
    // Fetch full user data
    $.get(APP_URL + '/api/admin.php?action=get_user_details&user_id=' + userId, function(response) {
        if (response.success) {
            const user = response.data;
            $('#edit_user_id').val(user.id);
            $('#edit_full_name').val(user.full_name);
            $('#edit_email').val(user.email || '');
            $('#edit_phone').val(user.phone_number);
            $('#edit_user_type').val(user.user_type.replace('_', ' '));
            
            const modal = new bootstrap.Modal(document.getElementById('editModal'));
            modal.show();
        }
    });
}

// Handle edit form submission
$('#editForm').submit(function(e) {
    e.preventDefault();
    
    const btn = $(this).find('button[type="submit"]');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Saving...');
    
    $.ajax({
        url: APP_URL + '/api/admin.php',
        method: 'POST',
        data: $(this).serialize() + '&action=update_user',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                showToast(response.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast(response.message, 'error');
                btn.prop('disabled', false).html('Save Changes');
            }
        },
        error: function() {
            showToast('Connection error', 'error');
            btn.prop('disabled', false).html('Save Changes');
        }
    });
});

// Toggle user status
function toggleStatus(userId, currentStatus) {
    const action = currentStatus ? 'deactivate' : 'activate';
    const actionCap = action.charAt(0).toUpperCase() + action.slice(1);
    
    Swal.fire({
        title: `${actionCap} User?`,
        text: `This will ${action} the user's account.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: currentStatus ? '#dc2626' : '#059669',
        confirmButtonText: `Yes, ${action}!`
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {
                action: 'update_user_status',
                user_id: userId,
                is_active: currentStatus ? 0 : 1
            }, function(response) {
                hideLoading();
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(response.message, 'error');
                }
            }, 'json').fail(function() {
                hideLoading();
                showToast('Connection error', 'error');
            });
        }
    });
}

// Export users
function exportUsers() {
    showLoading();
    window.location.href = APP_URL + '/api/admin.php?action=export_users&format=csv';
    setTimeout(hideLoading, 2000);
}
</script>

<?php renderAdminFooter(); ?>