# KSO Chandigarh Admin Panel - Copilot Instructions

This document provides guidance for AI agents working with the KSO (Kashmiri Students Organization) Chandigarh admin portal codebase.

## System Architecture

### Stack Overview
- **Frontend**: AdminLTE 3.2 template (Bootstrap-based), jQuery, Chart.js, DataTables
- **Backend**: PHP (non-framework), MySQL database
- **Authentication**: Session-based with remember-me functionality
- **Development**: XAMPP/local PHP server for development
- **Enhanced Features**: Dark Mode, Toast Notifications, Preloader System
- **Document Management**: PDF generation (TCPDF), ID card system, Receipt/Invoice system
- **Email System**: Templated email service with queue management

### Key Components

1. **API Layer** (`adminlte/api/*.php`):
   - RESTful endpoints providing data to frontend components
   - Core endpoints: `fetch_dashboard_stats.php`, `datatable.php`, `fetch_events.php`, `fetch_transactions.php`
   - Example pattern: `api/datatable.php?table=members&recent=true`
   - Error handling with consistent JSON response format
   - Specialized modules:
     - `api/documents/` - Document upload, download, and management
     - `api/receipts/` - PDF receipt generation with TCPDF
     - `api/id-cards/` - Member ID card creation and printing
     - `api/email/` - Email templating and sending

2. **Database Layer** (`adminlte/config/database.php`):
   - `Database` class manages PDO connections
   - `safelyQueryTable()` function with default empty values for resilience
   - MariaDB/MySQL compatibility fixes for queries
   - Table existence checks before operations

3. **Authentication** (`adminlte/config/auth_enhanced.php`):
   - Functions: `isAuthenticated()`, `requireAdmin()`, `checkAuthentication()`
   - Session-based with optional remember-me tokens
   - Role-based access control (Level 4-9 admin roles)

4. **UI Components** (`adminlte/index.php`):
   - Data visualization: Stats cards, DataTables, Charts
   - Empty state handling: Custom messages when tables have no data
   - Modular template system with header, navbar, sidebar, footer
   - Dark mode and theme manager

5. **Service Layer** (`adminlte/services/`):
   - `EmailService.php` - Handles email composition, templating, and delivery
   - Integration with SMTP settings and queue management

## Important Patterns

### Empty State Handling Pattern
The system implements a consistent pattern for handling empty database tables:

```php
// Backend (fetch_dashboard_stats.php)
function getDefaultEmptyValues($tableName) {
    switch ($tableName) {
        case 'members':
            return [
                'total_members' => 0,
                'active_members' => 0,
                // ...
            ];
        // Other cases...
    }
}

// Frontend (index.php)
function setNoDataValues() {
    $('#totalMembers').html('0 <small class="text-muted">members</small>');
    // ...
}
```

### DataTable Initialization Pattern
Tables use this pattern for setup with empty state handling:

```javascript
const membersTable = $('#membersTable').DataTable({
    ajax: {
        url: 'api/datatable.php?table=members&recent=true',
        dataSrc: function(json) {
            if (json.success && json.data && json.data.length > 0) {
                return json.data;
            } else {
                $('#membersTableContainer').html(
                    '<div class="alert alert-info m-3">' +
                    '<i class="fas fa-info-circle mr-2"></i> No members found...' +
                    '</div>'
                );
                return [];
            }
        }
    },
    // Column definitions and options...
});
```

## Development Workflow

### Running the Project
1. Start PHP development server:
   ```
   cd public_html
   php -S localhost:8000
   ```
2. Access admin panel: http://localhost:8000/adminlte/
3. Default login: admin@kso.org / password

### Database Setup
- Schema file: `adminlte/database/all_in_one_schema.sql`
- Connection settings in `adminlte/config/database.php`
- Tables: members, events, transactions, documents, id_cards, member_photos, etc.
- Use `safelyQueryTable()` for resilient database operations

### Debugging Tips
- PHP error logging enabled in `config/database.php`
- Check browser console for AJAX errors
- Use `error_log()` for server-side debugging
- Empty states are handled via container divs with IDs like `membersTableContainer`
- Dark mode issues can be debugged with `window.themeManager` in console

## Enhanced UI Features

### 1. Dark Mode
The system supports a full dark mode theme:
```javascript
// Toggle dark mode
window.themeManager.setTheme('dark'); // or 'light'

// Theme change event listener
window.addEventListener('themeChanged', (event) => {
    console.log('Theme changed to:', event.detail.theme);
});
```

### 2. Toast Notifications
Use the toast system for user feedback:
```javascript
// Show success notification
showToast('Operation completed successfully', 'success');

// Other types: error, warning, info
showToast('Something went wrong', 'error');
```

### 3. Preloader System
Manage loading states with the preloader:
```javascript
// Show loading screen
window.ksoPreloader.show();

// Update progress
window.ksoPreloader.updateProgress(50, 'Loading data...');

// Hide when complete
window.ksoPreloader.hide();
```

## Document Management System

### 1. Receipt/Invoice Generation
The system generates professional receipts and invoices using TCPDF:

```php
// Create receipt PDF (api/receipts/PDFGenerator.php)
$pdf = new ReceiptPDFGenerator();
$pdf->setReceiptData($receiptData);
$pdf->generate();
$pdf->Output('KSO_Receipt_' . $receiptNumber . '.pdf', 'D');
```

### 2. ID Card System
Member ID cards are generated and managed via dedicated endpoints:

```php
// Generate ID card (api/id-cards/generate.php)
$idCardGenerator = new IDCardGenerator($memberId);
$idCardGenerator->setTemplate('standard');
$idCardGenerator->includeLogo(true);
$idCardGenerator->setExpiryDate('+1 year');
$cardId = $idCardGenerator->generate();
```

### 3. Document Storage
Document upload and management follows this pattern:

```php
// Upload document (api/documents/upload.php)
$documentManager = new DocumentManager();
$documentManager->setMember($memberId);
$documentManager->setType('certificate');
$documentManager->setVisibility('admin_only');
$documentId = $documentManager->upload($_FILES['document']);
```

## Project Conventions

### API Response Format
All API endpoints return JSON with this structure:
```json
{
  "success": true,
  "data": { ... },
  "message": "Optional message"
}
```

### Table Container Pattern
HTML tables use this convention:
```html
<div id="[table]TableContainer" class="table-responsive">
    <table id="[table]Table" class="table table-striped table-hover">
        <!-- Content -->
    </table>
</div>
```

### JavaScript Update Pattern
Stats are updated with the `updateStatDisplay()` helper:
```javascript
updateStatDisplay('totalMembers', stats.member_stats.total_members, 'members');
```

## Database Compatibility Notes

### MariaDB/MySQL Compatibility
The system includes fixes for cross-compatibility between MariaDB and MySQL:

1. **Index Naming Convention**:
   - Use unique prefixes: `uk_` for unique keys, `idx_` for indexes
   - Example: `uk_receipt_number` instead of generic `receipt_number`

2. **Function-Based Indexes Not Supported**:
   - Avoid: `CREATE INDEX idx_year ON table (YEAR(created_at))`
   - Use: `CREATE INDEX idx_date ON table (created_at)` instead

3. **Date Functions Syntax**:
   - Use singular units: `INTERVAL 2 HOUR` not `INTERVAL 2 HOURS`
   - Example: `DATE_SUB(NOW(), INTERVAL 30 DAY)`

4. **Schema Compatibility Check**:
   ```php
   // Use this pattern for safe table operations
   $stmt = $conn->prepare("SHOW TABLES LIKE 'tablename'");
   $stmt->execute();
   $tableExists = $stmt->rowCount() > 0;
   
   if ($tableExists) {
       // Perform operations on existing table
   }
   ```

## Database Schema Structure

### Core Tables
1. **members**: 
   - Primary user accounts (id, kso_id, first_name, last_name, email, etc.)
   - Contains approval_status and membership fields
   - Enhanced with photo_id (linking to member_photos), is_online, last_activity_at
   
2. **events**:
   - Event details (id, event_title, event_date, event_location, etc.)
   - Status tracking (upcoming, ongoing, completed)
   
3. **transactions/finance**:
   - Financial records (id, amount, transaction_type, payment_date, etc.)
   - Links to members for membership fees

### Supporting Systems
1. **Photo System**:
   - member_photos: Stores photo data with processing states
   - photo_upload_sessions: Handles chunked uploads
   - member_online_status: Tracks real-time activity
   
2. **Document System**:
   - documents: Stores uploaded files with metadata
   - document_categories: Classifies documents
   
3. **ID Card System**:
   - id_cards: Tracks issued cards with expiry dates
   - card_templates: Defines available card designs

4. **Receipt/Invoice System**:
   - receipts: Records of payments with member associations
   - invoices: Payment requests with status tracking
   - receipt_templates: Defines layout templates

### Email System Tables
1. **email_logs**: Tracks all sent emails
2. **email_templates**: Stores reusable email templates
3. **notification_settings**: Per-user email preferences

## Integration Points
- AdminLTE 3.2 template integration (Bootstrap 4)
- Chart.js for data visualization
- DataTables for enhanced tables
- PDO for database access
- TCPDF for PDF generation
