# System Memory - Project Context

**Last Updated:** 2026-04-22  
**Project:** Global Consultants WordPress Site (glocalconsultants.com)  
**Type:** WordPress Site (Custom Theme + Multiple Plugins)

---

## High-Level Project Understanding

### Project Overview
- **Site Name:** Global Consultants (glocalconsultants.com)
- **Site Type:** Appears to be a law firm / professional services site (based on "cafirm" theme)
- **Technology Stack:** WordPress 6.5.3 with premium plugins
- **Current State:** Running locally for development/analysis
- **Backup Status:** Multiple backups available (full snapshots exist)

### Purpose & Context
- This is a professional services website
- Uses professional WordPress plugins (Gravity Forms, ACF Pro, WP Mail SMTP Pro, Yoast SEO)
- Complex content structure (custom post types via Custom Post Type UI)
- Professional table management and form handling
- Production site uses HTTPS with SSL enforcement (Really Simple SSL)

### Business Functions Supported
1. **Content Management** - 320 posts, 11 pages, custom post types
2. **Forms** - Gravity Forms for client inquiries/applications
3. **Advanced Fields** - ACF Pro for custom data structures
4. **SEO** - Yoast SEO integration for search visibility
5. **Caching** - LiteSpeed caching for performance
6. **Email** - Professional email handling via WP Mail SMTP Pro
7. **Tables** - TablePress for data presentation
8. **SVG Support** - For modern graphic handling

---

## Current Environment Assumptions

### Local Development Setup (Temporary)
```
PHP Server:    localhost:8000
MySQL Server:  localhost:3306
Database:      gloc_wp
DB User:       gloc_wp / gloc_wp
Admin User:    Pankaj / Admin@123Local (TEMPORARY)
WordPress:     6.5.3
Theme Active:  cafirm (custom)
Plugins:       10 active (1 disabled for HTTP)
```

### Detected Local Setup Artifacts
- **PHP Server PID:** Stored in `/tmp/php_server.pid`
- **PHP Server Log:** `/tmp/php_server.log`
- **Database Status:** ✅ All 37 tables imported and functional
- **Backup DB Files:** Both SQL and SQL.GZ available in `/DATABASE/`
- **Extracted SQL:** Database available in uncompressed form for reference

### Production Configuration (Saved for Restoration)
```
Site URLs:  https://glocalconsultants.com
SSL:        Enabled (Really Simple SSL active)
Admin:      Original password hash (cannot be reversed)
Plugins:    All 11 enabled in production
Database:   Presumably hosted on production server
```

---

## Theme Architecture

### cafirm Theme Structure
The site uses a **custom professional theme called "cafirm"** designed for professional services (law/consulting firms).

**Key Characteristics:**
- **Template-Based Design** - Uses WordPress template hierarchy with specific page templates
- **AJAX-Heavy Frontend** - Dynamic content loading without page reloads
- **Multi-Template Approach** - Different templates for Home, About, Contact, Services
- **Bootstrap Foundation** - Built on Bootstrap grid system for responsive design
- **Animation-Rich** - Uses GSAP, AOS, WOW for scroll animations and effects

**Core Components:**
1. **Header** (`header.php`)
   - Logo (Glocal branding)
   - Primary navigation menu
   - WhatsApp contact button (+91 9625755789)
   - Responsive mobile navigation

2. **Footer** (`footer.php`)
   - Company contact info and address
   - Copyright year (dynamic)
   - Floating "Pay Now" button (Razorpay integration)
   - Back-to-top scroll button

3. **Page Templates**
   - `page-home.php` (Homepage) - Hero slider, service grid - 153KB
   - `page-about.php` (About) - Team profiles, vision/mission (uses ACF)
   - `page-contact.php` (Contact) - Gravity Forms + Google Maps
   - `single-services.php` (Service detail) - Sticky category tabs, dynamic content
   - `archive.php` (Services list) - Service filtering by category

4. **Frontend Libraries**
   - Bootstrap (responsive grid)
   - jQuery (DOM manipulation)
   - GSAP/ScrollTrigger (advanced animations)
   - Slick Slider (image carousels)
   - AOS/WOW (scroll animations)
   - Flexslider (gallery)

### Template Hierarchy Priority
1. Single post types use `single-{post-type}.php` (e.g., `single-services.php`)
2. Archive pages use `archive.php`
3. Pages use `page-{page-slug}.php` (e.g., `page-about.php`)
4. Falls back to `page.php` for generic pages
5. Index.php is empty (uses hierarchy)

---

## Data Flow Mapping

### How Services Display & Load

**Service Data Storage:**
- **Post Type:** `services` (86 posts)
- **Taxonomy:** `service_type` (32 hierarchical terms)
- **Content:** Full post content + ACF metadata
- **Images:** Featured image + additional images via ACF

**Service Display Flow:**

```
1. Homepage (page-home.php)
   ├─ Queries: post_type='services', posts_per_page=X
   ├─ Shows: Service boxes with thumbnail (90x90) + title
   └─ Action: Links to service detail page

2. Services Archive (archive.php)
   ├─ Shows sticky tabs of service_type categories
   ├─ Tabs with images (from ACF: taxonomy_image)
   ├─ Queries posts by selected service_type
   └─ AJAX: Click tab → load_service_content() 
      ├─ Fetches post title + content
      └─ Updates page without reload

3. Service Detail (single-services.php)
   ├─ Shows full post content
   ├─ Sticky category tabs at top
   ├─ Displays all related services (same category)
   └─ AJAX: Switch service → show_select_post()
      ├─ Updates content panel
      └─ Shows selected post details
```

### Page-Level Data (ACF Fields)

**About Page (Page ID from context: uses get_field()):**
- `team_title` - "Our Team" heading
- `team_para` - Team description
- `our_vision_title`, `our_vision_image1`, `our_vision_para` - Vision block
- `our_mission_title`, `our_mission_image`, `our_mission_para` - Mission block

**Homepage Alternative (page-homenew.php):**
- `working_process_title` - Section heading
- `working_process_section_repeater` - Steps (repeating group)
- `our_mission_title`, `our_mission_heading`, `our_mission_content` - Mission
- `testimonial_title`, `testimonial_content` - Testimonials section
- `testimonial_repeater` - Individual testimonials (repeating)
- `faq_repeater` - FAQ items (repeating)

### Post Type Metadata (ACF)

**Team Posts:**
- `designation` - Role/title
- `about` - Biography

**Service Taxonomy (service_type):**
- `taxonomy_image` - Icon/image for category tab

**Service Posts:**
- Additional fields stored in postmeta (ACF)

---

## Plugin Responsibilities

### Critical Plugins (Required for Site Function)

**1. Advanced Custom Fields Pro (ACF Pro)**
- **Role:** Flexible field management for pages, posts, taxonomies
- **Data Stored:** All custom field values in wp_postmeta + wp_termmeta
- **Used By:** All page templates, team posts, service categories
- **Critical For:** About page (vision/mission), Contact page, Home sections
- **Risk If Removed:** All custom field data inaccessible (but not deleted), pages break visually

**2. Custom Post Type UI**
- **Role:** Defines custom post types (services, team, tax_advisory, etc.)
- **Data Stored:** Post type & taxonomy config in wp_options
- **Post Types Managed:** 6 custom types (services, team, company_formation, itin_ein, tax_advisory, tax_filing)
- **Taxonomies Managed:** service_type (32 terms), business_type (5 terms)
- **Critical For:** Services archive, filtering, display logic
- **Risk If Removed:** Post types still exist in database but are "unregistered" - content inaccessible via UI

**3. Gravity Forms**
- **Role:** Contact form handling and submissions
- **Data Stored:** Form definitions (Form ID 1), submission data
- **Used On:** Contact page (`[gravityform id="1" ...]`)
- **Integrations:** WP Mail SMTP Pro (email delivery)
- **Risk If Removed:** Contact form broken, submissions lost

### High-Impact Plugins

**4. WP Mail SMTP Pro**
- **Role:** Professional email delivery for form submissions
- **Data Stored:** Email logs, SMTP credentials in wp_options
- **Dependency:** Required by Gravity Forms for email notifications
- **Configuration:** Likely SMTP settings for smtp.gmail.com or other provider

**5. WordPress SEO (Yoast)**
- **Role:** SEO optimization, sitemaps, meta descriptions
- **Data Stored:** SEO metadata in postmeta
- **Impact:** Site visibility in search results
- **Risk:** Low - content remains accessible if disabled

### Performance Plugins

**6. LiteSpeed Cache**
- **Role:** Server-side caching for performance
- **Data Stored:** Cache files, settings
- **Impact:** Page load speed optimization
- **Risk:** Low - cache clears if disabled, no data loss

**7. Really Simple SSL**
- **Role:** HTTPS/SSL management, auto-redirect HTTP→HTTPS
- **Status:** Disabled locally (for HTTP development), enabled in production
- **Critical for Production:** Yes (handles SSL setup)

### Optional/Enhancement Plugins

**8. SVG Support** - Allows SVG file uploads (modern image format)
**9. TablePress** - Table management (1 table in database)
**10. Easy Table of Contents** - Auto-generate TOC in posts
**11. WP-CLI Login Server** - Development utility (local only)

---

## Critical System Components

### Foundation (Cannot Be Removed)
1. **Database** - All content, metadata, ACF fields
2. **WordPress Core** - wp-admin, wp-includes, wp-*.php files
3. **Theme (cafirm)** - Page rendering, template hierarchy
4. **Custom Post Types** - Via Custom Post Type UI plugin

### Core Functionality Stack
1. **Template Rendering** - cafirm theme page templates
2. **Content Storage** - WordPress posts/postmeta for ACF fields
3. **Data Organization** - Custom post types, taxonomies, hierarchies
4. **Form Handling** - Gravity Forms + WP Mail SMTP Pro
5. **Presentation** - Bootstrap, jQuery, animations, styling

### Data Dependencies
```
ACF Field Data
    ↓ (stored in)
wp_postmeta (pages, posts)
wp_termmeta (taxonomies)
    ↓ (displayed via)
Page Templates (cafirm theme)
    ↓ (processed by)
ACF Pro Plugin
    ↓ (rendered with)
Frontend Libraries (Bootstrap, jQuery, GSAP)
    ↓ (results)
User Interface
```

---

## Safe-to-Modify vs Risky Areas

### ✅ SAFE TO MODIFY (Low Risk)
- **Custom CSS** in `assets/css/custom.css` - Style overrides
- **Theme Colors/Styling** in `header.php` inline styles
- **Frontend Libraries** - Update versions if compatible
- **Image Assets** - Replace or optimize
- **JavaScript** in `assets/js/` - Custom functionality (with testing)
- **Page Content** - Edit via WordPress admin (post content)
- **ACF Field Values** - Edit via admin (field data, not structure)

### ⚠️ REQUIRES TESTING (Medium Risk)
- **Page Templates** - HTML structure changes (test all page types)
- **AJAX Handlers** - Modify if necessary (test loading states)
- **Database Queries** - Update WP_Query args (test performance)
- **Template Hierarchy** - Add new page templates (ensure fallback)
- **Plugin Updates** - Major version changes (backup first)

### 🔴 HIGHLY RISKY (Must Have Plan)
- **functions.php** - Register hooks, enqueue scripts (breaks if syntax error)
- **Custom Post Types** - Change registration (existing posts become inaccessible)
- **Taxonomies** - Modify structure (orphans existing terms)
- **Database Schema** - Direct SQL changes (data corruption risk)
- **wp-config.php** - Database credentials (site breaks if wrong)
- **Theme Switching** - Changes all display (comprehensive testing needed)
- **Plugin Removal** - Especially ACF Pro, Custom Post Type UI (data inaccessibility)

### ❌ DO NOT MODIFY (Locked)
- **WordPress Core** - wp-admin, wp-includes, wp-*.php (site breaks)
- **wp-config.php** - Database config (site breaks if changed)
- `.htaccess` - Server rewrite rules (breaks URLs)
- **Production Backups** - Keep as-is for safety
- **ACF Field Definitions** - Changes existing site structure
- **Plugin Code** - Unless creating custom filters/hooks

---

## Reversible Items (Completed Analysis)

### Database Changes (Existing)
- [x] Custom post types created - 6 types via Custom Post Type UI
  - services, team, company_formation, itin_ein, tax_advisory, tax_filing
  - Config stored in wp_options, posts in wp_posts
  - **Reversible:** Can be disabled (UI access lost) but data remains

- [x] Custom taxonomies created - 2 main types
  - service_type (32 terms, hierarchical) - organizing 86 service posts
  - business_type (5 terms) - categorizing business types
  - **Reversible:** Taxonomy can be unregistered; posts/terms remain in DB

- [x] Plugin-specific tables added
  - Gravity Forms: wp_gf_form, wp_gf_entry, wp_gf_entry_meta tables
  - TablePress: wp_tablepress_tables (1 table)
  - Yoast SEO: Meta in postmeta tables
  - **Reversible:** Tables can be left/deleted separately

- [x] Content-specific database changes
  - ACF field data in wp_postmeta and wp_termmeta (57 ACF fields, 7 field groups)
  - Service posts with featured images and custom metadata
  - Team posts with ACF custom fields (designation, about)
  - **Reversible:** Data remains if plugin disabled

- [x] Configuration option values changed
  - Site URLs changed from production to localhost (temporary)
  - Plugin-specific settings (LiteSpeed, Yoast, Gravity Forms)
  - Really Simple SSL setting modified (disabled for local)
  - **Reversible:** Options can be reset via next_session_revert_prompt.md

### Code-Level Changes (Analyzed)
- [x] Custom code in functions.php (theme)
  - AJAX handlers: load_service_content(), get_post_data(), show_select_post()
  - Theme setup: menu registration, image sizes, enqueue scripts
  - Code Quality: Straightforward, minimal - mostly boilerplate
  - **Risk Level:** Medium (AJAX handlers depend on correct post types/taxonomies)

- [x] Custom code in plugin directories
  - Minimal custom code found; plugins are mostly third-party
  - No custom plugins detected beyond standard WordPress plugins
  - **Risk Level:** Low (third-party code is maintained)

- [x] Child theme exists
  - **Finding:** NO child theme found
  - Only cafirm parent theme is active
  - All customizations in parent theme
  - **Risk:** Any updates to cafirm theme will overwrite customizations

- [x] Custom hooks/filters implemented
  - Custom filters found in functions.php for AJAX
  - No custom hooks for extending functionality found
  - **Risk Level:** Low (minimal hook usage means less extensibility)

- [x] Compatibility patches applied
  - **Finding:** None detected
  - PHP 8.5.4 compatibility appears native
  - WordPress 6.5.3 - no version compatibility issues found

### Configuration Items (Documented)
- [x] .htaccess rules and rewrites - Present, not analyzed in depth
- [x] WordPress options/settings changes - Temporary (site URL localhost)
- [x] Plugin-specific configurations stored in DB
  - Gravity Forms: Form definitions (Form ID 1)
  - Yoast: SEO settings per post
  - LiteSpeed: Cache settings
  - Really Simple SSL: Disabled for local dev
- [x] Theme customizations (colors, fonts, layouts)
  - Header inline CSS for menu hover colors
  - Font: Google Fonts (Marcellus, Mulish)
  - Color scheme: Dark blue, yellow accents, white background
  - Responsive breakpoints in media-query.css
- [x] Custom post type setups - Via Custom Post Type UI plugin
  - service_type taxonomy with term ordering (order_number meta)
  - Hierarchical structure (parent/child terms)

### Performance State (Documented)
- [x] Image optimization - Team images: 366x257px, Service images: 90x90px
- [x] Database optimization opportunities
  - 37 tables total; structure appears standard
  - wp_posts: 320 posts, 11 pages, 3 team members, service posts
  - Possible optimization: Index wp_postmeta for large queries
- [x] Caching strategy - LiteSpeed Cache plugin active
  - Cache files in wp-content/litespeed/
  - Cache rules configured (settings in wp_options)
- [x] CDN or asset delivery - Possible Cloudflare
  - Email-decode.min.js from /cdn-cgi/scripts/ (Cloudflare sign)
  - Image delivery may be cached at CDN
- [x] Script/style loading optimization
  - All scripts loaded from local theme assets
  - No minification detected (bootstrap.min.css exists but custom.css not minified)
  - jQuery loaded inline, not deferred
  - Opportunity: Defer non-critical scripts, lazy-load images

---

## Do Not Modify Without Approval

### Critical System Files (DO NOT TOUCH)
- `wp-config.php` - Database credentials and constants
- `/wp-admin/` - WordPress admin interface
- `/wp-includes/` - WordPress core functionality
- `.htaccess` - Server rewrite rules
- `index.php` - WordPress bootstrap
- `xmlrpc.php` - WordPress XML-RPC interface

### Production Assets (DO NOT TOUCH)
- `/DATABASE/gloc_wp.sql.gz` - Original backup (preserve for safety)
- `glocalconsultants.com_BACKUP/` - Full backup snapshot
- `glocalconsultants.com_BACKUP.zip` - Compressed backup
- `public_html_2025-02-22_15_13_28.zip` - Public HTML snapshot
- `wordpress-6.5.3.zip` - WordPress distribution archive

### Plugin/Theme Code (READ-ONLY ANALYSIS)
- `/wp-content/plugins/*/` - All plugin directories (analysis only)
- `/wp-content/themes/cafirm/` - Custom theme (analysis only)
- `/wp-content/themes/twentytwenty*/` - Default themes (DO NOT MODIFY)

### Local Development Files (PRESERVE)
- `current_local_state.md` - Current state documentation
- `local_setup_log.md` - Setup procedure log  
- `next_session_revert_prompt.md` - Revert instructions

---

## Key Technical Details

### WordPress Core Information
- **Version:** 6.5.3
- **PHP Version Required:** 8.5.4 (currently running)
- **MySQL Version:** 9.6.0

### Premium Plugin Licenses
The following premium plugins are installed (likely licensed):
1. **Advanced Custom Fields Pro** - Custom field management
2. **Gravity Forms** - Form builder and handler
3. **WP Mail SMTP Pro** - Professional email service

*Note:* These plugins may have licensing requirements that should be verified if site is transferred or modified significantly.

### Custom Theme: cafirm
- **Purpose:** Law firm / professional services site theme
- **Last Modified:** July 3, 2024
- **Status:** Active and in use
- **Size:** ~700 KB
- **Customization Level:** Unknown (needs analysis)

### Database Structure
- **Tables:** 37 total
- **Content:**
  - 320 posts
  - 11 pages
  - 1 user (Pankaj)
  - 522+ options
  - 4,514+ metadata entries
- **Charset:** utf8mb4 (Unicode with extended characters)
- **Collation:** utf8mb4_unicode_520_ci

---

## Security & Operational Notes

### Current Session Status
- ✅ Local environment fully operational
- ✅ All services running (PHP, MySQL, WordPress)
- ✅ Database fully imported and accessible
- ✅ Admin access working with temporary credentials
- ⚠️ Using HTTP instead of production HTTPS (expected for localhost)
- ⚠️ SSL plugin disabled (expected for HTTP development)

### Security Considerations
1. **Temporary Credentials** - Admin password is temporary (Admin@123Local)
2. **Database Credentials** - Stored in current_local_state.md (local only)
3. **SSL Disabled** - Production forces HTTPS; local uses HTTP
4. **Premium Plugins** - May require license keys (check configuration)
5. **Mail Configuration** - WP Mail SMTP Pro may need reconfiguration

### Data Privacy Considerations
- Database contains real customer/user data
- 320 posts likely contain real client information
- Treat database with appropriate confidentiality
- Do not upload to insecure locations

---

## Migration Path Reference

### From Local Back to Production
When ready to migrate changes back to production:

1. **Database:** Export updated local database, merge with production
2. **Theme:** Copy any modified theme files to production server
3. **Plugins:** Update plugin configurations on production
4. **Config:** Ensure wp-config.php is production-ready
5. **SSL:** Re-enable Really Simple SSL plugin
6. **URLs:** Change site URLs back to https://glocalconsultants.com
7. **Admin:** Restore original admin password
8. **Testing:** Verify all functionality in production

---

## Related Documentation

- **`current_local_state.md`** - Detailed current session state
- **`local_setup_log.md`** - How local setup was performed
- **`next_session_revert_prompt.md`** - Instructions to revert all changes
- **`project_analysis_progress.md`** - Analysis tracking and progress

---

## Critical Dependencies Map

### Tier 1: Foundation (Cannot Break These)
```
WordPress Core Files
    ↓ (loads)
wp-config.php
    ↓ (connects to)
MySQL Database (gloc_wp)
    ↓ (WordPress initializes)
wp-includes/ hooks
    ↓ (theme loads)
cafirm/functions.php
    ↓ (renders)
cafirm/page-*.php templates
```

**If any tier breaks:** Site becomes non-functional

### Tier 2: Plugin Dependencies
```
Custom Post Type UI
    ├─ Registers: services (86 posts), team, tax services
    ├─ Registers: service_type, business_type taxonomies
    └─ Stored in: wp_options (post type configuration)

Advanced Custom Fields Pro
    ├─ Stores: 57 field definitions (7 field groups)
    ├─ Data in: wp_postmeta, wp_termmeta
    ├─ Used by: All page templates
    └─ Risk: If disabled, fields become inaccessible

Gravity Forms
    ├─ Form ID 1: Contact form
    ├─ Data in: wp_gf_form, wp_gf_entry tables
    ├─ Displayed in: page-contact.php
    └─ Depends on: WP Mail SMTP Pro for email

WP Mail SMTP Pro
    ├─ Handles: Email delivery for forms
    ├─ Config: SMTP credentials in wp_options
    ├─ Uses: wp_mail() function
    └─ Required by: Gravity Forms notifications
```

### Tier 3: Template-Plugin Coupling
```
page-about.php
    ├─ Uses ACF: team_title, team_para, our_vision_*, our_mission_*
    ├─ Queries: post_type='team'
    └─ Risk: If CPT 'team' unregistered or ACF deleted → page breaks

page-contact.php
    ├─ Uses ACF: None (static HTML)
    ├─ Shortcode: [gravityform id="1"]
    ├─ Maps: embedded Google Maps
    └─ Risk: If form ID changes or GF plugin disabled → form vanishes

single-services.php
    ├─ Uses Taxonomy: service_type (32 terms)
    ├─ AJAX: get_post_data(), show_select_post() handlers
    ├─ Uses ACF: taxonomy_image field
    └─ Risk: If taxonomy deleted or AJAX breaks → filtering fails

archive.php
    ├─ Uses Taxonomy: service_type hierarchy
    ├─ AJAX: get_post_data() for filtering
    └─ Risk: If taxonomy/AJAX broken → services don't display
```

### Tier 4: AJAX-JavaScript Coupling
```
Frontend (browser)
    ├─ JavaScript: onclick="showPost(<?php echo get_the_id(); ?>)"
    ├─ Event: 'click' on .showPost class elements
    ├─ AJAX Call: wp.ajax.post('load_service_content', {post_id: id})
    └─ Expects: action='wp_ajax_load_service_content'
    
Backend (PHP)
    ├─ Handler: add_action('wp_ajax_load_service_content', 'load_service_content')
    ├─ Function: Queries post by ID
    ├─ Output: <h2> title + <div> content
    └─ Risk: Any mismatch → 404 error → silent failure

Critical Coupling Points:
    - Action name: 'load_service_content' (must match exactly)
    - HTML class: '.showPost' (JavaScript selector)
    - Data attribute: 'data-postid' (passes post ID)
    - Response format: '<h2>...' + '<div>...' (expected by JS)
```

### Tier 5: Environment Coupling
```
Local Development Environment
    ├─ Site URL: http://localhost:8000
    ├─ MySQL: localhost:3306, user: gloc_wp
    ├─ PHP: 8.5.4 (Homebrew)
    ├─ Really Simple SSL: DISABLED (HTTP only)
    └─ Admin: http://localhost:8000/wp-admin

Production Environment
    ├─ Site URL: https://glocalconsultants.com
    ├─ MySQL: Remote server (domain credentials)
    ├─ PHP: Likely 7.4+ or 8.x (shared hosting)
    ├─ Really Simple SSL: ENABLED (HTTPS enforcement)
    └─ Admin: https://glocalconsultants.com/wp-admin

Database Differences:
    - siteurl: MUST change between environments
    - home: MUST change between environments
    - Really Simple SSL settings: MUST be environment-specific
    - WP Mail SMTP credentials: MUST NOT be committed to version control
```

---

## Failure Scenarios

### Scenario 1: Critical - Theme File Corruption
**What Breaks:** Everything
**Trigger:** PHP syntax error in functions.php
**User Impact:** "Fatal Error" screen, site completely inaccessible
**Detection:** Immediate (any page load)
**Recovery:** Replace file with backup (< 1 min)
**Prevention:** Code review before commit, lint checking

### Scenario 2: Critical - Post Type Unregistration
**What Breaks:** Service pages, filtering, URLs
**Trigger:** Custom Post Type UI plugin disabled or CPT config deleted
**User Impact:** 86 service posts become "orphaned", 404 errors on old URLs
**Detection:** Immediate (services page shows nothing)
**Recovery:** Re-enable plugin or restore CPT config (5-15 min)
**Prevention:** Never delete CPT without planning migration

### Scenario 3: Critical - ACF Field Deletion
**What Breaks:** About, Home, Contact pages (depending on field)
**Trigger:** Delete field in ACF admin interface
**User Impact:** Blank sections on pages (content hidden)
**Detection:** Visual inspection (sections appear empty)
**Recovery:** Restore field definition from backup (10-20 min)
**Prevention:** Export/backup ACF field groups before changes

### Scenario 4: Critical - Database URL Mismatch
**What Breaks:** AJAX requests, forms, navigation links
**Trigger:** Migrating to production without updating siteurl
**User Impact:** 
  - AJAX calls to http://localhost:8000/admin-ajax.php fail
  - Redirects loop (if HTTPS redirect enabled)
  - Admin unreachable
**Detection:** AJAX 404 errors in console, redirect loops
**Recovery:** Update siteurl via wp-cli or phpmyadmin (5 min)
**Prevention:** Use environment-specific configuration, automation

### Scenario 5: High - AJAX Endpoint Name Changed
**What Breaks:** Dynamic service content loading
**Trigger:** Rename action in functions.php (e.g., 'load_service_content' → 'load_content')
**User Impact:** Service content doesn't load when clicking, silent failure
**Detection:** Browser console shows 400 error (frontend devs see this)
**Recovery:** Rename back to match JavaScript calls (5 min)
**Prevention:** Search codebase for all usages before renaming

### Scenario 6: High - Gravity Forms ID Wrong
**What Breaks:** Contact form functionality
**Trigger:** Change shortcode from id="1" to id="2"
**User Impact:** Different form displays or "Form not found" error
**Detection:** Contact page shows wrong form or error message
**Recovery:** Change ID back (2 min)
**Prevention:** Test shortcode before deploying

### Scenario 7: High - Email Configuration Error
**What Breaks:** Form submissions don't trigger emails
**Trigger:** WP Mail SMTP Pro SMTP credentials wrong or server down
**User Impact:** Forms submit (user sees success) but no notification received
**Detection:** Silent failure (check email log in WP Mail SMTP Pro)
**Recovery:** Verify SMTP credentials, test with wp-cli (10 min)
**Prevention:** Test email after any configuration change

### Scenario 8: Medium - Image Size Name Changed
**What Breaks:** Team member images
**Trigger:** Change 'team-image' to 'team-avatar' in functions.php without updating templates
**User Impact:** Broken image links on About page (404 or wrong size)
**Detection:** Visual inspection (missing/stretched images)
**Recovery:** Change name back or update template calls (5 min)
**Prevention:** Search for all usages before renaming

### Scenario 9: Medium - Taxonomy Term Deleted
**What Breaks:** Services in that category, filtering
**Trigger:** Delete service_type term (e.g., "Tax Filing") in WordPress admin
**User Impact:** 3 tax_filing services become unfiltered, category tab disappears
**Detection:** Missing category in tabs, services don't organize correctly
**Recovery:** Restore term (if backed up) or reassign services (15 min)
**Prevention:** Backup terms before deletion, use archive flag instead

### Scenario 10: Low - CSS Framework Update
**What Breaks:** Layout, styling
**Trigger:** Update Bootstrap from 4.x to 5.x
**User Impact:** Classes might not exist, layout breaks
**Detection:** Visual inspection (broken layout)
**Recovery:** Revert Bootstrap version or update HTML classes (30+ min)
**Prevention:** Test framework updates in staging environment

---

## Safe Modification Guidelines

### Before Any Modification

**Step 0: Backup Essentials**
```bash
BACKUP CHECKLIST:
☐ Database: Database/gloc_wp.sql.gz (compressed backup already exists)
☐ Code: Zip all /wp-content/themes/cafirm/ files
☐ Code: Zip all /wp-content/plugins/ directories
☐ Database State: Export wp_options table (site config)
☐ Document: Current state of what you're changing
☐ Document: Why you're changing it (reference for rollback)
```

**Step 1: Understand Dependencies**
```
Before changing ANY file, ask:
1. What does this file do? (core logic, template, asset)
2. What other files depend on this? (search codebase)
3. What database values depend on this? (check wp_options, postmeta)
4. What JavaScript depends on this? (search HTML selectors, action names)
5. What templates expect this? (grep for field names, shortcodes)
6. What happens if I remove this? (trace the failure)
```

**Step 2: Create a Safe Test Plan**
```
BEFORE deploying:
1. List all changes you're making
2. For each change, predict: what could break?
3. Document: how will you detect if it breaks?
4. Document: how will you recover?
5. Create: a fallback plan (rollback steps)
```

### Safe Places to Make Changes

#### ✅ SAFEST: WordPress Admin Interface
**Best For:** Content editing, ACF field values, plugin settings
**Why Safe:** Changes only affect database, not code
**How to Make Changes:**
```
1. Edit post/page content → goes to wp_posts.post_content
2. Change ACF field value → goes to wp_postmeta
3. Edit menu → goes to wp_postmeta (menu structure)
4. Plugin settings → goes to wp_options

These are all reversible:
- Content: Just edit and save again
- ACF fields: Restore from backup
- Menus: WordPress has revisions
- Settings: Most plugins backup previous settings
```

**Risk Level:** 🟢 LOW (data only, not code)

#### ✅ SAFE: Custom CSS File (custom.css)
**Best For:** Styling changes, color adjustments, layout tweaks
**Why Safe:** Only affects visual presentation
**How to Make Changes:**
```
1. Edit: wp-content/themes/cafirm/assets/css/custom.css
2. Add CSS rules (don't delete existing rules)
3. Test in browser
4. If broken, undo changes
5. Backup: Keep original copy

Key: Use CSS to override, don't delete existing styles
Risk: Worst case is broken layout, not broken functionality
```

**Risk Level:** 🟢 LOW (visual only)

#### ✅ SAFE: Create a Child Theme
**Best For:** Extending functionality without modifying parent
**Why Safe:** Parent theme stays untouched, changes isolated
**How to Make Changes:**
```
1. Create: wp-content/themes/cafirm-child/
2. In functions.php:
   add_action('wp_enqueue_scripts', function() {
       wp_enqueue_style('cafirm-child', get_stylesheet_uri());
   });
3. Add custom styles in: style.css
4. Add custom functions in: functions.php (with unique prefixes)
5. Override templates by copying to child theme

Key: Child theme allows updates to parent without losing changes
Risk: Low if done correctly
```

**Risk Level:** 🟡 MEDIUM (if poorly structured, could have conflicts)

#### ⚠️ RISKY: Modify functions.php
**Best For:** Hooks, filters, new AJAX handlers
**Why Risky:** Single syntax error breaks entire site
**How to Make Changes:**
```
PROCESS:
1. Always work on a copy first (locally)
2. Test every change immediately
3. Use PHP linter before uploading
4. Make small changes, test, commit
5. Use version control (git)

EXAMPLE OF SAFE ADDITION:
// At end of functions.php
if (!function_exists('my_new_function')) {
    function my_new_function() {
        // Your code
    }
    add_action('some_hook', 'my_new_function');
}

WHY: Wrapped in exists check, unique name, isolated logic
Risk: Medium (one syntax error breaks site)
```

**Risk Level:** 🔴 HIGH (one error = site down)

#### ⚠️ RISKY: Modify Page Templates
**Best For:** Layout changes, new sections, template restructuring
**Why Risky:** Changes affect what users see, need testing
**How to Make Changes:**
```
PROCESS:
1. Only modify ONE template at a time
2. Test the template on live site (if possible) with special parameter
3. Check all pages that use this template
4. Test on multiple browsers/devices
5. Keep original as backup

EXAMPLE: page-about.php
- Identify what page uses this: Settings → Reading → Front Page Template
- Test in local environment first
- Deploy and test each section
- Monitor for 24 hours
Risk: High (visible to users, affects UX)
```

**Risk Level:** 🔴 HIGH (visual/UX impact)

#### ❌ DO NOT: Modify ACF Field Names Directly
**Why Risky:** Multiple templates depend on exact field names
**Safe Alternative:**
```
Instead of renaming field in ACF:

1. Create NEW field with new name
2. Copy values from old field to new field (script or manual)
3. Update ONE template to use new field
4. Test that template
5. Update NEXT template
6. Continue until all templates updated
7. Then delete old field

Or better yet:
- Create new field as additional field (keeps both)
- Gradually move templates to new field
- Keep old field for backward compatibility
```

**Risk Level:** 🔴 CRITICAL (affects all templates using field)

#### ❌ DO NOT: Rename Post Types or Taxonomies
**Why Risky:** URLs change, filtering breaks, posts become inaccessible
**Safe Alternative:**
```
Instead of renaming:

1. Create NEW post type with new name
2. Migrate content (manually or via plugin)
3. Update templates to use new type
4. Set up 301 redirects for old URLs
5. Monitor redirects for 2-4 weeks
6. Then deactivate/remove old post type

Or just don't rename:
- Post type names are usually permanent decisions
- If you need to rename, plan migration 2-4 weeks ahead
```

**Risk Level:** 🔴 CRITICAL (SEO damage, UX damage)

---

## Rollback Strategy

### Fast Recovery Procedures

#### Recovery Plan A: Code File Corruption (< 1 minute)
```bash
IF: White screen of death, Fatal error in functions.php

STEP 1: Restore file immediately
  cd /Users/gouravmanna/Downloads/Temp/glocalconsultant/wp-content/themes/cafirm/
  # Copy backup: functions.php.backup → functions.php
  # Or git checkout functions.php (if version controlled)

STEP 2: Clear any caches
  LiteSpeed Cache: Delete wp-content/litespeed/ directory

STEP 3: Verify site loads
  Visit: http://localhost:8000
  Should show homepage without errors

TIME: < 1 minute
RISK: None (file is restored to known good state)
```

#### Recovery Plan B: Database Configuration Error (< 5 minutes)
```bash
IF: "Error establishing database connection"

STEP 1: Verify credentials in wp-config.php
  define('DB_NAME', 'gloc_wp');
  define('DB_USER', 'gloc_wp');
  define('DB_PASSWORD', 'gloc_wp');
  define('DB_HOST', 'localhost');

STEP 2: Verify MySQL is running
  mysql -u gloc_wp -pgloc_wp gloc_wp -e "SELECT 1;"
  Should return: 1 (MySQL is running)

STEP 3: If wrong credentials, restore from backup config
  git checkout wp-config.php
  or manually edit with correct values

STEP 4: Verify site loads
  Visit: http://localhost:8000

TIME: < 5 minutes
RISK: None (config is static, easy to fix)
```

#### Recovery Plan C: Site URL Changed (< 5 minutes)
```bash
IF: AJAX 404 errors, forms don't submit, redirects loop

STEP 1: Check current siteurl
  mysql -u gloc_wp -pgloc_wp gloc_wp -e "SELECT option_id, option_name, option_value FROM wp_options WHERE option_name IN ('siteurl', 'home');"

STEP 2: Update siteurl to correct value
  OPTION A - Using MySQL:
    mysql -u gloc_wp -pgloc_wp gloc_wp -e "UPDATE wp_options SET option_value='http://localhost:8000' WHERE option_name='siteurl';"
    mysql -u gloc_wp -pgloc_wp gloc_wp -e "UPDATE wp_options SET option_value='http://localhost:8000' WHERE option_name='home';"

  OPTION B - Using wp-cli:
    wp option update siteurl 'http://localhost:8000'
    wp option update home 'http://localhost:8000'

  OPTION C - Restore from backup wp_options
    See system_memory.md for original values

STEP 3: Clear caches
  LiteSpeed: Delete wp-content/litespeed/
  Browser: Clear all cookies

STEP 4: Verify
  Visit: http://localhost:8000
  AJAX should work, forms should submit

TIME: < 5 minutes
RISK: Low (option change only, very reversible)
```

#### Recovery Plan D: Plugin Broken (< 10 minutes)
```bash
IF: One plugin causes issues (blank page, error in specific feature)

STEP 1: Identify which plugin
  Check: recent changes, error logs
  Common culprits:
    - WP Mail SMTP Pro: email config wrong
    - Gravity Forms: form ID changed
    - ACF Pro: field deleted
    - Custom Post Type UI: CPT deleted

STEP 2A: If plugin code changed
  Restore original plugin files:
    git checkout wp-content/plugins/[plugin-name]/

STEP 2B: If plugin settings wrong
  Go to: WordPress Admin → Settings → [Plugin Name]
  Restore previous settings or check documentation

STEP 2C: If unsure, disable plugin temporarily
  Via admin: Plugins → Deactivate [Plugin]
  Test if issue resolves
  If yes: Issue is in that plugin → investigate/restore
  If no: Issue is elsewhere

STEP 3: Re-enable once fixed
  Via admin: Plugins → Activate [Plugin]

STEP 4: Verify feature works
  For Gravity Forms: Test contact form
  For ACF: Check About page displays fields
  For Custom Post Type UI: Check services page

TIME: < 10 minutes (if you know the cause)
RISK: Low (plugin disable is reversible)
```

#### Recovery Plan E: ACF Field Deleted (< 20 minutes)
```bash
IF: About page shows blank sections, field values disappeared

STEP 1: Check database for field definition
  The field definition might still exist in postmeta/acf-field-groups
  MySQL query:
    SELECT * FROM wp_posts WHERE post_type='acf-field-group' AND post_title LIKE '%team%';

STEP 2: Restore from backup
  OPTION A: ACF export/import
    - Admin → ACF → Tools → Export ACF Field Groups as JSON
    - Restore from previous JSON export
  
  OPTION B: Direct database restore
    - Restore wp_posts table from backup
    - Restore wp_postmeta table from backup
  
  OPTION C: If no backup, recreate field
    - Manual recreation: Admin → ACF → Add Field Group
    - Re-enter same field names and types
    - Attach to same post type/page

STEP 3: Verify field values still exist
  MySQL: SELECT * FROM wp_postmeta WHERE meta_key='team_title';
  If values exist: They survived, just field definition missing
  If values gone: Need to restore from backup

STEP 4: Verify pages display correctly
  Visit: /about (should show team section)
  Visit: /home (should show mission/vision)

TIME: < 20 minutes (with backup)
RISK: Medium (if no backup, need recreation)
```

#### Recovery Plan F: Post Type Unregistered (< 15 minutes)
```bash
IF: Services page shows "No posts found", 86 service posts vanished

STEP 1: Verify posts still exist in database
  MySQL: SELECT COUNT(*) FROM wp_posts WHERE post_type='services';
  Should return: 86 (posts are still there)

STEP 2: Re-enable Custom Post Type UI plugin
  Via admin: Plugins → Activate "Custom Post Type UI"
  The CPT should re-register immediately

STEP 3: Verify services appear
  Visit: /services (archive page)
  Should show service list

STEP 4: Check if anything needs reordering
  MySQL: Check for stale term relationships
  Usually nothing needed, posts re-attach to taxonomy

TIME: < 15 minutes
RISK: Low (data never lost, just unregistered)
```

#### Recovery Plan G: Complete Site Restore (< 30 minutes)
```bash
IF: Everything broken, multiple errors, unsure what went wrong

STEP 1: Stop all processes
  - PHP server: kill $(cat /tmp/php_server.pid)
  - MySQL: Still running (leave it)

STEP 2: Restore from backup
  a) Extract backup files:
    cd /Users/gouravmanna/Downloads/Temp/glocalconsultant/
    unzip -o glocalconsultants.com_BACKUP.zip
    (This restores entire public_html directory)

  b) Restore database:
    gunzip < DATABASE/gloc_wp.sql.gz | mysql -u gloc_wp -pgloc_wp gloc_wp
    (This restores all tables, data, and settings)

STEP 3: Restart services
  - PHP: php -S localhost:8000 > /tmp/php_server.log 2>&1 &
  - MySQL: Already running
  - Save PID: echo $! > /tmp/php_server.pid

STEP 4: Verify site
  Visit: http://localhost:8000
  Should show homepage, services, etc.
  Check admin: http://localhost:8000/wp-admin

STEP 5: Investigate what went wrong
  - Compare current files with backup
  - Check error logs
  - Review what changes were made

TIME: < 30 minutes (if backup is recent)
RISK: Low (complete restore to known state)
```

### Backup Strategy

**Required Backups Before Any Change:**
```
1. Database Backup (CRITICAL)
   ☐ Always: DATABASE/gloc_wp.sql.gz exists
   ☐ Before major change: Create fresh backup
   ☐ Command: mysqldump -u gloc_wp -pgloc_wp gloc_wp > /tmp/gloc_wp_$(date +%s).sql

2. Code Backup (CRITICAL)
   ☐ Theme files: wp-content/themes/cafirm/
   ☐ Plugin files: wp-content/plugins/ (if modifying)
   ☐ Command: zip -r /tmp/backup_$(date +%s).zip wp-content/

3. Configuration Backup (IMPORTANT)
   ☐ wp-config.php
   ☐ .htaccess
   ☐ wp_options table (site config)

4. Version Control (BEST PRACTICE)
   ☐ Initialize git: git init
   ☐ Commit baseline: git add . && git commit -m "Baseline"
   ☐ Create branch: git checkout -b feature/my-change
   ☐ Make changes on branch
   ☐ Can rollback: git checkout main (if main exists)
```

---

## Environment Sensitivities

### Critical Differences: Local vs Production

#### 1. Site URLs
```
LOCAL:
  siteurl = http://localhost:8000
  home = http://localhost:8000
  
PRODUCTION:
  siteurl = https://glocalconsultants.com
  home = https://glocalconsultants.com

⚠️ RISK: If production database has localhost URLs:
  - AJAX calls try to reach localhost (fails)
  - Redirects loop if SSL enforced
  - Admin links broken
  - External links pointing to localhost

✅ SOLUTION: Never copy production database without updating URLs first
```

#### 2. SSL/HTTPS Configuration
```
LOCAL:
  Really Simple SSL: DISABLED
  Protocol: HTTP only (localhost:8000)
  Browser allows insecure connection
  
PRODUCTION:
  Really Simple SSL: ENABLED
  Protocol: HTTPS enforced
  HTTP redirects to HTTPS
  Certificate required

⚠️ RISK: If production setting copied to local:
  - Infinite redirect loop (HTTP → HTTPS → HTTP)
  - Can't access site without SSL certificate
  - Only fix: Disable plugin or update certificate

✅ SOLUTION: Keep Really Simple SSL disabled in development
```

#### 3. Email Configuration
```
LOCAL:
  WP Mail SMTP Pro: May not be configured
  Mail testing: Uses wp-cli or test plugins
  Emails: May be sandboxed or logged only
  
PRODUCTION:
  WP Mail SMTP Pro: SMTP credentials stored in wp_options
  Mail testing: Real emails sent to real addresses
  Emails: Must use valid SMTP server

⚠️ RISK: If local SMTP config used in production:
  - Wrong server credentials
  - Emails fail silently
  - Form submissions lose contact info
  - Business loses leads

✅ SOLUTION: Use environment-specific configuration files
          Never hardcode credentials in code
          Use conditional logic:
            if (WP_ENV === 'production') { load_prod_config(); }
```

#### 4. Database Connections
```
LOCAL:
  Host: localhost
  Port: 3306 (default)
  User: gloc_wp
  Password: gloc_wp (test password)
  
PRODUCTION:
  Host: [Remote IP or domain]
  Port: 3306 (usually remote)
  User: [Production user]
  Password: [Secure password]

⚠️ RISK: If local database credentials used in production:
  - Connection fails (wrong host)
  - Tries to connect to localhost (doesn't exist)
  - Site completely non-functional

✅ SOLUTION: Keep wp-config.php environment-specific
          Use local wp-config-local.php (not version controlled)
          Use environment variables: define('DB_HOST', getenv('DB_HOST'));
```

#### 5. Plugin Behavior
```
LOCAL:
  Debug plugins (WP-CLI Login Server): ENABLED
  Cache plugins (LiteSpeed): May be disabled
  Development plugins: Active for testing
  
PRODUCTION:
  Debug plugins: DISABLED (security risk)
  Cache plugins: ENABLED (for performance)
  Dev plugins: REMOVED (unnecessary overhead)

⚠️ RISK: If local plugin set copied to production:
  - Debug info exposed to users (security risk)
  - WP-CLI Login Server allows unauthorized access
  - Extra plugins slow down site
  - Cache misconfigured for production

✅ SOLUTION: Keep wp-content/mu-plugins/ for environment detection
          Use conditional activation:
            if (!WP_ENV === 'production') { require plugin; }
```

#### 6. Debugging and Logging
```
LOCAL:
  WP_DEBUG: TRUE (enabled)
  WP_DEBUG_LOG: TRUE (log errors)
  WP_DEBUG_DISPLAY: FALSE (don't show to users)
  Error display: Sent to /tmp/php_server.log
  
PRODUCTION:
  WP_DEBUG: FALSE (disabled)
  WP_DEBUG_LOG: FALSE (no error logging)
  WP_DEBUG_DISPLAY: FALSE (never show errors)
  Error display: Hidden from users

⚠️ RISK: If local debug config used in production:
  - Errors displayed to users (security risk)
  - Database errors show table/column names
  - File paths exposed
  - Performance impact from logging

✅ SOLUTION: Define constants in wp-config.php based on WP_ENV
          Example: define('WP_DEBUG', WP_ENV === 'local');
```

#### 7. Caching
```
LOCAL:
  LiteSpeed Cache: May be disabled (development)
  Browser cache: Bypassed during testing
  Object cache: Disabled (Redis not running)
  Page cache: Disabled
  
PRODUCTION:
  LiteSpeed Cache: ENABLED (performance critical)
  Browser cache: ENABLED (static assets cached)
  Object cache: ENABLED (if Redis available)
  Page cache: ENABLED (full HTML cached)

⚠️ RISK: If you don't clear cache in production:
  - Old content served to users
  - Form changes don't appear until cache expires
  - Database changes invisible to users
  - Updates seem broken

✅ SOLUTION: Include cache-clear step in deployment
          LiteSpeed: Delete wp-content/litespeed/
          Browser: Instruct users to clear (Ctrl+Shift+Del)
          Always test on "no-cache" session
```

### Migration Checklist (Local to Production)

```
BEFORE MIGRATION:
☐ Backup current production database
☐ Backup current production files
☐ Test migration in staging environment
☐ Document all environment differences

DURING MIGRATION:
☐ Update DATABASE:
  - Export local database: mysqldump -u gloc_wp -pgloc_wp gloc_wp > backup.sql
  - Change siteurl to production domain
  - Change home to production domain
  - Change Really Simple SSL setting (enable)
  - Verify email SMTP credentials for production
  - Disable debug plugins

☐ Update FILES:
  - Copy wp-content/themes/cafirm/ (all template changes)
  - Copy wp-content/plugins/ (if new plugins added)
  - DO NOT copy wp-config.php (keep production credentials)
  - DO NOT copy wp-content/uploads/ (keep production media)
  - DO NOT copy database backups

☐ Update CONFIGURATION:
  - Verify wp-config.php has production DB credentials
  - Verify Really Simple SSL is enabled
  - Verify WP Mail SMTP Pro has production SMTP config
  - Clear all caches

AFTER MIGRATION:
☐ Test homepage loads
☐ Test services page (filtering)
☐ Test contact form (send test email)
☐ Test admin login
☐ Verify HTTPS working
☐ Check for mixed content warnings (HTTPS images loading as HTTP)
☐ Monitor for 24 hours for errors
```

---

## Analysis Checkpoints

- [x] Initial structural scan completed
- [ ] Theme code analysis (pending)
- [ ] Plugin code review (pending)
- [ ] Database schema analysis (pending)
- [ ] Security audit (pending)
- [ ] Performance analysis (pending)
- [ ] Compatibility verification (pending)
- [ ] Documentation finalization (pending)
