<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config/database.php';
require_once '../includes/functions.php';

if (!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'admin') {
    header('Location: ../index.php');
    exit;
}

$success = '';
$error = '';
$users = $pdo->query("SELECT * FROM users ORDER BY id")->fetchAll();

$roleLabels = [
    'admin' => 'مدیر ارشد',
    'expert' => 'مسئول ثبت‌نام',
    'reporter' => 'گزارشگر',
    'representative' => 'معرف‌کننده'
];
$roleColors = [
    'admin' => 'danger',
    'expert' => 'warning',
    'reporter' => 'info',
    'representative' => 'success'
];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_user'])) {
        try {
            $checkStmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $checkStmt->execute([$_POST['username']]);
            if ($checkStmt->fetch()) throw new Exception("❌ نام کاربری '{$_POST['username']}' قبلاً ثبت شده است.");
            
            $hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, password, fullname, level) VALUES (?, ?, ?, ?)");
            $stmt->execute([$_POST['username'], $hashed_password, $_POST['fullname'], $_POST['level']]);
            
            if ($_POST['level'] == 'representative') {
                $userId = $pdo->lastInsertId();
                $stmt = $pdo->prepare("INSERT INTO referrals (name, user_id, status, sort_order) VALUES (?, ?, 'active', 0)");
                $stmt->execute([$_POST['fullname'], $userId]);
            }
            logSystemActivity($_SESSION['user_id'], 'create_user', "کاربر جدید با نام {$_POST['username']} ایجاد شد");
            $success = "✅ کاربر با موفقیت اضافه شد";
            $users = $pdo->query("SELECT * FROM users ORDER BY id")->fetchAll();
        } catch(Exception $e) { $error = $e->getMessage(); }
        catch(PDOException $e) { $error = "❌ خطا: " . $e->getMessage(); }
    }
    elseif (isset($_POST['edit_user'])) {
        try {
            $userId = $_POST['user_id'];
            $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $currentUser = $stmt->fetch();
            if (!$currentUser) throw new Exception("❌ کاربر یافت نشد.");
            if ($userId == $_SESSION['user_id'] && $_POST['level'] != 'admin') throw new Exception("❌ نمی‌توانید سطح دسترسی خود را تغییر دهید.");
            
            $updates = []; $params = [];
            if (!empty($_POST['fullname'])) { $updates[] = "fullname = ?"; $params[] = $_POST['fullname']; }
            if (!empty($_POST['level'])) { $updates[] = "level = ?"; $params[] = $_POST['level']; }
            if (!empty($_POST['password'])) { $updates[] = "password = ?"; $params[] = password_hash($_POST['password'], PASSWORD_DEFAULT); }
            if (empty($updates)) throw new Exception("❌ هیچ تغییری اعمال نشد.");
            
            $params[] = $userId;
            $sql = "UPDATE users SET " . implode(", ", $updates) . " WHERE id = ?";
            $stmt = $pdo->prepare($sql); $stmt->execute($params);
            
            if ($_POST['level'] == 'representative' && $currentUser['level'] != 'representative') {
                $checkRef = $pdo->prepare("SELECT id FROM referrals WHERE user_id = ?");
                $checkRef->execute([$userId]);
                if (!$checkRef->fetch()) {
                    $stmt = $pdo->prepare("INSERT INTO referrals (name, user_id, status, sort_order) VALUES (?, ?, 'active', 0)");
                    $stmt->execute([$_POST['fullname'] ?: $currentUser['fullname'], $userId]);
                }
            }
            if ($_POST['level'] != 'representative' && $currentUser['level'] == 'representative') {
                $stmt = $pdo->prepare("UPDATE referrals SET status = 'inactive' WHERE user_id = ?");
                $stmt->execute([$userId]);
            }
            logSystemActivity($_SESSION['user_id'], 'edit_user', "کاربر با ID {$userId} ویرایش شد");
            $success = "✅ کاربر با موفقیت ویرایش شد";
            $users = $pdo->query("SELECT * FROM users ORDER BY id")->fetchAll();
        } catch(Exception $e) { $error = $e->getMessage(); }
        catch(PDOException $e) { $error = "❌ خطا: " . $e->getMessage(); }
    }
    elseif (isset($_POST['delete_user'])) {
        try {
            $userId = $_POST['user_id'];
            if ($userId == $_SESSION['user_id']) throw new Exception("❌ نمی‌توانید خود را حذف کنید.");
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM members WHERE created_by = ?");
            $stmt->execute([$userId]);
            $memberCount = $stmt->fetchColumn();
            if ($memberCount > 0) throw new Exception("❌ این کاربر {$memberCount} دانشجو ثبت کرده است. ابتدا دانشجویان را انتقال دهید.");
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $stmt = $pdo->prepare("DELETE FROM referrals WHERE user_id = ?");
            $stmt->execute([$userId]);
            logSystemActivity($_SESSION['user_id'], 'delete_user', "کاربر با ID {$userId} حذف شد");
            $success = "✅ کاربر با موفقیت حذف شد";
            $users = $pdo->query("SELECT * FROM users ORDER BY id")->fetchAll();
        } catch(Exception $e) { $error = $e->getMessage(); }
        catch(PDOException $e) { $error = "❌ خطا: " . $e->getMessage(); }
    }
}

$representatives = $pdo->query("SELECT id, fullname FROM users WHERE level = 'representative'")->fetchAll();
?>
<?php include '../includes/header.php'; ?>

<style>
.stat-card {
    background: white;
    border-radius: 14px;
    padding: 16px 20px;
    border: 1px solid #e9edf2;
    transition: all 0.3s ease;
    height: 100%;
}
.stat-card .stat-number {
    font-size: 1.5rem;
    font-weight: 700;
    color: #0f172a;
    line-height: 1.2;
}
.stat-card .stat-label {
    color: #94a3b8;
    font-size: 0.8rem;
    font-weight: 500;
}
.bg-gradient-purple {
    background: linear-gradient(135deg, #8b5cf6, #6d28d9);
}
.bg-gradient-blue {
    background: linear-gradient(135deg, #3b82f6, #1d4ed8);
}
.bg-gradient-green {
    background: linear-gradient(135deg, #22c55e, #15803d);
}
.bg-gradient-orange {
    background: linear-gradient(135deg, #f59e0b, #d97706);
}
.add-user-form {
    background: #f8fafc;
    border-radius: 14px;
    padding: 20px;
    border: 1px solid #e9edf2;
    margin-bottom: 25px;
}
.add-user-form .form-title {
    font-weight: 600;
    color: #0f172a;
    font-size: 0.9rem;
    margin-bottom: 12px;
}
.add-user-form .form-control,
.add-user-form .form-select {
    height: 44px;
    border-radius: 10px;
}
.table-modern {
    font-size: 0.85rem;
}
.table-modern thead th {
    background: #f8fafc;
    color: #475569;
    font-weight: 600;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    padding: 10px 14px;
    border-bottom: 2px solid #e9edf2;
}
.table-modern tbody td {
    padding: 10px 14px;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: middle;
}
.table-modern tbody tr:hover {
    background: #f8fafc;
}
.rep-list {
    background: #f8fafc;
    border-radius: 14px;
    padding: 16px 20px;
    border: 1px solid #e9edf2;
}
.rep-list .rep-item {
    display: inline-block;
    background: white;
    padding: 4px 14px;
    border-radius: 20px;
    border: 1px solid #e9edf2;
    font-size: 0.8rem;
    margin: 3px 4px;
    color: #334155;
}
</style>

<!-- ===== کارت‌های آماری ===== -->
<div class="row g-3 mb-4">
    <div class="col-xl-3 col-lg-3 col-md-6">
        <div class="stat-card">
            <div class="d-flex align-items-center gap-3">
                <div class="stat-icon bg-gradient-purple" style="width:44px;height:44px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.3rem;color:white;flex-shrink:0;">
                    <i class="bi bi-people-fill"></i>
                </div>
                <div>
                    <div class="stat-number"><?php echo toPersianNumbers(count($users)); ?></div>
                    <div class="stat-label">کل کاربران</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-lg-3 col-md-6">
        <div class="stat-card">
            <div class="d-flex align-items-center gap-3">
                <div class="stat-icon bg-gradient-blue" style="width:44px;height:44px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.3rem;color:white;flex-shrink:0;">
                    <i class="bi bi-person-badge-fill"></i>
                </div>
                <div>
                    <div class="stat-number"><?php echo toPersianNumbers(count(array_filter($users, fn($u) => $u['level'] == 'admin'))); ?></div>
                    <div class="stat-label">مدیران ارشد</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-lg-3 col-md-6">
        <div class="stat-card">
            <div class="d-flex align-items-center gap-3">
                <div class="stat-icon bg-gradient-green" style="width:44px;height:44px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.3rem;color:white;flex-shrink:0;">
                    <i class="bi bi-person-check-fill"></i>
                </div>
                <div>
                    <div class="stat-number"><?php echo toPersianNumbers(count(array_filter($users, fn($u) => $u['level'] == 'expert'))); ?></div>
                    <div class="stat-label">مسئولین ثبت‌نام</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-lg-3 col-md-6">
        <div class="stat-card">
            <div class="d-flex align-items-center gap-3">
                <div class="stat-icon bg-gradient-orange" style="width:44px;height:44px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.3rem;color:white;flex-shrink:0;">
                    <i class="bi bi-person-plus-fill"></i>
                </div>
                <div>
                    <div class="stat-number"><?php echo toPersianNumbers(count(array_filter($users, fn($u) => $u['level'] == 'representative'))); ?></div>
                    <div class="stat-label">معرف‌کنندگان</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ===== فرم افزودن کاربر ===== -->
<div class="add-user-form">
    <div class="form-title"><i class="bi bi-person-plus-fill me-2"></i>افزودن کاربر جدید</div>
    <form method="POST" class="row g-2">
        <div class="col-md-3">
            <input type="text" name="fullname" class="form-control" placeholder="نام کامل" required>
        </div>
        <div class="col-md-3">
            <input type="text" name="username" class="form-control" placeholder="نام کاربری" required>
        </div>
        <div class="col-md-2">
            <input type="password" name="password" class="form-control" placeholder="رمز عبور" required>
        </div>
        <div class="col-md-2">
            <select name="level" class="form-select" required>
                <option value="admin">مدیر ارشد</option>
                <option value="expert">مسئول ثبت‌نام</option>
                <option value="reporter">گزارشگر</option>
                <option value="representative">معرف‌کننده</option>
            </select>
        </div>
        <div class="col-md-2">
            <button type="submit" name="add_user" class="btn btn-pastel w-100"><i class="bi bi-plus-lg"></i> افزودن</button>
        </div>
    </form>
</div>

<!-- ===== لیست کاربران ===== -->
<div class="card">
    <div class="card-header"><i class="bi bi-table"></i> لیست کاربران</div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern mb-0">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>نام</th>
                        <th>نام کاربری</th>
                        <th>نقش</th>
                        <th>تاریخ عضویت</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $counter = 1; ?>
                    <?php foreach($users as $user): ?>
                    <tr>
                        <td><?php echo toPersianNumbers($counter++); ?></td>
                        <td><?php echo htmlspecialchars($user['fullname']); ?></td>
                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                        <td>
                            <span class="badge bg-<?php echo $roleColors[$user['level']] ?? 'secondary'; ?>">
                                <?php echo $roleLabels[$user['level']] ?? $user['level']; ?>
                            </span>
                        </td>
                        <td><?php echo convertToPersianDateFa($user['created_at']); ?></td>
                        <td>
                            <button class="btn btn-sm btn-primary" data-bs-toggle="collapse" data-bs-target="#editUser<?php echo $user['id']; ?>"><i class="bi bi-pencil-fill"></i></button>
                            <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('آیا از حذف کاربر «<?php echo htmlspecialchars($user['fullname']); ?>» مطمئن هستید؟');">
                                    <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                    <button type="submit" name="delete_user" class="btn btn-sm btn-danger"><i class="bi bi-trash3-fill"></i></button>
                                </form>
                            <?php endif; ?>
                            <div class="collapse mt-2" id="editUser<?php echo $user['id']; ?>">
                                <form method="POST" class="row g-1">
                                    <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                    <div class="col-md-4">
                                        <input type="text" name="fullname" class="form-control form-control-sm" value="<?php echo htmlspecialchars($user['fullname']); ?>" required>
                                    </div>
                                    <div class="col-md-3">
                                        <input type="password" name="password" class="form-control form-control-sm" placeholder="رمز جدید (اختیاری)">
                                    </div>
                                    <div class="col-md-3">
                                        <select name="level" class="form-select form-select-sm">
                                            <option value="admin" <?php echo $user['level'] == 'admin' ? 'selected' : ''; ?>>مدیر ارشد</option>
                                            <option value="expert" <?php echo $user['level'] == 'expert' ? 'selected' : ''; ?>>مسئول ثبت‌نام</option>
                                            <option value="reporter" <?php echo $user['level'] == 'reporter' ? 'selected' : ''; ?>>گزارشگر</option>
                                            <option value="representative" <?php echo $user['level'] == 'representative' ? 'selected' : ''; ?>>معرف‌کننده</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <button type="submit" name="edit_user" class="btn btn-sm btn-success w-100">ذخیره</button>
                                    </div>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ===== لیست معرف‌کنندگان ===== -->
<?php if (!empty($representatives)): ?>
<div class="rep-list mt-4">
    <strong class="d-block mb-1"><i class="bi bi-person-check-fill me-1"></i>لیست معرف‌کنندگان (Representatives)</strong>
    <?php foreach($representatives as $rep): ?>
        <span class="rep-item"><?php echo htmlspecialchars($rep['fullname']); ?></span>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?php include '../includes/footer.php'; ?>