<?php
session_start();
require_once '../config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $userId = (int)($_POST['user_id'] ?? 0);
    
    if ($action === 'add_coins' && $userId > 0) {
        $coins = (int)($_POST['coins'] ?? 0);
        $coinType = $_POST['coin_type'] ?? 'regular';
        
        if ($coins > 0) {
            if ($coinType === 'free') {
                $stmt = $pdo->prepare("UPDATE users SET free_coins = free_coins + ? WHERE id = ?");
                if ($stmt->execute([$coins, $userId])) {
                    // Add transaction record
                    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'free_bonus', ?, 'Admin free coins bonus')");
                    $stmt->execute([$userId, $coins]);
                    $success = "سکه‌های رایگان با موفقیت اضافه شد";
                }
            } else {
                $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
                if ($stmt->execute([$coins, $userId])) {
                    // Add transaction record
                    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'bonus', ?, 'Admin bonus')");
                    $stmt->execute([$userId, $coins]);
                    $success = "سکه با موفقیت اضافه شد";
                }
            }
        }
    } elseif ($action === 'edit_user' && $userId > 0) {
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $fullName = trim($_POST['full_name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        
        if (empty($username) || empty($email) || empty($fullName)) {
            $error = 'فیلدهای الزامی را پر کنید';
        } else {
            // Check if username or email already exists for other users
            $stmt = $pdo->prepare("SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ?");
            $stmt->execute([$username, $email, $userId]);
            if ($stmt->fetch()) {
                $error = 'نام کاربری یا ایمیل قبلاً استفاده شده است';
            } else {
                $stmt = $pdo->prepare("UPDATE users SET username = ?, email = ?, full_name = ?, phone = ? WHERE id = ?");
                if ($stmt->execute([$username, $email, $fullName, $phone, $userId])) {
                    $success = "اطلاعات کاربر با موفقیت ویرایش شد";
                } else {
                    $error = "خطا در ویرایش اطلاعات کاربر";
                }
            }
        }
    } elseif ($action === 'toggle_status' && $userId > 0) {
        $stmt = $pdo->prepare("UPDATE users SET is_active = NOT is_active WHERE id = ?");
        if ($stmt->execute([$userId])) {
            $success = "وضعیت کاربر با موفقیت تغییر کرد";
        } else {
            $error = "خطا در تغییر وضعیت کاربر";
        }
    } elseif ($action === 'delete_user' && $userId > 0) {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        if ($stmt->execute([$userId])) {
            $success = "کاربر با موفقیت حذف شد";
        }
    } elseif ($action === 'change_password' && $userId > 0) {
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        if ($newPassword === '' || $confirmPassword === '') {
            $error = 'رمز عبور جدید و تکرار آن را وارد کنید';
        } elseif ($newPassword !== $confirmPassword) {
            $error = 'رمز عبور و تکرار آن یکسان نیستند';
        } elseif (strlen($newPassword) < 6) {
            $error = 'رمز عبور باید حداقل ۶ کاراکتر باشد';
        } else {
            $hashed = password_hash($newPassword, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
            if ($stmt->execute([$hashed, $userId])) {
                $success = 'رمز عبور کاربر با موفقیت تغییر کرد';
            } else {
                $error = 'خطا در تغییر رمز عبور';
            }
        }
    }
}

// Get search and filter parameters
$search = trim($_GET['search'] ?? '');
$status = $_GET['status'] ?? '';

// Build query with search and filter
$whereConditions = [];
$params = [];

if (!empty($search)) {
    $whereConditions[] = "(username LIKE ? OR email LIKE ? OR full_name LIKE ? OR phone LIKE ?)";
    $searchParam = "%$search%";
    $params = array_merge($params, [$searchParam, $searchParam, $searchParam, $searchParam]);
}

if ($status !== '') {
    $whereConditions[] = "is_active = ?";
    $params[] = $status === 'active' ? 1 : 0;
}

$whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

// Get users with pagination
$page = (int)($_GET['page'] ?? 1);
$limit = 20;
$offset = ($page - 1) * $limit;

// Count total users with filters
$countQuery = "SELECT COUNT(*) FROM users $whereClause";
$stmt = $pdo->prepare($countQuery);
$stmt->execute($params);
$totalUsers = $stmt->fetchColumn();
$totalPages = ceil($totalUsers / $limit);

// Get users with filters
$query = "SELECT id, username, email, full_name, phone, coins, free_coins, telegram_user_id, telegram_username, telegram_first_name, is_active, created_at FROM users $whereClause ORDER BY created_at DESC LIMIT " . (int)$limit . " OFFSET " . (int)$offset;
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت کاربران - پنل مدیریت</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="assets/css/admin.css" rel="stylesheet">
</head>
<body class="admin-app">
    <?php include 'includes/menu.php'; ?>
    <?php include 'includes/header_bar.php'; ?>

    <main class="main">
        <div class="main-content">
                <?php
                $admin_page_title = 'مدیریت کاربران';
                $admin_page_icon = 'fas fa-users';
                $admin_page_actions = '<span class="badge rounded-pill admin-badge-soft">' . number_format($totalUsers) . ' کاربر</span>';
                include 'includes/topbar.php';
                ?>

                <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i>
                        <?= htmlspecialchars($success) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <?= htmlspecialchars($error) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Search and Filter -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">جستجو و فیلتر</h6>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-6">
                                <label for="search" class="form-label">جستجو</label>
                                <input type="text" class="form-control" id="search" name="search" 
                                       value="<?= htmlspecialchars($search) ?>" 
                                       placeholder="جستجو در نام کاربری، ایمیل، نام کامل یا تلفن...">
                            </div>
                            <div class="col-md-3">
                                <label for="status" class="form-label">وضعیت</label>
                                <select class="form-control" id="status" name="status">
                                    <option value="">همه کاربران</option>
                                    <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>فعال</option>
                                    <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>غیرفعال</option>
                                </select>
                            </div>
                            <div class="col-md-3 d-flex align-items-end">
                                <div class="d-flex gap-2 w-100">
                                    <button type="submit" class="btn btn-primary flex-fill">
                                        <i class="fas fa-search me-2"></i>جستجو
                                    </button>
                                    <a href="users.php" class="btn btn-secondary">
                                        <i class="fas fa-times me-2"></i>پاک کردن
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Users Table -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">لیست کاربران</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>نام کاربری</th>
                                        <th>نام کامل</th>
                                        <th>ایمیل</th>
                                        <th>تلفن</th>
                                        <th>سکه‌ها</th>
                                        <th>اطلاعات تلگرام</th>
                                        <th>وضعیت</th>
                                        <th>تاریخ ثبت</th>
                                        <th>عملیات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($users as $user): ?>
                                    <tr>
                                        <td><?= $user['id'] ?></td>
                                        <td><?= htmlspecialchars($user['username']) ?></td>
                                        <td><?= htmlspecialchars($user['full_name']) ?></td>
                                        <td><?= htmlspecialchars($user['email']) ?></td>
                                        <td><?= htmlspecialchars($user['phone'] ?: '-') ?></td>
                                        <td>
                                            <div class="small">
                                                <span class="badge bg-warning text-dark d-block mb-1">سکه: <?= number_format($user['coins']) ?></span>
                                                <span class="badge bg-info text-dark d-block">سکه رایگان: <?= number_format($user['free_coins']) ?></span>
                                            </div>
                                        </td>
                                        <td>
                                            <?php if (!empty($user['telegram_user_id'])): ?>
                                                <div class="small">
                                                    <div><strong>ID:</strong> <?= htmlspecialchars($user['telegram_user_id']) ?></div>
                                                    <div><strong>Username:</strong> <?= htmlspecialchars($user['telegram_username'] ?: '-') ?></div>
                                                    <div><strong>Name:</strong> <?= htmlspecialchars($user['telegram_first_name'] ?: '-') ?></div>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-muted small">سینک نشده</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?= $user['is_active'] ? 'success' : 'danger' ?>">
                                                <?= $user['is_active'] ? 'فعال' : 'غیرفعال' ?>
                                            </span>
                                        </td>
                                        <td><?= date('Y/m/d H:i', strtotime($user['created_at'])) ?></td>
                                        <td>
                                            <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-sm btn-primary" 
                                                        data-bs-toggle="modal" data-bs-target="#editUserModal" 
                                                        data-user='<?= json_encode($user) ?>'>
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-secondary" title="تغییر رمز عبور"
                                                        data-bs-toggle="modal" data-bs-target="#changePasswordModal"
                                                        data-user-id="<?= (int)$user['id'] ?>"
                                                        data-username="<?= htmlspecialchars($user['username'], ENT_QUOTES, 'UTF-8') ?>">
                                                    <i class="fas fa-key"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-success" 
                                                        data-bs-toggle="modal" data-bs-target="#addCoinsModal" 
                                                        data-user-id="<?= $user['id'] ?>" 
                                                        data-username="<?= htmlspecialchars($user['username']) ?>"
                                                        data-coin-type="regular">
                                                    <i class="fas fa-plus"></i> سکه
                                                </button>
                                                <button type="button" class="btn btn-sm btn-info" 
                                                        data-bs-toggle="modal" data-bs-target="#addCoinsModal" 
                                                        data-user-id="<?= $user['id'] ?>" 
                                                        data-username="<?= htmlspecialchars($user['username']) ?>"
                                                        data-coin-type="free">
                                                    <i class="fas fa-star"></i> سکه رایگان
                                                </button>
                                                <button type="button" class="btn btn-sm btn-<?= $user['is_active'] ? 'warning' : 'info' ?>" 
                                                        onclick="toggleUserStatus(<?= $user['id'] ?>, '<?= htmlspecialchars($user['username']) ?>', <?= $user['is_active'] ? 'false' : 'true' ?>)">
                                                    <i class="fas fa-<?= $user['is_active'] ? 'ban' : 'check' ?>"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-danger" 
                                                        onclick="deleteUser(<?= $user['id'] ?>, '<?= htmlspecialchars($user['username']) ?>')">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($totalPages > 1): 
                            $queryParams = [];
                            if (!empty($search)) $queryParams['search'] = $search;
                            if (!empty($status)) $queryParams['status'] = $status;
                            $queryString = !empty($queryParams) ? '&' . http_build_query($queryParams) : '';
                            
                            $startPage = max(1, $page - 2);
                            $endPage = min($totalPages, $page + 2);
                            
                            if ($endPage - $startPage < 4) {
                                if ($startPage == 1) {
                                    $endPage = min($totalPages, $startPage + 4);
                                } else {
                                    $startPage = max(1, $endPage - 4);
                                }
                            }
                        ?>
                        <nav aria-label="Page navigation" class="mt-4">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="text-muted">
                                    نمایش <?= number_format(($page - 1) * $limit + 1) ?> تا <?= number_format(min($page * $limit, $totalUsers)) ?> از <?= number_format($totalUsers) ?> کاربر
                                </div>
                                <ul class="pagination mb-0">
                                    <!-- Previous Button -->
                                    <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                                        <a class="page-link" href="?page=<?= $page - 1 ?><?= $queryString ?>" aria-label="قبلی">
                                            <i class="fas fa-chevron-right"></i>
                                        </a>
                                    </li>
                                    
                                    <!-- First Page -->
                                    <?php if ($startPage > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=1<?= $queryString ?>">1</a>
                                        </li>
                                        <?php if ($startPage > 2): ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    
                                    <!-- Page Numbers -->
                                    <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                                        <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                            <a class="page-link" href="?page=<?= $i ?><?= $queryString ?>"><?= $i ?></a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <!-- Last Page -->
                                    <?php if ($endPage < $totalPages): ?>
                                        <?php if ($endPage < $totalPages - 1): ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        <?php endif; ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?= $totalPages ?><?= $queryString ?>"><?= $totalPages ?></a>
                                        </li>
                                    <?php endif; ?>
                                    
                                    <!-- Next Button -->
                                    <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
                                        <a class="page-link" href="?page=<?= $page + 1 ?><?= $queryString ?>" aria-label="بعدی">
                                            <i class="fas fa-chevron-left"></i>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </nav>
                        <?php endif; ?>
                    </div>
                </div>
        </div>
    </main>

    <!-- Edit User Modal -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">ویرایش اطلاعات کاربر</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="edit_user">
                        <input type="hidden" name="user_id" id="editUserId">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editUsername" class="form-label">نام کاربری *</label>
                                    <input type="text" class="form-control" id="editUsername" name="username" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editEmail" class="form-label">ایمیل *</label>
                                    <input type="email" class="form-control" id="editEmail" name="email" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editFullName" class="form-label">نام کامل *</label>
                                    <input type="text" class="form-control" id="editFullName" name="full_name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editPhone" class="form-label">شماره تلفن</label>
                                    <input type="text" class="form-control" id="editPhone" name="phone" placeholder="09123456789">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                        <button type="submit" class="btn btn-primary">ذخیره تغییرات</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Change Password Modal -->
    <div class="modal fade" id="changePasswordModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">تغییر رمز عبور</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" autocomplete="off">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="change_password">
                        <input type="hidden" name="user_id" id="changePasswordUserId">
                        <p class="mb-3">کاربر: <strong id="changePasswordUsername"></strong></p>
                        <div class="mb-3">
                            <label for="newPassword" class="form-label">رمز عبور جدید *</label>
                            <input type="password" class="form-control" id="newPassword" name="new_password" minlength="6" required autocomplete="new-password">
                            <div class="form-text">حداقل ۶ کاراکتر</div>
                        </div>
                        <div class="mb-0">
                            <label for="confirmPassword" class="form-label">تکرار رمز عبور *</label>
                            <input type="password" class="form-control" id="confirmPassword" name="confirm_password" minlength="6" required autocomplete="new-password">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                        <button type="submit" class="btn btn-primary">ذخیره رمز عبور</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Coins Modal -->
    <div class="modal fade" id="addCoinsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">افزودن سکه</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_coins">
                        <input type="hidden" name="user_id" id="modalUserId">
                        <input type="hidden" name="coin_type" id="modalCoinType">
                        <p>افزودن سکه برای کاربر: <strong id="modalUsername"></strong></p>
                        <div class="mb-3">
                            <label for="coins" class="form-label">تعداد سکه</label>
                            <input type="number" class="form-control" id="coins" name="coins" min="1" required>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="coin_type" id="regularCoins" value="regular" checked>
                            <label class="form-check-label" for="regularCoins">سکه معمولی</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="coin_type" id="freeCoins" value="free">
                            <label class="form-check-label" for="freeCoins">سکه رایگان</label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                        <button type="submit" class="btn btn-success">افزودن سکه</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <?php include 'includes/admin_shell_scripts.php'; ?>
    <script>
        // Change Password Modal
        document.getElementById('changePasswordModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            document.getElementById('changePasswordUserId').value = button.getAttribute('data-user-id');
            document.getElementById('changePasswordUsername').textContent = button.getAttribute('data-username');
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
        });

        // Edit User Modal
        document.getElementById('editUserModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var user = JSON.parse(button.getAttribute('data-user'));
            
            document.getElementById('editUserId').value = user.id;
            document.getElementById('editUsername').value = user.username;
            document.getElementById('editEmail').value = user.email;
            document.getElementById('editFullName').value = user.full_name;
            document.getElementById('editPhone').value = user.phone || '';
        });

        // Add Coins Modal
        document.getElementById('addCoinsModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var userId = button.getAttribute('data-user-id');
            var username = button.getAttribute('data-username');
            var coinType = button.getAttribute('data-coin-type');
            
            document.getElementById('modalUserId').value = userId;
            document.getElementById('modalUsername').textContent = username;
            document.getElementById('regularCoins').checked = coinType === 'regular'; // Set checked based on coin type
            document.getElementById('freeCoins').checked = coinType === 'free';
        });

        // Toggle User Status
        function toggleUserStatus(userId, username, newStatus) {
            var statusText = newStatus ? 'فعال' : 'غیرفعال';
            if (confirm('آیا از تغییر وضعیت کاربر "' + username + '" به "' + statusText + '" اطمینان دارید؟')) {
                var form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="toggle_status">
                    <input type="hidden" name="user_id" value="${userId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Delete User
        function deleteUser(userId, username) {
            if (confirm('آیا از حذف کاربر "' + username + '" اطمینان دارید؟')) {
                var form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_user">
                    <input type="hidden" name="user_id" value="${userId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>
