# CMS Setup and Testing Guide

## 🚀 Complete Setup Instructions

Follow these steps in order to set up and test the CMS system.

---

## Step 1: Execute Database Migration

### Option A: Using phpMyAdmin (Recommended)

1. Open phpMyAdmin: http://localhost/phpmyadmin
2. Select database: `obgyn_research_platform`
3. Click the "SQL" tab
4. Open `database/cms_migration.sql` in a text editor
5. Copy ALL contents (Ctrl+A, Ctrl+C)
6. Paste into phpMyAdmin SQL box
7. Click "Go" button
8. Wait for success message

**Expected Result:** You should see multiple "Query OK" messages indicating tables were created.

### Option B: Using MySQL Command Line

```bash
# Navigate to the database directory
cd database

# Execute migration
mysql -u obgyn_research_platform_user -p obgyn_research_platform < cms_migration.sql

# Enter password when prompted: 2UFAT605IQCLmyyd
```

### Verify Migration Success

Run this query in phpMyAdmin:
```sql
SHOW TABLES LIKE 'cms_%';
```

You should see 12 tables:
- cms_features
- cms_hero_sections
- cms_media
- cms_menu_items
- cms_menus
- cms_pages
- cms_posts
- cms_slider_items
- cms_sliders
- cms_stats
- cms_team_members
- cms_testimonials
- cms_widgets

---

## Step 2: Create Admin User

### Using PHP Script (Recommended)

```bash
# Navigate to database directory
cd database

# Run the admin user creation script
php create_admin_user.php
```

**Follow the prompts:**
- If admin user exists, choose option 1 to update password
- If no admin exists, it will create one automatically

### Default Admin Credentials

After running the script, you'll get:

```
Email: admin@obgynresearch.com
Password: Admin@123456
```

**IMPORTANT:** Change this password after first login!

### Manual Creation (Alternative)

If the script doesn't work, run this SQL in phpMyAdmin:

```sql
-- Create admin user
INSERT INTO users (
    email, password, first_name, last_name, 
    role_id, status, email_verified, created_at
) VALUES (
    'admin@obgynresearch.com',
    '$2y$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewY5GyYIxIYJuQBK', -- Admin@123456
    'Super',
    'Admin',
    1,
    'active',
    1,
    NOW()
);

-- Get the user ID (check the result of above query)
SET @user_id = LAST_INSERT_ID();

-- Create researcher profile
INSERT INTO researcher_profiles (
    user_id, title, specialization, bio, verified_badge, created_at
) VALUES (
    @user_id,
    'Platform Administrator',
    'System Administration',
    'Super administrator with full access to all platform features.',
    1,
    NOW()
);
```

---

## Step 3: Run Testing Script

```bash
# Navigate to database directory
cd database

# Run the testing script
php test_cms_features.php
```

### What the Testing Script Does:

1. **Tests Database Connection**
2. **Verifies All CMS Tables Exist**
3. **Checks Email Templates** (should be 6)
4. **Checks CMS Settings** (should be 16+)
5. **Verifies Admin User Exists**
6. **Tests CRUD Operations** (Create, Read, Update, Delete pages)
7. **Creates Sample Data:**
   - 4 sample pages (About, Contact, Privacy, Terms)
   - 4 sample features
   - 4 sample statistics
   - 3 sample testimonials
8. **Checks File Permissions**

### Expected Output:

```
===========================================
CMS Features Testing Script
===========================================

✓ Database Connection
✓ Table: cms_pages
✓ Table: cms_posts
... (all tables)
✓ Email Templates
✓ CMS Settings
✓ Admin User Exists
✓ Create CMS Page
✓ Read CMS Page
✓ Update CMS Page
✓ Delete CMS Page
✓ Sample Page: About Us
... (all sample data)

===========================================
Test Summary
===========================================
Total Tests: 35+
Passed: 35+ ✓
Failed: 0 ✗
Success Rate: 100%
===========================================

🎉 All tests passed! CMS is ready to use.
```

---

## Step 4: Login and Test CMS

### 4.1 Login to Admin Panel

1. Open: http://localhost/obgyn-research-platform/login.php
2. Enter credentials:
   - Email: `admin@obgynresearch.com`
   - Password: `Admin@123456`
3. Click "Login"

### 4.2 Access CMS

1. After login, you'll be redirected to the admin dashboard
2. Look at the left sidebar
3. Find the "CONTENT MANAGEMENT" section
4. You should see these menu items:
   - Pages
   - Blog Posts
   - Menus
   - Media Library
   - Homepage
   - Branding
   - Contact Info
   - Team
   - Announcements
   - Email Templates

### 4.3 Test Pages Management

1. Click **"CMS → Pages"**
2. You should see 4 sample pages created by the testing script
3. Click **"Add New Page"** button
4. Fill in the form:
   - Title: "Test Page"
   - Content: Use the rich text editor to add content
   - Status: Published
5. Click **"Create Page"**
6. Verify the page appears in the list

### 4.4 Test Page Editor

1. Click **"Edit"** on any page
2. Test the TinyMCE editor:
   - Try bold, italic, underline
   - Add headings
   - Create lists
   - Insert links
3. Test SEO fields:
   - Add meta title
   - Add meta description
   - Add keywords
4. Click **"Update Page"**
5. Verify changes are saved

### 4.5 Test Search Functionality

1. In the pages list, use the search box
2. Type a page title
3. Verify the table filters in real-time

### 4.6 Test Quick Actions

1. Click the **"View"** icon (eye) to see the page
2. Click the **"Toggle Status"** icon to change draft/published
3. Click the **"Delete"** icon to remove a test page

---

## Step 5: Verify Sample Data

### Check Sample Pages

Run this SQL query:
```sql
SELECT id, title, slug, status FROM cms_pages ORDER BY created_at DESC;
```

You should see:
- About Us
- Contact
- Privacy Policy
- Terms of Service

### Check Sample Features

Run this SQL query:
```sql
SELECT id, title, icon, description FROM cms_features;
```

You should see 4 features with icons and descriptions.

### Check Sample Stats

Run this SQL query:
```sql
SELECT id, label, value, icon FROM cms_stats;
```

You should see 4 statistics counters.

### Check Sample Testimonials

Run this SQL query:
```sql
SELECT id, name, title, rating FROM cms_testimonials;
```

You should see 3 testimonials with 4-5 star ratings.

---

## 🧪 Manual Testing Checklist

### Pages Management
- [ ] Can access cms-pages.php
- [ ] Can see list of pages
- [ ] Search functionality works
- [ ] Can click "Add New Page"
- [ ] Can create a new page
- [ ] TinyMCE editor loads correctly
- [ ] Auto-slug generation works
- [ ] Can save page as draft
- [ ] Can publish page
- [ ] Can edit existing page
- [ ] Can toggle page status
- [ ] Can delete page
- [ ] Statistics show correct counts

### Page Editor
- [ ] Rich text editor works (bold, italic, etc.)
- [ ] Can add headings
- [ ] Can create lists
- [ ] Can insert links
- [ ] Can insert images
- [ ] SEO fields save correctly
- [ ] Meta title field works
- [ ] Meta description field works
- [ ] Open Graph fields work
- [ ] Language selection works
- [ ] Status dropdown works
- [ ] Form validation works
- [ ] CSRF protection works

### Security
- [ ] Non-admin users cannot access CMS
- [ ] CSRF tokens are validated
- [ ] SQL injection attempts fail
- [ ] XSS attempts are prevented
- [ ] Activity is logged

### UI/UX
- [ ] Sidebar menu displays correctly
- [ ] CMS section is visible
- [ ] Icons display properly
- [ ] Responsive design works on mobile
- [ ] Buttons are clickable
- [ ] Forms are user-friendly
- [ ] Success messages appear
- [ ] Error messages are clear

---

## 🐛 Troubleshooting

### Issue: "Table doesn't exist" error

**Solution:**
```bash
# Re-run the migration
mysql -u obgyn_research_platform_user -p obgyn_research_platform < database/cms_migration.sql
```

### Issue: "Access denied" when accessing CMS

**Solution:**
1. Make sure you're logged in
2. Check your user role:
```sql
SELECT u.email, r.name as role 
FROM users u 
JOIN roles r ON u.role_id = r.id 
WHERE u.email = 'admin@obgynresearch.com';
```
3. Role should be "super_admin" (role_id = 1)

### Issue: TinyMCE editor not loading

**Solution:**
1. Check internet connection (TinyMCE loads from CDN)
2. Check browser console for errors (F12)
3. Try a different browser
4. Clear browser cache

### Issue: "CSRF token mismatch" error

**Solution:**
1. Clear browser cookies
2. Logout and login again
3. Make sure sessions are working:
```php
<?php
session_start();
echo session_id();
?>
```

### Issue: Sample data not created

**Solution:**
```bash
# Re-run the testing script
php database/test_cms_features.php
```

### Issue: Cannot upload files

**Solution:**
1. Check directory permissions:
```bash
chmod 755 assets/uploads
chmod 755 assets/uploads/profiles
chmod 755 assets/uploads/documents
chmod 755 assets/uploads/studies
```

2. Check PHP upload settings in php.ini:
```ini
upload_max_filesize = 10M
post_max_size = 10M
```

---

## 📊 Verification Queries

Run these SQL queries to verify everything is set up correctly:

### Check All CMS Tables
```sql
SELECT TABLE_NAME 
FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'obgyn_research_platform' 
AND TABLE_NAME LIKE 'cms_%';
```

### Check Admin User
```sql
SELECT u.id, u.email, u.first_name, u.last_name, r.name as role, u.status
FROM users u
JOIN roles r ON u.role_id = r.id
WHERE u.role_id = 1;
```

### Check Email Templates
```sql
SELECT id, name, slug, category FROM email_templates;
```

### Check CMS Settings
```sql
SELECT key_name, value, category 
FROM settings 
WHERE category = 'cms';
```

### Check Sample Pages
```sql
SELECT id, title, slug, status, language, created_at 
FROM cms_pages 
ORDER BY created_at DESC;
```

---

## 🎯 Success Criteria

Your CMS setup is successful if:

1. ✅ All 12+ CMS tables exist in database
2. ✅ 6 email templates are present
3. ✅ 16+ CMS settings are configured
4. ✅ Admin user can login
5. ✅ CMS menu appears in admin sidebar
6. ✅ Can access cms-pages.php
7. ✅ Can create, edit, and delete pages
8. ✅ TinyMCE editor loads and works
9. ✅ Sample data is created (4 pages, 4 features, 4 stats, 3 testimonials)
10. ✅ All tests pass in test_cms_features.php

---

## 📞 Support

If you encounter issues:

1. **Check the error logs:**
   - PHP error log
   - MySQL error log
   - Browser console (F12)

2. **Review documentation:**
   - PHASE8_QUICK_START.md
   - PHASE8_IMPLEMENTATION_SUMMARY.md
   - PHASE8_TODO.md

3. **Verify prerequisites:**
   - PHP 7.4+ installed
   - MySQL/MariaDB running
   - Apache/Nginx running
   - PDO extension enabled

---

## 🎉 Next Steps

After successful setup:

1. **Change admin password** (Settings → Account)
2. **Create real content pages** (About, Contact, etc.)
3. **Customize branding** (when implemented)
4. **Add team members** (when implemented)
5. **Configure menus** (when implemented)
6. **Upload media** (when implemented)

---

**Setup Time:** ~15-20 minutes  
**Last Updated:** January 2025  
**Version:** 1.0
