# 🔐 Ensi.lk Admin Panel

A secure, modern admin panel for managing users of the Ensi.lk English learning app.

## 📋 Features

### ✅ User Management
- **Create Users**: Add new users with custom levels (0-10)
- **Edit Users**: Modify user details, levels, and verification status
- **Delete Users**: Soft delete users (data preserved)
- **Search & Filter**: Find users by name, email, level, or status
- **User Levels**: 11 levels (0-10) with color-coded badges

### 📊 Dashboard
- Real-time statistics (Total, Verified, New Today, Deleted)
- Recent users list
- Quick access to all management features

### 📋 Activity Logs
- Track all admin activities
- IP address logging
- User agent tracking
- Timestamps for all actions
- Pagination for large datasets

### 🔒 Security Features
- Password hashing (bcrypt)
- Session management with timeout
- CSRF protection ready
- SQL injection prevention (PDO prepared statements)
- XSS protection (input sanitization)
- Activity logging for audit trails
- Login attempt monitoring
- Direct file access prevention (.htaccess)

---

## 🚀 Installation

### Step 1: Upload Files
Upload the entire `admin` folder to your server:
```
www.howdoyou.space/admin/
```

### Step 2: Create Database Tables
Run the SQL schema to create admin tables:

1. Go to phpMyAdmin
2. Select your database: `playbdqv_engweb`
3. Click "SQL" tab
4. Copy and paste the contents of `admin_schema.sql`
5. Click "Go"

This will create:
- ✅ `admins` table (for admin users)
- ✅ `admin_logs` table (for activity tracking)
- ✅ Default admin account (username: `admin`, password: `admin123`)

### Step 3: Configure Database Connection
Edit `admin/config.php` if your database credentials are different:

```php
define('DB_HOST', 'localhost');
define('DB_NAME', 'playbdqv_engweb');
define('DB_USER', 'playbdqv_engweb');
define('DB_PASS', 'your_password_here');
```

### Step 4: Set Permissions
Ensure proper file permissions:
```bash
chmod 755 admin/
chmod 644 admin/*.php
chmod 600 admin/config.php
```

---

## 🔑 Default Login Credentials

**⚠️ CHANGE THESE IMMEDIATELY AFTER FIRST LOGIN!**

```
Username: admin
Password: admin123
```

**Access URL:**
```
https://www.howdoyou.space/admin/
```

---

## 📖 How to Use

### Login
1. Go to: `https://www.howdoyou.space/admin/`
2. Enter username: `admin`
3. Enter password: `admin123`
4. Click "Login to Admin Panel"

### Dashboard
- View real-time statistics
- See recent user registrations
- Quick access to all features

### Manage Users
1. Click "👥 Users" in the navigation
2. **Search**: Use the search box to find users by name or email
3. **Filter**: Filter by level (0-10) or status (Verified/Pending)
4. **Add User**:
   - Click "+ Add User" button
   - Fill in: Name, Email, Password, Level
   - Click "Add User"
5. **Edit User**:
   - Click the ✏️ edit icon next to any user
   - Update details
   - Toggle email verification
   - Click "Update User"
6. **Delete User**:
   - Click the 🗑️ delete icon
   - Confirm deletion
   - User will be soft-deleted (data preserved)

### View Activity Logs
1. Click "📋 Activity Logs" in navigation
2. View all admin activities with timestamps
3. Track who did what and when
4. Use pagination to browse historical logs

---

## 👥 User Levels Explained

The system supports 11 user levels (0-10):

| Level | Badge Color | Description |
|-------|-------------|-------------|
| 0 | Gray | Beginner |
| 1 | Light Blue | Elementary |
| 2 | Teal | Pre-Intermediate |
| 3 | Green | Intermediate |
| 4 | Light Green | Upper-Intermediate |
| 5 | Yellow | Advanced |
| 6 | Orange | Proficient |
| 7 | Deep Orange | Expert |
| 8 | Pink | Master |
| 9 | Purple | Native-like |
| 10 | Gradient | Champion |

---

## 🔒 Security Best Practices

### Immediately After Installation:

1. **Change Default Admin Password**:
   - Login with default credentials
   - Go to phpMyAdmin
   - Select `admins` table
   - Update the password_hash for admin user
   - Use this command to generate new hash:
   ```php
   echo password_hash('your_new_password', PASSWORD_DEFAULT);
   ```

2. **Create New Admin Account**:
   ```sql
   INSERT INTO admins (username, password_hash, full_name, email, role) 
   VALUES ('your_username', '$2y$10$...your_hash...', 'Your Name', 'your@email.com', 'super_admin');
   ```

3. **Delete Default Admin**:
   ```sql
   DELETE FROM admins WHERE username = 'admin';
   ```

4. **Restrict Access**:
   - Add IP whitelist in `.htaccess`:
   ```apache
   Order Deny,Allow
   Deny from all
   Allow from 123.456.789.0
   ```

5. **Use HTTPS**:
   - Always access admin panel via HTTPS
   - Force HTTPS in `.htaccess`:
   ```apache
   RewriteEngine On
   RewriteCond %{HTTPS} off
   RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
   ```

---

## 🛠️ Troubleshooting

### Can't Login
- Check database connection in `config.php`
- Verify `admins` table exists
- Check default credentials: `admin` / `admin123`
- Clear browser cookies and try again

### "Session expired" message
- Session timeout is 1 hour by default
- Change timeout in `config.php`:
  ```php
  define('ADMIN_SESSION_TIMEOUT', 3600); // in seconds
  ```

### Changes Not Saving
- Check PHP error logs
- Verify database credentials
- Check file permissions (644 for PHP files)
- Ensure PDO MySQL extension is enabled

### "Permission Denied" errors
- Check file permissions: `chmod 644 *.php`
- Check folder permissions: `chmod 755 admin/`
- Ensure web server user has read access

---

## 📂 File Structure

```
admin/
├── index.php              # Entry point (redirects to dashboard)
├── login.php              # Admin login page
├── logout.php             # Logout handler
├── dashboard.php          # Dashboard with statistics
├── users.php              # User management page
├── logs.php               # Activity logs page
├── config.php             # Database & security config
├── .htaccess             # Apache security rules
├── api/
│   └── users.php         # User CRUD API endpoints
├── assets/
│   ├── style.css         # Admin panel styles
│   └── script.js         # JavaScript functions
└── includes/
    └── header.php        # Navigation header
```

---

## 🔄 API Endpoints

### `/admin/api/users.php`

All requests use POST method with `action` parameter:

**Add User**
```
POST action=add_user
Parameters: name, email, password, user_level
```

**Get User**
```
POST action=get_user
Parameters: user_id
```

**Update User**
```
POST action=update_user
Parameters: user_id, name, email, user_level, email_verified
```

**Delete User**
```
POST action=delete_user
Parameters: user_id
```

---

## 🎨 Design Features

- **Modern UI**: Clean, gradient-based design
- **Responsive**: Works on desktop, tablet, and mobile
- **Intuitive**: Easy-to-use interface with modals
- **Fast**: Optimized for performance
- **Accessible**: Keyboard navigation support

---

## 📊 Database Schema

### `admins` Table
```sql
id              INT (Primary Key)
username        VARCHAR(50) UNIQUE
password_hash   VARCHAR(255)
full_name       VARCHAR(100)
email           VARCHAR(255)
role            ENUM('super_admin', 'admin', 'moderator')
is_active       TINYINT(1)
last_login      TIMESTAMP
created_at      TIMESTAMP
updated_at      TIMESTAMP
```

### `admin_logs` Table
```sql
id              INT (Primary Key)
admin_id        INT (Foreign Key → admins.id)
action          VARCHAR(100)
description     TEXT
ip_address      VARCHAR(45)
user_agent      TEXT
created_at      TIMESTAMP
```

---

## 🚨 Important Notes

1. **Never commit config.php** to public repositories
2. **Always use HTTPS** in production
3. **Regular backups** of admin_logs table recommended
4. **Monitor activity logs** for suspicious behavior
5. **Keep PHP updated** for security patches
6. **Use strong passwords** for all admin accounts

---

## 📞 Support

If you encounter any issues:
1. Check error logs: `/admin/logs/error.log`
2. Check PHP error logs on server
3. Verify database connection
4. Review activity logs for clues

---

## 📜 License

This admin panel is part of the Ensi.lk project.
© 2024 Ensi.lk - All rights reserved.

---

## ✅ Quick Setup Checklist

- [ ] Upload `admin` folder to server
- [ ] Run `admin_schema.sql` in phpMyAdmin
- [ ] Verify database credentials in `config.php`
- [ ] Set file permissions (755/644)
- [ ] Test login with default credentials
- [ ] Change default admin password
- [ ] Create your personal admin account
- [ ] Delete default admin account
- [ ] Test creating/editing/deleting users
- [ ] Review security settings
- [ ] Add IP whitelist (optional)
- [ ] Enable HTTPS (required for production)

**Done! Your admin panel is ready! 🎉**
