# 🚀 Complete Deployment Guide

**Version:** 2.0.0
**Date:** 2025-12-26
**Status:** ✅ Ready for Production

---

## 📋 Table of Contents

1. [System Overview](#system-overview)
2. [Folder Structure](#folder-structure)
3. [Pre-Deployment Checklist](#pre-deployment-checklist)
4. [Database Setup](#database-setup)
5. [Configuration](#configuration)
6. [Testing](#testing)
7. [Default Credentials](#default-credentials)
8. [Troubleshooting](#troubleshooting)

---

## 🎯 System Overview

### Features Implemented

✅ **Multi-User Authentication System**
- Admin dashboard with full access
- User dashboard with limited access
- Role-based access control (RBAC)
- Session-based authentication
- Failed login protection (5 attempts, 30-min lockout)

✅ **Shortlink Management**
- Random subdomain generation (6-char alphanumeric)
- Bulk creation (1-25 links at once)
- Global domain (random) vs Specific domain selection
- Open Graph meta tags support
- Shim page support
- User ownership tracking

✅ **Domain Management**
- Admin: Global domains (visible to all users)
- Users: Private domains (visible only to owner)
- Wildcard subdomain support
- Cloudflare DNS auto-creation
- cPanel subdomain automation

✅ **Security Features**
- Password hashing (bcrypt)
- CSRF protection on all forms
- Session token validation
- Activity logging
- IP address tracking
- Mini WAF (SQL injection, XSS protection)

---

## 📁 Folder Structure

### Current Structure (Before Rename)
```
E:\.rounting/
├── domain-dashboard-final/     ← RENAME THIS to "dashboard"
│   ├── public/                 (Admin Dashboard)
│   │   ├── login.php           ✅ Admin login page
│   │   ├── logout.php          ✅ Admin logout
│   │   ├── index.php           ✅ Admin dashboard (protected)
│   │   ├── ajax/
│   │   │   ├── create-user.php       ✅ Create user
│   │   │   ├── get-users.php         ✅ List users
│   │   │   ├── update-user.php       ✅ Update user
│   │   │   ├── delete-user.php       ✅ Delete user
│   │   │   └── create-bulk-shortlinks.php  ✅ Create shortlinks
│   │   └── components/
│   │       └── shortlink-form.html   ✅ Shortlink creation form
│   │
│   ├── user-dashboard/         (User Dashboard)
│   │   ├── login.php           ✅ User login page
│   │   ├── logout.php          ✅ User logout
│   │   ├── index.php           ✅ User dashboard (protected)
│   │   └── ajax/
│   │       ├── get-my-shortlinks.php   ✅ User's shortlinks
│   │       ├── get-my-domains.php      ✅ User's domains
│   │       ├── add-my-domain.php       ✅ Add domain
│   │       └── delete-my-domain.php    ✅ Delete domain
│   │
│   ├── bootstrap/
│   │   └── init.php            ✅ Updated with AuthService
│   │
│   ├── src/
│   │   ├── Service/
│   │   │   ├── AuthService.php         ✅ Authentication
│   │   │   ├── SubdomainGenerator.php  ✅ Random subdomain
│   │   │   └── ShortlinkService.php    ✅ Updated with user_id
│   │   ├── Middleware/
│   │   │   └── AuthMiddleware.php      ✅ Route protection
│   │   └── Repository/
│   │       ├── DomainRepository.php    ✅ Updated with user methods
│   │       └── ShortlinkRepository.php ✅ Updated with user_id
│   │
│   └── database-migrations/
│       ├── 010_create_users_table.sql        ✅ Users & sessions
│       ├── 011_add_user_domains.sql          ✅ User domain ownership
│       └── 012_add_shortlink_user_id.sql     ✅ Shortlink ownership
│
└── redirect/                   (OUTSIDE dashboard folder)
    ├── s.php                   ✅ Shortlink redirect handler
    ├── shim.php                ✅ Intermediate page
    └── .htaccess               ✅ Clean URLs
```

### Target Structure (After Rename)
```
E:\.rounting/
├── dashboard/                  ← RENAMED from domain-dashboard-final
│   ├── public/                 (Admin Dashboard)
│   ├── user-dashboard/         (User Dashboard)
│   ├── bootstrap/
│   ├── src/
│   └── database-migrations/
│
└── redirect/                   (Same level as dashboard)
```

---

## ✅ Pre-Deployment Checklist

### Step 1: Rename Folder

**IMPORTANT:** Close all terminals, editors, and IDE windows first!

```bash
# Windows Command Prompt
cd E:\.rounting
rename domain-dashboard-final dashboard

# OR Windows PowerShell
cd E:\.rounting
Rename-Item -Path "domain-dashboard-final" -NewName "dashboard"

# Linux/Mac
cd /home/username
mv domain-dashboard-final dashboard
```

**Verify:**
```bash
ls -la | grep dashboard
# Should show: dashboard/ (not domain-dashboard-final/)
```

### Step 2: Verify Redirect Folder Location

**Correct location:** `E:\.rounting\redirect\` (OUTSIDE dashboard folder)

```bash
# Should exist at same level as dashboard:
E:\.rounting/
├── dashboard/
└── redirect/
```

If redirect folder is inside dashboard, move it:
```bash
# Windows
cd E:\.rounting
move dashboard\redirect redirect

# Linux/Mac
mv dashboard/redirect ./redirect
```

---

## 🗄️ Database Setup

### Step 1: Create Database User (Optional but Recommended)

```sql
-- MySQL/MariaDB
CREATE DATABASE IF NOT EXISTS dashboard_db
    CHARACTER SET utf8mb4
    COLLATE utf8mb4_unicode_ci;

CREATE USER 'dashboard_user'@'localhost' IDENTIFIED BY 'STRONG_PASSWORD_HERE';

GRANT ALL PRIVILEGES ON dashboard_db.* TO 'dashboard_user'@'localhost';

FLUSH PRIVILEGES;
```

### Step 2: Run Migrations in Order

**Important:** Run ALL migrations, including the new ones!

```bash
cd E:\.rounting\dashboard

# Windows users: Use full path to mysql.exe
# Example: "C:\xampp\mysql\bin\mysql.exe"

# Migration 010: Users, sessions, activity logs
mysql -u dashboard_user -p dashboard_db < database-migrations/010_create_users_table.sql

# Migration 011: User domain ownership
mysql -u dashboard_user -p dashboard_db < database-migrations/011_add_user_domains.sql

# Migration 012: Shortlink user ownership
mysql -u dashboard_user -p dashboard_db < database-migrations/012_add_shortlink_user_id.sql
```

### Step 3: Verify Tables Created

```sql
USE dashboard_db;

-- Should show these tables:
SHOW TABLES;
-- Expected output:
-- - users
-- - user_sessions
-- - user_activity_logs
-- - domains (updated with user_id, is_global columns)
-- - shortlinks (updated with user_id column)

-- Verify admin user exists:
SELECT * FROM users WHERE username = 'admin';
-- Should return 1 row with role='admin'

-- Verify columns added:
DESCRIBE domains;
-- Should show: user_id, is_global columns

DESCRIBE shortlinks;
-- Should show: user_id column
```

---

## ⚙️ Configuration

### Step 1: Update .env File

```bash
cd E:\.rounting\dashboard
```

**Edit `.env` file:**
```ini
# Database Configuration
DB_HOST=localhost
DB_NAME=dashboard_db
DB_USER=dashboard_user
DB_PASS=STRONG_PASSWORD_HERE

# cPanel API (for subdomain automation)
CPANEL_HOST=your-server.com
CPANEL_USERNAME=your_cpanel_username
CPANEL_API_TOKEN=your_api_token_here
CPANEL_PORT=2083

# Cloudflare API (for DNS automation)
CLOUDFLARE_EMAIL=your@email.com
CLOUDFLARE_API_KEY=your_cloudflare_api_key_here

# Application Settings
APP_ENV=production
APP_DEBUG=false
```

### Step 2: Update Existing Domains to Global

**If you have existing domains, mark them as global:**

```sql
UPDATE domains
SET is_global = 1, user_id = NULL
WHERE user_id IS NULL;
```

This makes existing admin domains visible to all users.

---

## 🧪 Testing

### Test 1: Admin Login

1. **Visit:** `http://localhost/login.php`
   (or `https://your-domain.com/login.php`)

2. **Enter credentials:**
   - Username: `admin`
   - Password: `admin123`

3. **Expected result:**
   - Redirects to `/index.php`
   - Shows "Domain Dashboard (Admin)" with welcome message
   - Displays: "👤 Administrator" and Logout button
   - All tabs accessible

4. **⚠️ SECURITY:** Change admin password immediately!
   ```sql
   UPDATE users
   SET password_hash = '$2y$10$YOUR_NEW_HASH_HERE'
   WHERE username = 'admin';
   ```
   Generate hash with:
   ```php
   <?php echo password_hash('your_new_password', PASSWORD_BCRYPT); ?>
   ```

### Test 2: Create Test User

**Via MySQL:**
```sql
INSERT INTO users (username, email, password_hash, full_name, role, status)
VALUES (
    'testuser',
    'test@example.com',
    '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
    'Test User',
    'user',
    'active'
);
-- Password: admin123
```

**OR via Admin Dashboard (Recommended):**
1. Login as admin
2. Go to "Users" tab (if implemented in UI)
3. Click "Create User"
4. Fill form and submit

### Test 3: User Login

1. **Visit:** `http://localhost/user-dashboard/login.php`

2. **Enter test user credentials:**
   - Username: `testuser`
   - Password: `admin123`

3. **Expected result:**
   - Redirects to `/user-dashboard/index.php`
   - Shows "Shortlink Dashboard" with welcome message
   - Three tabs: Create Shortlinks, My Shortlinks, My Domains
   - Can create shortlinks and domains

### Test 4: Create Shortlink (as User)

1. Login as test user
2. Go to "Create Shortlinks" tab
3. Fill form:
   - Destination URL: `https://example.com`
   - Title: `Test Link` (optional)
   - Domain: Select "🌐 Global Domain (Random)" or specific domain
   - Bulk Count: `3`
4. Click "Create Shortlinks"
5. Expected: 3 URLs generated with random subdomains
6. Go to "My Shortlinks" tab
7. Expected: See the 3 shortlinks created

### Test 5: Add User Domain

1. Login as test user
2. Go to "My Domains" tab
3. Click "Add Domain"
4. Fill form:
   - Domain Name: `mytest.com`
   - Subdomain: `*` (wildcard)
   - Cloudflare Sync: Checked (if API configured)
5. Click "Add Domain"
6. Expected: Domain added and visible in dropdown

### Test 6: Verify Domain Visibility

**As User:**
- Should see: Global domains (admin-added) + Own domains
- Should NOT see: Other users' private domains

**As Admin:**
- Should see: All global domains
- (Admin can see all via database, but UI shows global by default)

### Test 7: Test Shortlink Redirect

1. Get a generated shortlink URL (e.g., `http://abc123.example.com/xyz456`)
2. Open in browser
3. Expected: Redirects to destination URL
4. Click count increments in database

---

## 🔐 Default Credentials

### Admin Account

```
Login URL: /login.php
Username:  admin
Email:     admin@example.com
Password:  admin123

⚠️ CHANGE THIS PASSWORD IMMEDIATELY IN PRODUCTION!
```

### Test User Account

```
Login URL: /user-dashboard/login.php
Username:  testuser
Email:     test@example.com
Password:  admin123

(Created manually via SQL or admin dashboard)
```

---

## 🐛 Troubleshooting

### Issue 1: "Session token not found" after login

**Cause:** Session not starting properly

**Fix:**
```php
// Check bootstrap/init.php lines 138-141:
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
```

**Verify:** Clear browser cookies and try again.

---

### Issue 2: "Access denied. Admin role required."

**Cause:** User trying to access admin dashboard

**Fix:** Users must use `/user-dashboard/login.php`, not `/login.php`

**Admin URLs:**
- `/login.php` → Admin login
- `/index.php` → Admin dashboard

**User URLs:**
- `/user-dashboard/login.php` → User login
- `/user-dashboard/index.php` → User dashboard

---

### Issue 3: "An error occurred while loading domains"

**Cause:** Database migration not run or column missing

**Fix:**
```sql
-- Check if columns exist:
DESCRIBE domains;
-- Should show: user_id, is_global

-- If missing, run migration:
mysql -u user -p database < database-migrations/011_add_user_domains.sql
```

---

### Issue 4: User domains not appearing in dropdown

**Cause:** Domain not marked with user_id or is_global flag

**Fix:**
```sql
-- Check domain ownership:
SELECT id, domain, user_id, is_global FROM domains;

-- Mark admin domains as global:
UPDATE domains SET is_global = 1, user_id = NULL WHERE user_id IS NULL;

-- Check user's private domain:
SELECT * FROM domains WHERE user_id = 2;  -- Replace with user ID
```

---

### Issue 5: "Cannot create shortlink" - user_id error

**Cause:** Migration 012 not run

**Fix:**
```sql
-- Check if user_id column exists in shortlinks:
DESCRIBE shortlinks;

-- If missing, run migration:
mysql -u user -p database < database-migrations/012_add_shortlink_user_id.sql
```

---

### Issue 6: "Too many failed login attempts"

**Cause:** Account locked after 5 failed attempts

**Fix:**
```sql
-- Reset failed attempts:
UPDATE users
SET failed_login_attempts = 0, locked_until = NULL
WHERE username = 'admin';
```

---

### Issue 7: Logout redirects to wrong page

**Expected behavior:**
- Admin logout → `/login.php`
- User logout → `/user-dashboard/login.php`

**Fix:** Check logout.php files:
- `public/logout.php` → redirects to `/login.php`
- `user-dashboard/logout.php` → redirects to `/user-dashboard/login.php`

---

## 📊 Database Schema Summary

### New Tables

**users**
- Primary authentication table
- Columns: id, username, email, password_hash, full_name, role, status
- Indexes: uk_username (unique), uk_email (unique)

**user_sessions**
- Active session tracking
- Columns: id, user_id, session_token, ip_address, user_agent, expires_at
- Indexes: uk_session_token (unique), idx_user_id, idx_expires

**user_activity_logs**
- Audit trail for user actions
- Columns: id, user_id, action, ip_address, user_agent, details, created_at
- Indexes: idx_user_id, idx_created_at

### Updated Tables

**domains**
- Added: user_id INT (nullable), is_global TINYINT(1) default 0
- Indexes: idx_user_id, idx_is_global

**shortlinks**
- Added: user_id INT (nullable)
- Indexes: idx_user_id

---

## 🎉 Post-Deployment Steps

1. **Change Admin Password**
   ```sql
   UPDATE users
   SET password_hash = '$2y$10$NEW_HASH_HERE'
   WHERE username = 'admin';
   ```

2. **Create Real Users**
   - Login as admin
   - Use admin dashboard to create users
   - Users will receive credentials to login at `/user-dashboard/login.php`

3. **Add Global Domains (Admin)**
   - Login as admin
   - Add domains that all users can use
   - These appear in all users' dropdowns

4. **Test User Workflow**
   - Login as user
   - Create shortlink
   - Add private domain
   - Verify domain only visible to that user

5. **Monitor Logs**
   ```sql
   -- Check recent logins:
   SELECT * FROM user_activity_logs ORDER BY created_at DESC LIMIT 20;

   -- Check active sessions:
   SELECT u.username, s.ip_address, s.created_at
   FROM user_sessions s
   JOIN users u ON s.user_id = u.id
   WHERE s.expires_at > NOW();
   ```

---

## 📝 API Endpoints Reference

### Admin Endpoints (Require Admin Role)

```
POST /ajax/create-user.php           Create new user
GET  /ajax/get-users.php              List all users
POST /ajax/update-user.php            Update user
POST /ajax/delete-user.php            Delete user
```

### User Endpoints (Require User or Admin Role)

```
POST /ajax/create-bulk-shortlinks.php    Create shortlinks
GET  /user-dashboard/ajax/get-my-shortlinks.php   Get user's shortlinks
GET  /user-dashboard/ajax/get-my-domains.php      Get user's domains
POST /user-dashboard/ajax/add-my-domain.php       Add domain
POST /user-dashboard/ajax/delete-my-domain.php    Delete domain
```

### Authentication Endpoints (Public)

```
GET  /login.php                       Admin login page
POST /login.php                       Admin login submit
GET  /logout.php                      Admin logout

GET  /user-dashboard/login.php        User login page
POST /user-dashboard/login.php        User login submit
GET  /user-dashboard/logout.php       User logout
```

---

## 🔒 Security Recommendations

1. **Change default admin password immediately**
2. **Use strong passwords (12+ characters, mixed case, numbers, symbols)**
3. **Enable HTTPS in production**
4. **Set restrictive file permissions:**
   ```bash
   chmod 644 .env
   chmod 755 public/ user-dashboard/
   chmod 600 database-migrations/*.sql
   ```
5. **Disable error display in production:**
   ```php
   // bootstrap/init.php - Update line 5-6:
   error_reporting(E_ALL);
   ini_set('display_errors', '0');  // Change to '0'
   ```
6. **Enable MySQL slow query log**
7. **Regular database backups**
8. **Monitor user_activity_logs for suspicious activity**

---

## ✅ Deployment Complete!

Your multi-user domain dashboard and shortlink system is now ready for production use.

**Next Steps:**
1. ✅ Rename folder to `dashboard`
2. ✅ Run all database migrations (010, 011, 012)
3. ✅ Update .env configuration
4. ✅ Change admin password
5. ✅ Create test user and verify workflows
6. ✅ Add global domains (admin)
7. ✅ Share user login URL with team: `/user-dashboard/login.php`

---

**For support or questions, refer to:**
- `AUTHENTICATION_IMPLEMENTATION.md` - Authentication system details
- `SHORTLINK_FEATURES.md` - Shortlink features guide
- `QUICK_START.md` - Quick start guide

**Last Updated:** 2025-12-26
**Version:** 2.0.0
