# Technical Specifications - How to Malaysia Website/Blog CMS

## System Architecture Overview

### Technology Stack
- **Frontend:** HTML5, CSS3, JavaScript (ES6+), Bootstrap 5
- **Backend:** PHP 8.1+, MySQL 8.0+
- **CMS Platform:** WordPress 6.3+ or Custom Laravel-based CMS
- **Server:** Apache 2.4+ / Nginx 1.20+
- **Operating System:** Linux (Ubuntu 22.04 LTS)

### Development Environment Requirements
- **Local Development:** XAMPP 8.2+ (Current setup)
- **Version Control:** Git 2.40+
- **Package Managers:** Composer, NPM
- **Build Tools:** Webpack, Sass/SCSS
- **IDE/Editor:** VS Code with recommended extensions

## Database Design Specifications

### Core Tables Structure

#### Content Management Tables
```sql
-- Articles/Posts Table
CREATE TABLE articles (
    id INT PRIMARY KEY AUTO_INCREMENT,
    title VARCHAR(255) NOT NULL,
    slug VARCHAR(255) UNIQUE NOT NULL,
    content TEXT NOT NULL,
    excerpt TEXT,
    featured_image VARCHAR(255),
    category_id INT,
    author_id INT,
    status ENUM('draft', 'published', 'archived'),
    seo_title VARCHAR(60),
    seo_description VARCHAR(160),
    seo_keywords TEXT,
    views_count INT DEFAULT 0,
    rating_average DECIMAL(3,2) DEFAULT 0,
    rating_count INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    published_at TIMESTAMP NULL,
    INDEX idx_category (category_id),
    INDEX idx_author (author_id),
    INDEX idx_status (status),
    INDEX idx_published (published_at),
    FULLTEXT(title, content, excerpt)
);

-- Categories Table
CREATE TABLE categories (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    slug VARCHAR(100) UNIQUE NOT NULL,
    description TEXT,
    parent_id INT NULL,
    sort_order INT DEFAULT 0,
    icon VARCHAR(50),
    color VARCHAR(7),
    is_featured BOOLEAN DEFAULT FALSE,
    seo_title VARCHAR(60),
    seo_description VARCHAR(160),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_parent (parent_id),
    INDEX idx_featured (is_featured)
);

-- Tags Table
CREATE TABLE tags (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL UNIQUE,
    slug VARCHAR(50) UNIQUE NOT NULL,
    usage_count INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Article-Tag Relationship
CREATE TABLE article_tags (
    article_id INT,
    tag_id INT,
    PRIMARY KEY (article_id, tag_id),
    FOREIGN KEY (article_id) REFERENCES articles(id) ON DELETE CASCADE,
    FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
);
```

#### User Management Tables
```sql
-- Users Table
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    role ENUM('admin', 'editor', 'author', 'contributor', 'subscriber') DEFAULT 'subscriber',
    avatar VARCHAR(255),
    bio TEXT,
    status ENUM('active', 'inactive', 'suspended') DEFAULT 'active',
    last_login TIMESTAMP NULL,
    email_verified BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_email (email),
    INDEX idx_role (role),
    INDEX idx_status (status)
);

-- User Sessions
CREATE TABLE user_sessions (
    id VARCHAR(128) PRIMARY KEY,
    user_id INT,
    ip_address VARCHAR(45),
    user_agent TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_user (user_id),
    INDEX idx_expires (expires_at)
);
```

#### Interaction & Engagement Tables
```sql
-- Comments Table
CREATE TABLE comments (
    id INT PRIMARY KEY AUTO_INCREMENT,
    article_id INT NOT NULL,
    user_id INT NULL,
    parent_id INT NULL,
    author_name VARCHAR(100),
    author_email VARCHAR(255),
    content TEXT NOT NULL,
    status ENUM('pending', 'approved', 'spam', 'rejected') DEFAULT 'pending',
    ip_address VARCHAR(45),
    user_agent TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (article_id) REFERENCES articles(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL,
    FOREIGN KEY (parent_id) REFERENCES comments(id) ON DELETE CASCADE,
    INDEX idx_article (article_id),
    INDEX idx_status (status),
    INDEX idx_created (created_at)
);

-- Ratings Table
CREATE TABLE ratings (
    id INT PRIMARY KEY AUTO_INCREMENT,
    article_id INT NOT NULL,
    user_id INT NULL,
    rating TINYINT CHECK (rating BETWEEN 1 AND 5),
    ip_address VARCHAR(45),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (article_id) REFERENCES articles(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL,
    UNIQUE KEY unique_article_user (article_id, user_id),
    UNIQUE KEY unique_article_ip (article_id, ip_address),
    INDEX idx_article (article_id)
);

-- Newsletter Subscribers
CREATE TABLE newsletter_subscribers (
    id INT PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR(255) UNIQUE NOT NULL,
    name VARCHAR(100),
    status ENUM('active', 'unsubscribed', 'bounced') DEFAULT 'active',
    source VARCHAR(50),
    subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    unsubscribed_at TIMESTAMP NULL,
    INDEX idx_email (email),
    INDEX idx_status (status)
);
```

## API Specifications

### RESTful API Endpoints

#### Content API
```
GET    /api/articles              - Get articles list (paginated)
GET    /api/articles/{id}         - Get single article
GET    /api/articles/search       - Search articles
GET    /api/categories            - Get categories list
GET    /api/categories/{id}/articles - Get articles by category
GET    /api/tags                  - Get tags list
GET    /api/articles/popular      - Get popular articles
GET    /api/articles/recent       - Get recent articles
GET    /api/articles/featured     - Get featured articles
```

#### User Interaction API
```
POST   /api/comments              - Create comment
GET    /api/comments/{article_id} - Get comments for article
POST   /api/ratings               - Submit rating
GET    /api/ratings/{article_id}  - Get ratings for article
POST   /api/newsletter/subscribe  - Subscribe to newsletter
POST   /api/contact               - Submit contact form
```

#### Search API
```
GET    /api/search?q={query}&category={id}&tag={name}&sort={field}
POST   /api/search/suggestions    - Get search suggestions
GET    /api/search/popular        - Get popular search terms
```

### Response Format Standards
```json
{
  "success": true,
  "data": {
    "articles": [
      {
        "id": 123,
        "title": "How to Apply for Malaysian Visa",
        "slug": "how-to-apply-malaysian-visa",
        "excerpt": "Complete guide for visa application...",
        "category": {
          "id": 5,
          "name": "Immigration",
          "slug": "immigration"
        },
        "author": {
          "id": 2,
          "name": "John Doe",
          "avatar": "/uploads/avatars/john.jpg"
        },
        "featured_image": "/uploads/articles/visa-guide.jpg",
        "published_at": "2025-10-10T10:00:00Z",
        "reading_time": 8,
        "views_count": 1245,
        "rating": {
          "average": 4.7,
          "count": 89
        },
        "tags": ["visa", "immigration", "government"]
      }
    ],
    "pagination": {
      "current_page": 1,
      "per_page": 20,
      "total": 150,
      "total_pages": 8
    }
  },
  "message": "Articles retrieved successfully"
}
```

## Frontend Architecture

### Component Structure
```
src/
├── assets/
│   ├── css/
│   │   ├── main.scss
│   │   ├── components/
│   │   └── pages/
│   ├── js/
│   │   ├── main.js
│   │   ├── components/
│   │   └── utils/
│   └── images/
├── templates/
│   ├── layout/
│   │   ├── header.php
│   │   ├── footer.php
│   │   └── sidebar.php
│   ├── pages/
│   │   ├── home.php
│   │   ├── article.php
│   │   ├── category.php
│   │   └── search.php
│   └── components/
│       ├── article-card.php
│       ├── comment-form.php
│       └── newsletter-signup.php
```

### CSS Framework & Guidelines
- **Framework:** Bootstrap 5.3+
- **Custom Variables:** CSS custom properties for theming
- **Responsive Breakpoints:** 
  - xs: 0px, sm: 576px, md: 768px, lg: 992px, xl: 1200px, xxl: 1400px
- **Typography Scale:** Modular scale based on 1.25 ratio
- **Color Palette:** Malaysian-inspired colors with accessibility compliance

### JavaScript Architecture
```javascript
// Main application structure
const HowToMalaysia = {
    // Core modules
    Core: {
        init: function() { /* Initialize app */ },
        utils: { /* Utility functions */ },
        api: { /* API communication */ }
    },
    
    // Feature modules
    Search: {
        init: function() { /* Search functionality */ },
        autocomplete: function() { /* Search suggestions */ },
        filters: function() { /* Advanced filtering */ }
    },
    
    Comments: {
        init: function() { /* Comment system */ },
        form: { /* Comment form handling */ },
        moderation: { /* Comment moderation */ }
    },
    
    Newsletter: {
        init: function() { /* Newsletter signup */ },
        validation: function() { /* Form validation */ }
    }
};
```

## Security Specifications

### Authentication & Authorization
- **Password Requirements:** Minimum 8 characters, mixed case, numbers, special characters
- **Session Management:** Secure session handling with CSRF protection
- **Role-Based Access Control (RBAC):** Admin, Editor, Author, Contributor, Subscriber
- **Two-Factor Authentication (2FA):** Optional for admin accounts

### Data Protection
- **Input Validation:** Server-side validation for all user inputs
- **SQL Injection Prevention:** Prepared statements and parameterized queries
- **XSS Protection:** Input sanitization and output encoding
- **CSRF Protection:** Token-based CSRF protection for all forms
- **File Upload Security:** Type validation, size limits, secure storage

### Infrastructure Security
- **SSL/TLS:** Enforce HTTPS with strong cipher suites
- **Headers:** Security headers (HSTS, CSP, X-Frame-Options, etc.)
- **Rate Limiting:** API rate limiting and brute force protection
- **Backup Security:** Encrypted backups with secure storage
- **Monitoring:** Security event logging and monitoring

## Performance Specifications

### Loading Time Requirements
- **Homepage:** < 2 seconds (LCP)
- **Article Pages:** < 2.5 seconds (LCP)
- **Search Results:** < 1.5 seconds
- **Admin Dashboard:** < 3 seconds

### Optimization Techniques
- **Caching Strategy:** Multi-layer caching (browser, CDN, application, database)
- **Image Optimization:** WebP format, responsive images, lazy loading
- **Code Optimization:** Minification, compression, tree shaking
- **Database Optimization:** Query optimization, indexing, connection pooling
- **CDN Integration:** Static asset delivery via CDN

### Scalability Requirements
- **Concurrent Users:** Support 1000+ concurrent users
- **Database Performance:** < 100ms average query time
- **Server Resources:** Auto-scaling based on traffic
- **Monitoring:** Real-time performance monitoring and alerting

## SEO & Accessibility Specifications

### SEO Requirements
- **Meta Tags:** Dynamic meta titles, descriptions, and keywords
- **Structured Data:** JSON-LD markup for articles, reviews, organization
- **URL Structure:** SEO-friendly URLs with proper hierarchy
- **Sitemap:** Dynamic XML sitemap generation
- **Open Graph:** Social media optimization tags
- **Page Speed:** Core Web Vitals compliance

### Accessibility Compliance
- **WCAG 2.1 Level AA:** Full compliance with accessibility guidelines
- **Keyboard Navigation:** Full keyboard accessibility
- **Screen Reader Support:** ARIA labels and semantic HTML
- **Color Contrast:** Minimum 4.5:1 contrast ratio
- **Alternative Text:** Descriptive alt text for all images

### Multi-language Support
- **Languages:** English (primary), Bahasa Malaysia, Chinese (Simplified)
- **URL Structure:** Subdirectory structure (/en/, /my/, /zh/)
- **Content Translation:** Database-level translation support
- **RTL Support:** Right-to-left language support capability
- **Locale Settings:** Currency, date, number formatting per locale

## Integration Specifications

### Third-Party API Integrations
```php
// Weather API Integration
class WeatherService {
    public function getCurrentWeather($location) {
        // OpenWeatherMap API integration
    }
}

// Currency Conversion
class CurrencyService {
    public function convertCurrency($from, $to, $amount) {
        // Exchange rates API integration
    }
}

// Google Maps Integration
class MapService {
    public function getLocationData($address) {
        // Google Maps Geocoding API
    }
}
```

### Analytics & Tracking
- **Google Analytics 4:** Enhanced ecommerce tracking
- **Google Tag Manager:** Tag management and conversion tracking
- **Search Console:** Search performance monitoring
- **Heatmap Tools:** User behavior analysis
- **Performance Monitoring:** Real User Monitoring (RUM)

## Deployment & Maintenance

### Deployment Strategy
- **Environment Setup:** Development → Staging → Production
- **Version Control:** Git-based deployment with automated testing
- **Database Migrations:** Version-controlled database schema changes
- **Asset Pipeline:** Automated build and optimization process
- **Rollback Strategy:** Quick rollback capability for failed deployments

### Backup & Recovery
- **Database Backups:** Daily automated backups with 30-day retention
- **File Backups:** Weekly full backups, daily incremental
- **Backup Testing:** Monthly backup restoration testing
- **Disaster Recovery:** RTO: 4 hours, RPO: 1 hour
- **Geographic Redundancy:** Off-site backup storage

### Monitoring & Maintenance
- **Uptime Monitoring:** 99.9% uptime SLA
- **Performance Monitoring:** APM tool integration
- **Security Monitoring:** Intrusion detection and prevention
- **Log Management:** Centralized logging with retention policies
- **Update Schedule:** Monthly security updates, quarterly feature updates