# Phases 2-4: Detailed Implementation Plan

## Phase 2: Enterprise Features (Weeks 5-8)

> **CRITICAL CLARIFICATION: Admin Panel Technology**
> 
> All admin UI files in this document (e.g., `admin/pages/*.js`, `admin/components/*.js`) use **Vanilla JavaScript + Webpack 5 + SCSS**, NOT React/TypeScript.
> 
> - **WordPress Admin (customer-facing)** = Vanilla JS (this plugin)
> - **Press.zone Backend (internal team)** = React 18 + TypeScript (separate system)
> 
> Any references to `.tsx` files have been corrected to `.js` files.

### Week 5: Translation Workflow System

#### Task 5.1: Workflow State Machine

**File:** `includes/Workflow/StateMachine.php`
**Class:** `MultilingualPressZone\Workflow\StateMachine`

##### Sub-task 5.1.1: Define Workflow States
- [ ] Create `includes/Workflow/WorkflowState.php` enum with states: `draft`, `in_review`, `approved`, `published`, `rejected`, `archived`
- [ ] Define state transition rules matrix in `StateMachine::getTransitionRules()`
- [ ] Implement `StateMachine::canTransition(string $from, string $to, int $userId): bool`
- [ ] Create permission mapping for each transition (e.g., draft→in_review requires `submit_translation` capability)
- [ ] Add validation rules for state changes in `StateMachine::validateTransition()`
- [ ] Create exception classes: `InvalidStateTransitionException`, `InsufficientPermissionsException`
- [ ] Unit tests for all valid transitions
- [ ] Unit tests for all invalid transitions
- [ ] Unit tests for permission checks

##### Sub-task 5.1.2: Database Table for Workflow

**Required Skills:** `database-operations`
**File:** `includes/Core/Database.php` (modify `createTables()` method)
- [ ] CREATE TABLE `wp_mpz_workflow_states`:
  - `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  - `translation_id` BIGINT UNSIGNED NOT NULL
  - `state` VARCHAR(20) NOT NULL
  - `previous_state` VARCHAR(20) NULL
  - `assigned_to` BIGINT UNSIGNED NULL (user_id)
  - `assigned_by` BIGINT UNSIGNED NULL (user_id)
  - `deadline` DATETIME NULL
  - `started_at` DATETIME NULL
  - `completed_at` DATETIME NULL
  - `notes` TEXT NULL
  - `metadata` JSON NULL (for extensibility)
  - `created_at` DATETIME NOT NULL
  - `updated_at` DATETIME NOT NULL
- [ ] Add indexes: `idx_translation` (translation_id), `idx_state` (state), `idx_assigned` (assigned_to), `idx_deadline` (deadline)
- [ ] Add foreign key constraint to `wp_mpz_translations` table
- [ ] Add foreign key constraints to `wp_users` for assigned_to/assigned_by
- [ ] Create migration script `includes/Migrations/Migration_Add_Workflow_States_Table.php`
- [ ] Add rollback functionality for migration
- [ ] Test migration on clean install
- [ ] Test migration on existing installation with 10k+ translations

##### Sub-task 5.1.3: Workflow State History Tracking
**File:** `includes/Core/Database.php`
- [ ] CREATE TABLE `wp_mpz_workflow_history`:
  - `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  - `translation_id` BIGINT UNSIGNED NOT NULL
  - `from_state` VARCHAR(20) NOT NULL
  - `to_state` VARCHAR(20) NOT NULL
  - `changed_by` BIGINT UNSIGNED NOT NULL
  - `change_reason` TEXT NULL
  - `time_in_state` INT UNSIGNED NULL (seconds in previous state)
  - `created_at` DATETIME NOT NULL
- [ ] Add indexes: `idx_translation_history` (translation_id, created_at), `idx_changed_by` (changed_by)
- [ ] Add foreign key constraints
- [ ] Create `WorkflowHistory` model class in `includes/Workflow/WorkflowHistory.php`
- [ ] Implement `WorkflowHistory::log()` method
- [ ] Implement `WorkflowHistory::getTimeline(int $translationId): array`
- [ ] Add automatic history logging to `StateMachine::transition()` method

##### Sub-task 5.1.4: State Machine Core Implementation
**File:** `includes/Workflow/StateMachine.php`
- [ ] Implement `StateMachine::__construct(Database $db, PermissionManager $permissions)`
- [ ] Implement `StateMachine::getCurrentState(int $translationId): ?WorkflowState`
- [ ] Implement `StateMachine::transition(int $translationId, WorkflowState $toState, array $options = []): bool`
- [ ] Implement `StateMachine::getAvailableTransitions(int $translationId, int $userId): array`
- [ ] Implement `StateMachine::assignTo(int $translationId, int $userId, ?DateTime $deadline): bool`
- [ ] Implement `StateMachine::unassign(int $translationId): bool`
- [ ] Implement `StateMachine::setDeadline(int $translationId, DateTime $deadline): bool`
- [ ] Implement `StateMachine::addNotes(int $translationId, string $notes): bool`
- [ ] Add hooks: `mpz_before_state_transition`, `mpz_after_state_transition`, `mpz_state_transition_failed`
- [ ] Add filters: `mpz_workflow_transition_rules`, `mpz_workflow_state_permissions`
- [ ] Unit tests for each method (100% code coverage)
- [ ] Integration tests with actual database

##### Sub-task 5.1.5: Workflow Assignment Algorithm
**File:** `includes/Workflow/AssignmentEngine.php`
**Class:** `MultilingualPressZone\Workflow\AssignmentEngine`
- [ ] Implement `AssignmentEngine::autoAssign(int $translationId, array $criteria = []): ?int` (returns assigned user_id)
- [ ] Load balancing algorithm: distribute based on current workload
- [ ] Skill matching: assign based on language pairs (translator expertise)
- [ ] Availability checking: respect user's working hours and capacity limits
- [ ] Priority queue: handle urgent translations first
- [ ] Round-robin fallback when no criteria match
- [ ] Implement `AssignmentEngine::getTranslatorWorkload(int $userId): int`
- [ ] Implement `AssignmentEngine::getAvailableTranslators(string $sourceLang, string $targetLang): array`
- [ ] Implement `AssignmentEngine::calculatePriority(int $translationId): int`
- [ ] Create `wp_mpz_translator_capacity` table:
  - `user_id` BIGINT UNSIGNED PRIMARY KEY
  - `max_concurrent` INT DEFAULT 10
  - `current_assigned` INT DEFAULT 0
  - `language_pairs` JSON (e.g., [{"from": "en", "to": "es", "proficiency": 5}])
  - `availability_schedule` JSON (working hours)
  - `updated_at` DATETIME
- [ ] Unit tests for each assignment strategy
- [ ] Load tests with 1000+ concurrent assignments

#### Task 5.2: Email Notification System

**File:** `includes/Workflow/NotificationManager.php`
**Class:** `MultilingualPressZone\Workflow\NotificationManager`

##### Sub-task 5.2.1: Notification Template Engine
**File:** `includes/Workflow/EmailTemplates/TemplateEngine.php`
- [ ] Implement `TemplateEngine::render(string $templateName, array $vars): string`
- [ ] Create base template layout: `templates/emails/layouts/base.php`
  - Header with logo
  - Main content area
  - Footer with unsubscribe link
  - Responsive HTML/CSS (inline styles)
- [ ] Create text-only fallback: `templates/emails/layouts/base.txt`
- [ ] Implement variable replacement: `{{variable_name}}`
- [ ] Implement conditionals: `{{#if condition}}...{{/if}}`
- [ ] Implement loops: `{{#each items}}...{{/each}}`
- [ ] Add XSS protection for template variables
- [ ] Unit tests for template rendering

##### Sub-task 5.2.2: Email Templates for Each Workflow Event
**Directory:** `templates/emails/workflow/`

- [ ] **Template: Assignment Notification** (`assigned.php`, `assigned.txt`)
  - Subject: "New translation assigned: {{content_title}}"
  - Variables: translator_name, content_title, source_lang, target_lang, deadline, content_url, accept_url, decline_url
  - CTA buttons: "Accept Assignment", "View Details"
  
- [ ] **Template: Deadline Reminder** (`deadline-reminder.php`, `deadline-reminder.txt`)
  - Subject: "Reminder: Translation due {{time_remaining}}"
  - Variables: translator_name, content_title, deadline, time_remaining, content_url
  - Urgent flag if < 24 hours remaining
  
- [ ] **Template: Deadline Passed** (`deadline-passed.php`, `deadline-passed.txt`)
  - Subject: "Translation deadline passed: {{content_title}}"
  - Variables: manager_name, translator_name, content_title, deadline, days_overdue, content_url
  - Sent to translation manager
  
- [ ] **Template: Submitted for Review** (`submitted-review.php`, `submitted-review.txt`)
  - Subject: "Translation ready for review: {{content_title}}"
  - Variables: reviewer_name, translator_name, content_title, submitted_at, review_url
  - Sent to reviewer
  
- [ ] **Template: Review Approved** (`review-approved.php`, `review-approved.txt`)
  - Subject: "Translation approved: {{content_title}}"
  - Variables: translator_name, reviewer_name, content_title, approved_at, feedback
  - Sent to translator and manager
  
- [ ] **Template: Review Rejected** (`review-rejected.php`, `review-rejected.txt`)
  - Subject: "Translation needs revision: {{content_title}}"
  - Variables: translator_name, reviewer_name, content_title, rejection_reason, revision_notes, content_url
  - Sent to translator
  
- [ ] **Template: Published** (`published.php`, `published.txt`)
  - Subject: "Translation published: {{content_title}}"
  - Variables: translator_name, content_title, published_at, published_url
  - Sent to translator and manager
  
- [ ] **Template: Workflow Escalation** (`escalation.php`, `escalation.txt`)
  - Subject: "Translation escalation: {{content_title}}"
  - Variables: manager_name, translator_name, content_title, issue_type, escalation_reason, content_url
  - Sent to translation manager

##### Sub-task 5.2.3: NotificationManager Core Implementation
**File:** `includes/Workflow/NotificationManager.php`
- [ ] Implement `NotificationManager::__construct(TemplateEngine $templates, Database $db)`
- [ ] Implement `NotificationManager::sendAssignmentNotification(int $translationId, int $userId): bool`
- [ ] Implement `NotificationManager::sendDeadlineReminder(int $translationId): bool`
- [ ] Implement `NotificationManager::sendDeadlinePassedNotification(int $translationId): bool`
- [ ] Implement `NotificationManager::sendSubmittedForReviewNotification(int $translationId): bool`
- [ ] Implement `NotificationManager::sendApprovedNotification(int $translationId): bool`
- [ ] Implement `NotificationManager::sendRejectedNotification(int $translationId, string $reason): bool`
- [ ] Implement `NotificationManager::sendPublishedNotification(int $translationId): bool`
- [ ] Implement `NotificationManager::sendEscalationNotification(int $translationId, string $reason): bool`
- [ ] Queue system for bulk emails (prevent sending 1000+ emails synchronously)
- [ ] Create `wp_mpz_notification_queue` table:
  - `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  - `recipient_email` VARCHAR(255) NOT NULL
  - `recipient_user_id` BIGINT UNSIGNED NULL
  - `template_name` VARCHAR(100) NOT NULL
  - `template_vars` JSON NOT NULL
  - `priority` TINYINT DEFAULT 5
  - `status` ENUM('pending', 'processing', 'sent', 'failed') DEFAULT 'pending'
  - `attempts` TINYINT DEFAULT 0
  - `last_error` TEXT NULL
  - `scheduled_at` DATETIME NULL
  - `sent_at` DATETIME NULL
  - `created_at` DATETIME NOT NULL
- [ ] Implement `NotificationManager::queueEmail(string $email, string $template, array $vars, int $priority = 5): bool`
- [ ] Create WP-Cron job for processing queue: `mpz_process_notification_queue`
- [ ] Implement rate limiting (e.g., 100 emails per minute)
- [ ] Add retry logic for failed sends (3 attempts with exponential backoff)
- [ ] Hook into `mpz_after_state_transition` to auto-send notifications
- [ ] Add filters: `mpz_notification_recipients`, `mpz_notification_template_vars`, `mpz_notification_enabled`
- [ ] Unit tests for each notification type
- [ ] Integration tests with email sending

##### Sub-task 5.2.4: User Notification Preferences

**Required Skills:** `users-permissions`
**File:** `includes/Workflow/NotificationPreferences.php`
- [ ] Create `wp_mpz_notification_preferences` table:
  - `user_id` BIGINT UNSIGNED PRIMARY KEY
  - `email_enabled` TINYINT(1) DEFAULT 1
  - `assignment_notifications` TINYINT(1) DEFAULT 1
  - `deadline_reminders` TINYINT(1) DEFAULT 1
  - `review_notifications` TINYINT(1) DEFAULT 1
  - `approval_notifications` TINYINT(1) DEFAULT 1
  - `digest_frequency` ENUM('realtime', 'hourly', 'daily', 'weekly') DEFAULT 'realtime'
  - `quiet_hours_start` TIME NULL
  - `quiet_hours_end` TIME NULL
  - `updated_at` DATETIME NOT NULL
- [ ] Implement `NotificationPreferences::get(int $userId): array`
- [ ] Implement `NotificationPreferences::update(int $userId, array $preferences): bool`
- [ ] Implement `NotificationPreferences::shouldSendEmail(int $userId, string $notificationType): bool`
- [ ] Implement digest system: batch emails if user prefers daily/weekly
- [ ] Create digest templates: `templates/emails/workflow/digest-daily.php`, `digest-weekly.php`
- [ ] Add WP-Cron jobs: `mpz_send_daily_digest`, `mpz_send_weekly_digest`
- [ ] Add user profile section for notification preferences
- [ ] Add unsubscribe link handler
- [ ] Unit tests for preference logic
- [ ] Integration tests for digest batching

##### Sub-task 5.2.5: In-App Notifications (Complementary to Email)
**File:** `includes/Workflow/InAppNotificationManager.php`
- [ ] Create `wp_mpz_notifications` table:
  - `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  - `user_id` BIGINT UNSIGNED NOT NULL
  - `type` VARCHAR(50) NOT NULL
  - `title` VARCHAR(255) NOT NULL
  - `message` TEXT NOT NULL
  - `link` VARCHAR(512) NULL
  - `is_read` TINYINT(1) DEFAULT 0
  - `read_at` DATETIME NULL
  - `created_at` DATETIME NOT NULL
- [ ] Add indexes: `idx_user_unread` (user_id, is_read, created_at)
- [ ] Implement `InAppNotificationManager::create(int $userId, string $type, string $title, string $message, ?string $link): int`
- [ ] Implement `InAppNotificationManager::getUnread(int $userId, int $limit = 20): array`
- [ ] Implement `InAppNotificationManager::markAsRead(int $notificationId): bool`
- [ ] Implement `InAppNotificationManager::markAllAsRead(int $userId): bool`
- [ ] Implement `InAppNotificationManager::getUnreadCount(int $userId): int`
- [ ] Add REST API endpoint: `GET /wp-json/mpz/v1/notifications`
- [ ] Add REST API endpoint: `POST /wp-json/mpz/v1/notifications/{id}/read`
- [ ] Add REST API endpoint: `POST /wp-json/mpz/v1/notifications/read-all`
- [ ] Create admin bar notification icon with unread count badge
- [ ] Create notification dropdown UI in admin bar
- [ ] Add real-time notifications using AJAX polling (30-second interval)
- [ ] Add dismissible notification banners for urgent items
- [ ] Unit tests for notification CRUD
- [ ] Integration tests for REST API endpoints

#### Task 5.3: Deadline Tracking & Alerts

**File:** `includes/Workflow/DeadlineManager.php`
**Class:** `MultilingualPressZone\Workflow\DeadlineManager`

##### Sub-task 5.3.1: Deadline Management Core
- [ ] Implement `DeadlineManager::__construct(Database $db, NotificationManager $notifications)`
- [ ] Implement `DeadlineManager::setDeadline(int $translationId, DateTime $deadline): bool`
- [ ] Implement `DeadlineManager::extendDeadline(int $translationId, DateTime $newDeadline, string $reason): bool`
- [ ] Implement `DeadlineManager::getUpcomingDeadlines(int $userId, int $days = 7): array`
- [ ] Implement `DeadlineManager::getOverdueTranslations(int $userId = null): array`
- [ ] Implement `DeadlineManager::getDeadlineStatus(int $translationId): array` (returns status, time_remaining, is_overdue)
- [ ] Add deadline change history to `wp_mpz_workflow_history`
- [ ] Add hooks: `mpz_deadline_set`, `mpz_deadline_extended`, `mpz_deadline_passed`
- [ ] Unit tests for deadline calculations
- [ ] Unit tests for timezone handling

##### Sub-task 5.3.2: Automated Deadline Monitoring
**File:** `includes/Workflow/DeadlineMonitor.php`
- [ ] Create WP-Cron job: `mpz_check_deadlines` (runs every hour)
- [ ] Implement `DeadlineMonitor::checkDeadlines(): void`
- [ ] Send reminders at configurable intervals: 7 days, 3 days, 1 day, 6 hours, 1 hour before deadline
- [ ] Create `wp_mpz_deadline_reminders` table to track sent reminders:
  - `translation_id` BIGINT UNSIGNED
  - `reminder_type` VARCHAR(20) (e.g., '7_days', '1_day', '1_hour')
  - `sent_at` DATETIME
  - PRIMARY KEY (translation_id, reminder_type)
- [ ] Implement `DeadlineMonitor::shouldSendReminder(int $translationId, string $reminderType): bool`
- [ ] Escalate overdue translations to managers after 24 hours
- [ ] Auto-reassign translations overdue by more than 3 days
- [ ] Generate weekly deadline report for managers
- [ ] Add settings page for configuring reminder intervals
- [ ] Add settings for escalation rules
- [ ] Unit tests for reminder logic
- [ ] Integration tests with cron execution

##### Sub-task 5.3.3: Deadline Dashboard Widget

**Required Skills:** `admin-panel-fullstack`
**File:** `admin/components/DeadlineWidget.php`
- [ ] Create dashboard widget showing upcoming deadlines (next 7 days)
- [ ] Display overdue translations with red badge
- [ ] Display at-risk translations (< 24 hours) with orange badge
- [ ] Group by urgency: Overdue, Due Today, Due This Week
- [ ] Add quick actions: View, Extend Deadline, Reassign
- [ ] Show translator name and content title for each item
- [ ] Add "View All" link to full deadline report page
- [ ] Make widget sortable by deadline, content type, translator
- [ ] Add AJAX refresh without page reload
- [ ] Responsive design for mobile admin
- [ ] CSS in `admin/assets/css/deadline-widget.scss`
- [ ] JS in `admin/assets/js/deadline-widget.js` (Vanilla JS, not React)
- [ ] Unit tests for widget rendering
- [ ] E2E tests for widget interactions

#### Task 5.4: Workflow Progress Reporting

**File:** `includes/Workflow/ProgressReporter.php`
**Class:** `MultilingualPressZone\Workflow\ProgressReporter`

##### Sub-task 5.4.1: Progress Metrics Collection
- [ ] Implement `ProgressReporter::getTranslationProgress(int $translationId): array`
  - Returns: state, assigned_to, time_in_state, time_since_created, completion_percentage
- [ ] Implement `ProgressReporter::getProjectProgress(array $filters = []): array`
  - Filters: date_range, language_pair, content_type, translator
  - Returns: total_translations, by_state, avg_completion_time, bottlenecks
- [ ] Implement `ProgressReporter::getTranslatorProgress(int $userId, string $period = 'week'): array`
  - Returns: completed_count, in_progress_count, avg_time_per_translation, quality_score
- [ ] Implement `ProgressReporter::getWorkflowBottlenecks(): array`
  - Identify states where translations get stuck (> 3 days)
  - Returns: state, avg_time, stuck_count, affected_translations
- [ ] Implement `ProgressReporter::getVelocityMetrics(string $period = 'month'): array`
  - Returns: translations_per_day, completion_rate, rejection_rate, trend
- [ ] Cache progress metrics for 5 minutes to reduce DB load
- [ ] Add filters: `mpz_progress_metrics`, `mpz_bottleneck_threshold`
- [ ] Unit tests for each metric calculation
- [ ] Performance tests with large datasets

##### Sub-task 5.4.2: Progress Dashboard UI

**Required Skills:** `admin-panel-fullstack`
**File:** `admin/pages/WorkflowDashboard.js` (Vanilla JS, NOT React/TypeScript)
**Route:** `/wp-admin/admin.php?page=mpz-workflow-dashboard`

- [ ] Create main dashboard layout with grid system
- [ ] **Section 1: Overview Cards**
  - Total Active Translations
  - Pending Review
  - Overdue Translations
  - Avg Completion Time
- [ ] **Section 2: Workflow Funnel Chart**
  - Show count at each stage: Draft → In Review → Approved → Published
  - Click to drill down into specific stage
- [ ] **Section 3: Progress by Language Chart**
  - Bar chart showing completion rate per language pair
  - Target: 100% completion
- [ ] **Section 4: Translator Performance Table**
  - Columns: Name, Active, Completed (7d), Avg Time, Quality Score
  - Sortable columns
  - Click to view translator detail page
- [ ] **Section 5: Bottleneck Alerts**
  - List of translations stuck > 3 days
  - Suggested actions: Reassign, Escalate, Contact Translator
- [ ] **Section 6: Recent Activity Timeline**
  - Last 20 workflow events
  - Real-time updates via AJAX
- [ ] Add date range selector (Today, 7 Days, 30 Days, Custom)
- [ ] Add export button (PDF, CSV)
- [ ] Add refresh button with last updated timestamp
- [ ] Responsive design for tablet/mobile
- [ ] Use Chart.js for visualizations
- [ ] Add loading skeletons for async data
- [ ] CSS in `admin/assets/css/workflow-dashboard.scss`
- [ ] Unit tests for Vanilla JS components
- [ ] E2E tests for dashboard interactions

##### Sub-task 5.4.3: Individual Translation Progress Page

**Required Skills:** `admin-panel-fullstack`, `wpml-integration`
**File:** `admin/pages/TranslationProgress.js` (Vanilla JS, NOT React/TypeScript)
**Route:** `/wp-admin/admin.php?page=mpz-translation-progress&id={translation_id}`

- [ ] Display content title, type, word count
- [ ] Display source and target language
- [ ] **Progress Timeline:**
  - Visual timeline showing all state changes
  - Time spent in each state
  - User who triggered each transition
  - Notes/comments at each stage
- [ ] **Current Status Card:**
  - Current state (with icon)
  - Assigned to (with avatar)
  - Deadline (with countdown)
  - Time in current state
  - Available actions (buttons for next transitions)
- [ ] **Translation Comparison:**
  - Side-by-side view: Original content | Translation
  - Highlight differences if translation was revised
  - Show revision history (if review→rejected→resubmitted)
- [ ] **Activity Log:**
  - All actions taken on this translation
  - User, timestamp, action, notes
- [ ] **Performance Metrics:**
  - Time to first review
  - Number of revisions
  - Total time to publish
  - Compared to project average
- [ ] Add quick actions: Reassign, Extend Deadline, Add Notes, Export Report
- [ ] Breadcrumb navigation back to dashboard
- [ ] CSS in `admin/assets/css/translation-progress.scss`
- [ ] Unit tests for Vanilla JS components
- [ ] E2E tests for page functionality

---

### Week 6: Team Management & Role-Based Access Control

#### Task 6.1: Custom User Roles & Capabilities

**Required Skills:** `users-permissions`

**File:** `includes/Team/RoleManager.php`
**Class:** `MultilingualPressZone\Team\RoleManager`

##### Sub-task 6.1.1: Define Custom Roles

**Required Skills:** `users-permissions`
- [ ] Define role: `mpz_administrator` (full access)
  - All capabilities
  - Can manage team members
  - Can view all reports
  - Can configure system settings
  
- [ ] Define role: `mpz_translation_manager` (workflow oversight)
  - Capabilities: `manage_translators`, `assign_translations`, `view_reports`, `manage_workflow`, `override_deadlines`, `view_audit_logs`
  - Cannot modify system settings
  - Can reassign any translation
  - Can approve/reject any translation
  
- [ ] Define role: `mpz_translator` (content translation)
  - Capabilities: `translate_content`, `submit_for_review`, `view_own_assignments`, `request_deadline_extension`
  - Can only see own assigned translations
  - Cannot assign to others
  - Cannot access reports
  
- [ ] Define role: `mpz_reviewer` (quality control)
  - Capabilities: `review_translations`, `approve_translations`, `reject_translations`, `view_review_queue`
  - Can see all translations in review state
  - Can provide feedback to translators
  - Cannot assign translations
  
- [ ] Define role: `mpz_viewer` (read-only)
  - Capabilities: `view_translations`, `view_reports`
  - No editing capabilities
  - Useful for clients/stakeholders

##### Sub-task 6.1.2: Role Registration Implementation

**Required Skills:** `users-permissions`
**File:** `includes/Team/RoleManager.php`
- [ ] Implement `RoleManager::registerRoles(): void` (called on plugin activation)
- [ ] Implement `RoleManager::unregisterRoles(): void` (called on plugin deactivation)
- [ ] Implement `RoleManager::getRoleCapabilities(string $role): array`
- [ ] Implement `RoleManager::addRoleToUser(int $userId, string $role): bool`
- [ ] Implement `RoleManager::removeRoleFromUser(int $userId, string $role): bool`
- [ ] Implement `RoleManager::userHasRole(int $userId, string $role): bool`
- [ ] Implement `RoleManager::getUsersByRole(string $role): array`
- [ ] Store role definitions in `includes/Team/RoleDefinitions.php` as configuration array
- [ ] Add migration script to assign roles to existing users
- [ ] Add hooks: `mpz_role_added`, `mpz_role_removed`, `mpz_capabilities_modified`
- [ ] Add filters: `mpz_role_capabilities`, `mpz_role_display_name`
- [ ] Unit tests for role CRUD operations
- [ ] Integration tests with WordPress role system

##### Sub-task 6.1.3: Capability System Implementation

**Required Skills:** `users-permissions`
**File:** `includes/Team/PermissionManager.php`
**Class:** `MultilingualPressZone\Team\PermissionManager`

- [ ] Implement `PermissionManager::userCan(int $userId, string $capability, array $context = []): bool`
- [ ] Implement `PermissionManager::currentUserCan(string $capability, array $context = []): bool`
- [ ] Implement `PermissionManager::checkPermission(string $capability, array $context = []): void` (throws exception if denied)
- [ ] Implement context-aware permissions:
  - `view_translation` + context['translation_id'] → check if user is assigned or has manager role
  - `edit_translation` + context['translation_id'] → check if user is assigned and translation is in draft state
  - `assign_translation` + context['user_id'] → check if target user has translator role
- [ ] Implement `PermissionManager::getUserCapabilities(int $userId): array`
- [ ] Implement `PermissionManager::canAccessAdminPage(int $userId, string $pageSlug): bool`
- [ ] Add capability checks to all admin pages (at page load)
- [ ] Add capability checks to all REST API endpoints (in permission_callback)
- [ ] Create `PermissionDeniedException` exception class
- [ ] Add filter: `mpz_user_has_capability` (for custom permission logic)
- [ ] Unit tests for all capability checks
- [ ] Integration tests with actual user sessions

##### Sub-task 6.1.4: Role Management UI

**Required Skills:** `admin-panel-fullstack`, `users-permissions`
**File:** `admin/pages/TeamRoles.js` (Vanilla JS, NOT React/TypeScript)
**Route:** `/wp-admin/admin.php?page=mpz-team-roles`

- [ ] Create role list table with columns: Role Name, Display Name, User Count, Capabilities
- [ ] Add "Edit Capabilities" button for each role (opens modal)
- [ ] Create capability editor modal:
  - Checkbox list of all available capabilities
  - Grouped by category (Workflow, Content, Reports, Team, System)
  - Description for each capability
  - Save/Cancel buttons
- [ ] Add "Assign Role to User" button (opens user selector)
- [ ] Create user role assignment modal:
  - Search users by name/email
  - Select user
  - Select role to assign
  - Optional: expiration date for temporary access
- [ ] Display warning when removing critical capabilities
- [ ] Show "Users with this role" section (expandable)
- [ ] Add bulk actions: Assign role to multiple users, Remove role from multiple users
- [ ] Add search/filter for users by role
- [ ] Implement AJAX save for instant feedback
- [ ] Add undo/redo capability for accidental changes
- [ ] CSS in `admin/assets/css/team-roles.scss`
- [ ] Unit tests for Vanilla JS components
- [ ] E2E tests for role management flows

#### Task 6.2: User Activity Tracking

**Required Skills:** `users-permissions`

**File:** `includes/Team/ActivityTracker.php`
**Class:** `MultilingualPressZone\Team\ActivityTracker`

##### Sub-task 6.2.1: Activity Tracking Database

**Required Skills:** `database-operations`
**File:** `includes/Core/Database.php`
- [ ] CREATE TABLE `wp_mpz_user_activity`:
  - `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  - `user_id` BIGINT UNSIGNED NOT NULL
  - `activity_type` VARCHAR(50) NOT NULL (e.g., 'translation_started', 'translation_submitted', 'review_completed')
  - `object_type` VARCHAR(50) NOT NULL (e.g., 'translation', 'workflow_state')
  - `object_id` BIGINT UNSIGNED NOT NULL
  - `metadata` JSON NULL (additional context)
  - `ip_address` VARCHAR(45) NULL
  - `user_agent` VARCHAR(512) NULL
  - `created_at` DATETIME NOT NULL
- [ ] Add indexes: `idx_user_activity` (user_id, created_at), `idx_activity_type` (activity_type), `idx_object` (object_type, object_id)
- [ ] Add partition by RANGE on created_at (monthly partitions for 12 months)
- [ ] Create migration script
- [ ] Add data retention policy (keep 90 days by default, configurable)

##### Sub-task 6.2.2: Activity Tracker Implementation
- [ ] Implement `ActivityTracker::__construct(Database $db)`
- [ ] Implement `ActivityTracker::track(int $userId, string $activityType, string $objectType, int $objectId, array $metadata = []): bool`
- [ ] Implement `ActivityTracker::getUserActivity(int $userId, array $filters = []): array`
  - Filters: date_range, activity_type, limit, offset
- [ ] Implement `ActivityTracker::getRecentActivity(array $filters = []): array` (all users)
- [ ] Implement `ActivityTracker::getUserStats(int $userId, string $period = 'week'): array`
  - Returns: total_activities, by_type, most_active_hour, most_active_day
- [ ] Implement `ActivityTracker::getActiveUsers(string $period = 'day'): array`
  - Returns users with activity in given period, sorted by activity count
- [ ] Auto-track activities by hooking into:
  - `mpz_after_state_transition`
  - `mpz_translation_created`
  - `mpz_translation_updated`
  - `mpz_role_added`
  - WordPress login/logout hooks
- [ ] Implement batch insert for high-volume tracking (buffer 10 events before INSERT)
- [ ] Add privacy compliance: anonymize IP addresses (last octet to 0)
- [ ] Add GDPR export: `ActivityTracker::exportUserData(int $userId): array`
- [ ] Add GDPR deletion: `ActivityTracker::deleteUserData(int $userId): bool`
- [ ] Add filter: `mpz_track_activity` (allow disabling tracking for specific events)
- [ ] Unit tests for tracking logic
- [ ] Performance tests with 1M+ activity records

##### Sub-task 6.2.3: Activity Log Viewer UI

**Required Skills:** `admin-panel-fullstack`
**File:** `admin/pages/ActivityLog.js` (Vanilla JS, NOT React/TypeScript)
**Route:** `/wp-admin/admin.php?page=mpz-activity-log`

- [ ] Create activity log table with columns: Timestamp, User, Activity Type, Object, Details, IP Address
- [ ] Add real-time updates (AJAX polling every 10 seconds)
- [ ] Add filters:
  - Date range picker
  - User selector (dropdown with search)
  - Activity type multi-select
  - Object type multi-select
- [ ] Add search box for free-text search in metadata
- [ ] Implement infinite scroll pagination
- [ ] Add "View Details" button for each activity (opens modal with full metadata JSON)
- [ ] Add export functionality (CSV, JSON) with applied filters
- [ ] Show user avatar and name (clickable to filter by that user)
- [ ] Color-code activity types: Green (created), Blue (updated), Red (deleted), Orange (workflow)
- [ ] Add "Group by User" toggle view
- [ ] Implement activity replay: show sequence of actions for a specific object
- [ ] CSS in `admin/assets/css/activity-log.scss`
- [ ] Unit tests for Vanilla JS components
- [ ] E2E tests for filtering and export

#### Task 6.3: Performance Metrics & Translator Scoring

**File:** `includes/Team/PerformanceMetrics.php`
**Class:** `MultilingualPressZone\Team\PerformanceMetrics`

##### Sub-task 6.3.1: Metrics Collection System
- [ ] Implement `PerformanceMetrics::__construct(Database $db, ActivityTracker $activity)`
- [ ] Implement `PerformanceMetrics::calculateTranslatorScore(int $userId, string $period = 'month'): float`
  - Score components:
    - Completion rate (40%): completed / assigned
    - Quality score (30%): approved_first_time / submitted
    - Speed score (20%): avg_time vs target_time
    - Consistency score (10%): std_deviation of completion times
  - Returns: 0-100 score
- [ ] Implement `PerformanceMetrics::getTranslatorStats(int $userId, string $period = 'month'): array`
  - Returns:
    - total_assigned
    - total_completed
    - total_in_progress
    - avg_completion_time (seconds)
    - fastest_completion_time
    - slowest_completion_time
    - first_time_approval_rate
    - revision_count
    - words_translated
    - languages_worked_on
- [ ] Implement `PerformanceMetrics::getQualityMetrics(int $userId, string $period = 'month'): array`
  - Returns:
    - approval_rate
    - rejection_count
    - avg_revisions_per_translation
    - common_rejection_reasons (from reviewer feedback)
- [ ] Implement `PerformanceMetrics::getProductivityMetrics(int $userId, string $period = 'month'): array`
  - Returns:
    - words_per_day
    - translations_per_day
    - peak_productivity_hours
    - productivity_trend (increasing/stable/decreasing)
- [ ] Implement `PerformanceMetrics::compareToTeam(int $userId, string $period = 'month'): array`
  - Returns user's rank and percentile for each metric
- [ ] Create `wp_mpz_performance_snapshots` table for historical tracking:
  - `user_id` BIGINT UNSIGNED
  - `period` DATE (first day of week/month)
  - `score` DECIMAL(5,2)
  - `metrics` JSON (full metrics snapshot)
  - `created_at` DATETIME
  - PRIMARY KEY (user_id, period)
- [ ] Create WP-Cron job: `mpz_calculate_performance_scores` (runs weekly)
- [ ] Unit tests for score calculations
- [ ] Validate scoring algorithm with sample data

##### Sub-task 6.3.2: Workload Balancing Algorithm
**File:** `includes/Team/WorkloadBalancer.php`
- [ ] Implement `WorkloadBalancer::getCurrentWorkload(int $userId): array`
  - Returns: active_translations, estimated_hours_remaining, capacity_percentage
- [ ] Implement `WorkloadBalancer::getOptimalAssignee(string $sourceLang, string $targetLang, int $priority = 5): ?int`
  - Algorithm:
    1. Filter translators by language pair proficiency
    2. Exclude translators at capacity (>= max_concurrent)
    3. Consider current workload (favor lower workload)
    4. Consider past performance score
    5. Consider specialization (content type match)
    6. Return best match or null if none available
- [ ] Implement `WorkloadBalancer::suggestReassignment(int $translationId): array`
  - Returns list of candidate translators with scores
  - Used when current translator is overdue/struggling
- [ ] Implement `WorkloadBalancer::balanceTeamWorkload(): array`
  - Scans all active translations
  - Suggests reassignments to balance load
  - Returns list of recommended changes
- [ ] Implement `WorkloadBalancer::calculateEstimatedTime(int $translationId, int $userId): int`
  - Based on word count and translator's avg words-per-hour
- [ ] Add settings page for workload parameters:
  - Default max_concurrent per translator
  - Workload calculation formula
  - Priority weighting
- [ ] Unit tests for assignment algorithm
- [ ] Load tests with 100+ translators and 1000+ active translations

##### Sub-task 6.3.3: Time Tracking Implementation
**File:** `includes/Team/TimeTracker.php`
**Class:** `MultilingualPressZone\Team\TimeTracker`

- [ ] CREATE TABLE `wp_mpz_time_entries`:
  - `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  - `user_id` BIGINT UNSIGNED NOT NULL
  - `translation_id` BIGINT UNSIGNED NOT NULL
  - `started_at` DATETIME NOT NULL
  - `ended_at` DATETIME NULL
  - `duration_seconds` INT UNSIGNED NULL
  - `is_active` TINYINT(1) DEFAULT 0
  - `notes` TEXT NULL
  - `created_at` DATETIME NOT NULL
- [ ] Add indexes: `idx_user_time` (user_id, translation_id), `idx_active` (is_active)
- [ ] Implement `TimeTracker::startTimer(int $userId, int $translationId): int` (returns entry_id)
- [ ] Implement `TimeTracker::stopTimer(int $entryId): int` (returns duration_seconds)
- [ ] Implement `TimeTracker::getTotalTime(int $translationId): int` (sum all entries)
- [ ] Implement `TimeTracker::getUserTimeEntries(int $userId, array $filters = []): array`
- [ ] Auto-stop active timers after 8 hours of inactivity
- [ ] Add manual time entry: `TimeTracker::addManualEntry(int $userId, int $translationId, int $durationSeconds, string $notes): int`
- [ ] Create timer widget in admin bar (start/stop timer for current translation)
- [ ] Add time tracking summary to translator dashboard
- [ ] Add time-based reports: time per language pair, time per content type
- [ ] Unit tests for timer operations
- [ ] Integration tests with frontend widget

#### Task 6.4: Team Dashboard

**Required Skills:** `admin-panel-fullstack`

**File:** `admin/pages/TeamDashboard.js` (Vanilla JS, NOT React/TypeScript)
**Route:** `/wp-admin/admin.php?page=mpz-team-dashboard`

##### Sub-task 6.4.1: Team Overview Section

**Required Skills:** `admin-panel-fullstack`
- [ ] Create responsive grid layout
- [ ] **Overview Cards:**
  - Total Team Members (by role)
  - Active Translators (worked in last 7 days)
  - Avg Team Performance Score
  - Total Translations This Month
- [ ] **Team Velocity Chart:**
  - Line chart showing translations completed per day (last 30 days)
  - Compare to previous period
  - Show trend line
- [ ] **Workload Distribution Chart:**
  - Bar chart showing active translations per translator
  - Color-code by capacity (green < 70%, yellow 70-90%, red > 90%)
  - Click to view translator details

##### Sub-task 6.4.2: Translator Performance Table

**Required Skills:** `database-operations`
- [ ] Columns:
  - Avatar & Name
  - Role
  - Performance Score (0-100, with badge color)
  - Active Translations
  - Completed (7d)
  - Avg Completion Time
  - Quality Score (approval rate)
  - Last Active
  - Actions (View Details, Message, Assign Translation)
- [ ] Sortable by any column
- [ ] Click row to open translator detail modal
- [ ] Add bulk actions: Send message to selected, Assign translation to selected
- [ ] Add filters: Role, Performance Range, Activity Status, Language Pair
- [ ] Add search by name/email
- [ ] Pagination with 25/50/100 per page options
- [ ] Export to CSV

##### Sub-task 6.4.3: Translator Detail Modal
**Component:** `TranslatorDetailModal.js` (Vanilla JS)
- [ ] **Header:**
  - Avatar, Name, Email, Role
  - Edit button (opens user edit screen)
  - Send message button
- [ ] **Performance Tab:**
  - Performance score with breakdown by component
  - Trend chart (last 12 weeks)
  - Comparison to team average
- [ ] **Statistics Tab:**
  - Current workload (active translations list)
  - Completed translations (last 30 days)
  - Avg completion time
  - Quality metrics
  - Language pairs with proficiency levels
- [ ] **Activity Timeline Tab:**
  - Recent activity feed (last 50 actions)
  - Filterable by activity type
- [ ] **Time Tracking Tab:**
  - Total hours worked this week/month
  - Time entries table
  - Time per translation breakdown
- [ ] **Reviews Tab:**
  - List of received reviews from reviewers
  - Approval/rejection history
  - Common feedback themes

##### Sub-task 6.4.4: Real-Time Updates
- [ ] Implement WebSocket connection for real-time dashboard updates
- [ ] Alternative: AJAX polling every 30 seconds if WebSockets unavailable
- [ ] Update active translation counts in real-time
- [ ] Update performance scores when new translations completed
- [ ] Show toast notifications for significant events (translation completed by team member)
- [ ] Add "Last updated" timestamp
- [ ] Add manual refresh button

##### Sub-task 6.4.5: Team Analytics Section
- [ ] **Languages Coverage Matrix:**
  - Heatmap showing translator count per language pair
  - Identify gaps in coverage
- [ ] **Capacity Planning:**
  - Current team capacity vs demand
  - Forecast need based on translation queue
  - Suggest hiring needs
- [ ] **Bottleneck Analysis:**
  - Identify which translators are consistently overloaded
  - Identify which language pairs are bottlenecks
  - Suggest redistribution
- [ ] CSS in `admin/assets/css/team-dashboard.scss`
- [ ] Unit tests for all Vanilla JS components
- [ ] E2E tests for dashboard interactions

---

### Week 7: Audit Logging & Compliance

#### Task 7.1: Audit Log System

**File:** `includes/Audit/AuditLogger.php`
**Class:** `MultilingualPressZone\Audit\AuditLogger`

##### Sub-task 7.1.1: Audit Log Database Schema

**Required Skills:** `database-operations`
**File:** `includes/Core/Database.php`
- [ ] CREATE TABLE `wp_mpz_audit_logs`:
  - `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  - `user_id` BIGINT UNSIGNED NULL (NULL for system actions)
  - `user_email` VARCHAR(255) NULL (denormalized for deleted users)
  - `user_role` VARCHAR(50) NULL
  - `action` VARCHAR(100) NOT NULL (e.g., 'translation.updated', 'user.role_changed')
  - `object_type` VARCHAR(50) NOT NULL (e.g., 'translation', 'user', 'setting')
  - `object_id` BIGINT UNSIGNED NULL
  - `object_name` VARCHAR(255) NULL (denormalized, e.g., post title)
  - `old_value` LONGTEXT NULL (JSON)
  - `new_value` LONGTEXT NULL (JSON)
  - `diff` LONGTEXT NULL (JSON, computed diff)
  - `ip_address` VARCHAR(45) NULL
  - `user_agent` VARCHAR(512) NULL
  - `request_uri` VARCHAR(512) NULL
  - `severity` ENUM('info', 'warning', 'critical') DEFAULT 'info'
  - `status` ENUM('success', 'failure') DEFAULT 'success'
  - `error_message` TEXT NULL
  - `session_id` VARCHAR(64) NULL
  - `created_at` DATETIME NOT NULL
- [ ] Add indexes: 
  - `idx_user` (user_id, created_at)
  - `idx_action` (action, created_at)
  - `idx_object` (object_type, object_id)
  - `idx_created_at` (created_at)
  - `idx_severity` (severity, created_at)
- [ ] Add FULLTEXT index on action, object_name for search
- [ ] Partition by RANGE on created_at (monthly partitions)
- [ ] Create migration script
- [ ] Add automatic partitioning management (create new partitions, drop old ones)

##### Sub-task 7.1.2: AuditLogger Core Implementation
- [ ] Implement `AuditLogger::__construct(Database $db)`
- [ ] Implement `AuditLogger::log(string $action, string $objectType, $objectId, array $options = []): int`
  - Options: old_value, new_value, severity, status, error_message
  - Auto-capture: user_id, ip_address, user_agent, request_uri, session_id
  - Compute diff if both old and new values provided
  - Return log entry ID
- [ ] Implement `AuditLogger::logSuccess(string $action, string $objectType, $objectId, $oldValue, $newValue): int`
- [ ] Implement `AuditLogger::logFailure(string $action, string $objectType, $objectId, string $errorMessage): int`
- [ ] Implement `AuditLogger::logCritical(string $action, string $objectType, $objectId, array $options = []): int`
  - Also send email notification to administrators
- [ ] Implement change detection helper: `AuditLogger::computeDiff($oldValue, $newValue): array`
  - Recursive diff for nested arrays/objects
  - Return only changed fields
- [ ] Implement sensitive data masking:
  - Auto-mask fields named: password, token, secret, api_key
  - Configurable via filter: `mpz_audit_sensitive_fields`
- [ ] Implement bulk logging for batch operations: `AuditLogger::logBatch(array $entries): bool`
- [ ] Add async logging option (queue to background job for high-volume operations)
- [ ] Add filter: `mpz_audit_log_entry` (modify entry before saving)
- [ ] Add action: `mpz_audit_logged` (fired after log saved)
- [ ] Unit tests for all logging scenarios
- [ ] Integration tests with actual user actions

##### Sub-task 7.1.3: Automatic Audit Logging Integration
**File:** `includes/Audit/AutoAuditHooks.php`

Hook into these events and auto-log:

- [ ] **Translation Events:**
  - `mpz_translation_created` → log 'translation.created'
  - `mpz_translation_updated` → log 'translation.updated' (with diff)
  - `mpz_translation_deleted` → log 'translation.deleted'
  - `mpz_after_state_transition` → log 'translation.state_changed'
  
- [ ] **Workflow Events:**
  - Assignment → log 'translation.assigned' (old_user, new_user)
  - Deadline changes → log 'translation.deadline_changed' (old_deadline, new_deadline)
  - Review approval → log 'translation.approved' (reviewer, notes)
  - Review rejection → log 'translation.rejected' (reviewer, reason)
  
- [ ] **User & Team Events:**
  - Role added → log 'user.role_added' (user, role)
  - Role removed → log 'user.role_removed' (user, role)
  - User created → log 'user.created'
  - User deleted → log 'user.deleted'
  - Capability changed → log 'user.capability_changed'
  
- [ ] **Settings Events:**
  - Plugin settings saved → log 'settings.updated' (changed fields only)
  - Language added → log 'language.created'
  - Language disabled → log 'language.disabled'
  
- [ ] **Security Events:**
  - Failed permission check → log 'security.permission_denied' (severity: warning)
  - Failed login (if applicable) → log 'security.failed_login' (severity: warning)
  - Mass deletion → log 'security.mass_deletion' (severity: critical)
  
- [ ] **System Events:**
  - Plugin activation → log 'system.plugin_activated'
  - Plugin deactivation → log 'system.plugin_deactivated'
  - Database migration → log 'system.migration_executed'
  
- [ ] Add action priority management (ensure audit logs after actual change)
- [ ] Add error handling (audit logging failure should not break main operation)
- [ ] Integration tests for each hook

##### Sub-task 7.1.4: Data Retention & Cleanup
**File:** `includes/Audit/RetentionManager.php`

- [ ] Implement `RetentionManager::__construct(Database $db)`
- [ ] Implement `RetentionManager::getRetentionPolicy(): int` (returns days)
- [ ] Implement `RetentionManager::setRetentionPolicy(int $days): bool`
- [ ] Implement `RetentionManager::cleanupOldLogs(): int` (returns deleted count)
  - Delete logs older than retention period
  - Keep critical severity logs indefinitely (configurable)
  - Archive instead of delete (optional, configurable)
- [ ] Implement `RetentionManager::archiveLogs(DateTime $before): string` (returns archive file path)
  - Export old logs to JSON/CSV file
  - Compress with gzip
  - Store in wp-content/uploads/mpz-audit-archives/
  - Return file path
- [ ] Create WP-Cron job: `mpz_cleanup_audit_logs` (runs daily)
- [ ] Add settings page for retention policy
- [ ] Add manual cleanup button in settings
- [ ] Add archive browser UI (list + download archived files)
- [ ] Implement restore from archive functionality
- [ ] Unit tests for cleanup logic
- [ ] Test with large datasets (1M+ logs)

#### Task 7.2: Audit Log Viewer UI

**Required Skills:** `admin-panel-fullstack`

**File:** `admin/pages/AuditLog.js` (Vanilla JS, NOT React/TypeScript)
**Route:** `/wp-admin/admin.php?page=mpz-audit-log`

##### Sub-task 7.2.1: Main Audit Log View

**Required Skills:** `admin-panel-fullstack`
- [ ] Create audit log table with columns:
  - Timestamp
  - User (with avatar)
  - Action (with icon based on action type)
  - Object (clickable to view object)
  - Status (success/failure badge)
  - Severity (color-coded badge)
  - Details (expand button)
- [ ] Implement expandable row details:
  - Full user agent
  - IP address
  - Request URI
  - Session ID
  - Old value (JSON viewer)
  - New value (JSON viewer)
  - Diff (highlighted changes)
  - Error message (if failure)
- [ ] Add color coding:
  - Info: Blue
  - Warning: Orange
  - Critical: Red
  - Failure: Red background
- [ ] Add real-time updates (new logs appear at top with animation)
- [ ] Implement virtual scrolling for performance (handle 100k+ logs)

##### Sub-task 7.2.2: Advanced Filtering

**Required Skills:** `wordpress-php-integration`
- [ ] **Filter Panel (collapsible sidebar):**
  - Date range picker (presets: Today, Yesterday, Last 7 days, Last 30 days, Custom)
  - User selector (multi-select with search)
  - Action type (multi-select, grouped by category)
  - Object type (multi-select)
  - Severity (checkboxes: Info, Warning, Critical)
  - Status (checkboxes: Success, Failure)
  - IP address filter (exact match or CIDR range)
  - Search box (full-text search in action, object_name, error_message)
- [ ] Implement filter presets:
  - "Security Events" (severity: warning+critical, category: security)
  - "Failed Actions" (status: failure)
  - "My Actions" (user_id: current user)
  - "Critical Events" (severity: critical)
- [ ] Save custom filter presets
- [ ] Add "Active Filters" pills (click to remove)
- [ ] Add "Clear All Filters" button
- [ ] Persist filter state in URL query params (shareable links)

##### Sub-task 7.2.3: Search & Query Builder

**Required Skills:** `admin-panel-fullstack`, `database-operations`
- [ ] Implement advanced query builder UI:
  - Add condition rows: Field, Operator, Value
  - Operators: equals, not equals, contains, starts with, greater than, less than, between, is null
  - Combine with AND/OR logic
  - Group conditions with parentheses
- [ ] Add saved searches functionality:
  - Save query with name
  - Quick access dropdown
  - Share saved search with team
- [ ] Implement search suggestions (autocomplete for common searches)
- [ ] Add search history (last 10 searches)
- [ ] Add "Export Search Results" button

##### Sub-task 7.2.4: Audit Log Detail Modal
**Component:** `AuditLogDetailModal.js` (Vanilla JS)

- [ ] **Header:**
  - Action name with icon
  - Timestamp (with timezone)
  - Status badge
  - Severity badge
  
- [ ] **User Information:**
  - Avatar, Name, Email
  - Role at time of action
  - Link to user's activity history
  
- [ ] **Object Information:**
  - Object type and ID
  - Object name (clickable to view object)
  - Link to object's audit history
  
- [ ] **Change Details:**
  - Side-by-side comparison: Old Value | New Value
  - Syntax-highlighted JSON
  - Diff viewer with added (green) and removed (red) highlights
  - Collapsible sections for large objects
  
- [ ] **Request Context:**
  - IP address (with geolocation lookup)
  - User agent (parsed: browser, OS, device)
  - Request URI
  - Session ID
  - Referrer URL
  
- [ ] **Related Events:**
  - List of logs in same session (5 minutes window)
  - Link to view full session history
  
- [ ] **Actions:**
  - Copy log ID
  - Export log entry (JSON)
  - Report issue (if failure)
  - Add to investigation (if available)

##### Sub-task 7.2.5: Export & Reporting
- [ ] Implement export functionality:
  - Formats: CSV, JSON, Excel (XLSX), PDF
  - Include applied filters in export
  - Option to include/exclude sensitive data
  - Async export for large datasets (download link via email)
- [ ] Implement scheduled reports:
  - Configure report: filters, format, frequency
  - Frequencies: Daily, Weekly, Monthly
  - Email recipients list
  - Store in cron jobs table
- [ ] Create report templates:
  - Security audit report (all critical/warning events)
  - User activity report (per user or all users)
  - Failed actions report (all failures)
  - Change history report (for specific object)
- [ ] Add report preview before export/schedule
- [ ] CSS in `admin/assets/css/audit-log.scss`
- [ ] Unit tests for all Vanilla JS components
- [ ] E2E tests for filtering and export

#### Task 7.3: Compliance & Security Features

##### Sub-task 7.3.1: GDPR Compliance Tools
**File:** `includes/Audit/GDPRCompliance.php`

- [ ] Implement `GDPRCompliance::exportUserData(int $userId): array`
  - Export all audit logs for user
  - Export all translations created/modified by user
  - Export all activity history
  - Export all time tracking data
  - Return structured data array (for WordPress data export tool)
  
- [ ] Implement `GDPRCompliance::deleteUserData(int $userId): bool`
  - Anonymize audit logs (replace user_id with 0, user_email with '[deleted]')
  - Keep logs for compliance but remove PII
  - Delete or anonymize activity tracking
  - Delete time tracking data
  - Option to reassign translations or delete them
  
- [ ] Implement `GDPRCompliance::generateDataReport(int $userId): string`
  - Human-readable PDF report
  - Summary of all data stored
  - Includes audit logs, translations, activity
  
- [ ] Add consent tracking:
  - Track when user agreed to data processing
  - Store consent version
  - Log consent withdrawal
  
- [ ] Add data processing disclosure:
  - Document what data is collected
  - Document why it's collected
  - Document how long it's retained
  - Document who has access
  
- [ ] Integrate with WordPress privacy tools:
  - Add exporter to `wp_privacy_data_exporters` hook
  - Add eraser to `wp_privacy_data_erasers` hook
  
- [ ] Unit tests for GDPR functions
- [ ] Compliance verification tests

##### Sub-task 7.3.2: Security Monitoring & Alerts
**File:** `includes/Audit/SecurityMonitor.php`

- [ ] Implement `SecurityMonitor::detectAnomalies(): array`
  - Detect unusual patterns:
    - Mass deletions (> 10 objects in 1 minute)
    - Rapid permission changes (> 5 in 1 minute)
    - Failed permission checks from same user (> 10 in 5 minutes)
    - After-hours activity (outside normal working hours)
    - Unusual IP addresses (new country/region)
  - Return list of detected anomalies
  
- [ ] Implement `SecurityMonitor::alertAdministrators(array $anomaly): bool`
  - Send email notification to all administrators
  - Include: detected pattern, affected user, timestamp, affected objects, recommended action
  - Create dashboard notification
  
- [ ] Implement `SecurityMonitor::blockUser(int $userId, string $reason): bool`
  - Temporarily suspend user account
  - Log security event
  - Notify administrators
  - Require admin approval to unblock
  
- [ ] Create security dashboard widget:
  - Recent security events (last 7 days)
  - Anomaly count by type
  - Top users with warnings
  - Quick actions: View details, Block user, Dismiss alert
  
- [ ] Create WP-Cron job: `mpz_security_monitoring` (runs every 10 minutes)
  
- [ ] Add configurable security rules:
  - Thresholds for anomaly detection
  - Enable/disable specific detections
  - Whitelist trusted IPs
  - Configure alert recipients
  
- [ ] Unit tests for anomaly detection
- [ ] Integration tests with email alerts

##### Sub-task 7.3.3: Audit Log Integrity Verification
**File:** `includes/Audit/IntegrityVerifier.php`

- [ ] Implement tamper detection:
  - Add `checksum` column to `wp_mpz_audit_logs` (SHA256 hash of log data + secret)
  - Calculate checksum on insert
  - Verify checksum on read
  - Detect modified logs
  
- [ ] Implement `IntegrityVerifier::verifyLog(int $logId): bool`
  - Recalculate checksum
  - Compare with stored checksum
  - Return true if match
  
- [ ] Implement `IntegrityVerifier::verifyAllLogs(): array`
  - Scan all logs
  - Return list of tampered logs
  - Can be slow, run as background job
  
- [ ] Create WP-Cron job: `mpz_verify_audit_integrity` (runs weekly)
  
- [ ] Implement chain verification (blockchain-style):
  - Each log includes hash of previous log
  - Detect if logs deleted from sequence
  
- [ ] Add admin notice if tampering detected
  
- [ ] Add "Integrity Status" indicator in audit log viewer
  
- [ ] Unit tests for integrity verification
- [ ] Tamper simulation tests

---

### Week 8: Advanced Reporting & Analytics

#### Task 8.1: Reporting Engine Architecture

**File:** `includes/Reporting/ReportEngine.php`
**Class:** `MultilingualPressZone\Reporting\ReportEngine`

##### Sub-task 8.1.1: Report Engine Core
- [ ] Implement `ReportEngine::__construct(Database $db, CacheManager $cache)`
- [ ] Implement `ReportEngine::generateReport(string $reportType, array $parameters = []): Report`
  - Factory method to create specific report instances
  - Parameters: date_range, filters, grouping, sorting
  - Return Report object with data and metadata
  
- [ ] Create `Report` value object class:
  - Properties: title, description, data (array), metadata (date range, filters applied), generated_at
  - Methods: toArray(), toJSON(), toCSV(), toPDF()
  
- [ ] Implement report caching:
  - Cache key based on report type + parameters hash
  - TTL: 5 minutes for real-time reports, 1 hour for historical reports
  - Option to force refresh
  
- [ ] Implement report scheduling:
  - Store scheduled reports in `wp_mpz_scheduled_reports` table
  - Fields: id, report_type, parameters (JSON), frequency, recipients, format, last_run, next_run
  - Create WP-

<task_metadata>
session_id: ses_40d03f579ffe71CR1CtBc13JES
</task_metadata>