# NCS Billing System Update Manager

## Overview

The NCS Billing System Update Manager provides a comprehensive solution for updating existing installations without affecting user data or configuration. It supports both file updates and database schema migrations.

## Features

### 1. Safe File Updates
- **Backup Creation**: Automatically creates backups of existing files before updating
- **Selective Updates**: Only updates system files, preserving user customizations
- **Rollback Support**: Maintains backup files for potential rollback scenarios

### 2. Database Schema Updates
- **SQL File Execution**: Runs the complete `billing.sql` file to add new tables and data
- **Smart Execution**: Handles existing tables gracefully without data loss
- **Safe Updates**: Only adds new tables/columns without modifying existing data

### 3. Configuration Preservation
- **Database Config**: Preserves existing database connection settings
- **User Settings**: Maintains all user-configured settings
- **Custom Files**: Preserves user-uploaded files and customizations

## File Structure

```
setup/update/
├── index.php              # Main update interface
├── update.php             # Update system core logic
├── taskCoreClass.php      # Core update functions
├── test_update.php        # Test script
├── cleanup_backups.php    # Backup cleanup utility
├── includes/
│   ├── databaseLibrary.php
│   ├── config_file.php
│   └── templatevthree.php
└── README.md              # This documentation

setup/install/
└── billing.sql            # Complete database schema file

application/controllers/
└── Update_manager.php     # Admin panel update controller

application/views/
└── update_manager.php     # Admin panel update interface
```

## Usage

### Method 1: Web Interface (Recommended)

1. **Access Update Interface**:
   - Navigate to `http://yourdomain.com/setup/update/`
   - Enter your database credentials
   - The system will automatically check for available updates

2. **Update Process**:
   - Review the current and target versions
   - Select update options (backup, database update, config preservation)
   - Click "Update System" to begin the process
   - Monitor the progress and review the update log

### Method 2: Admin Panel

1. **Access Admin Panel**:
   - Login to your admin panel
   - Navigate to `http://yourdomain.com/update_manager`
   - Use the built-in update manager interface

2. **Update Options**:
   - Check for updates
   - Configure update settings
   - Monitor update progress
   - View detailed update logs

## Update Options

### Backup Options
- **Create Backup**: Automatically creates timestamped backups
- **Backup Location**: `backups/YYYY-MM-DD_HH-MM-SS/`
- **Backup Contents**: Controllers, models, views, helpers, libraries, themes

### Database Options
- **Update Schema**: Applies pending database migrations
- **Add New Tables**: Creates new tables defined in migration files
- **Preserve Data**: Never modifies existing data, only adds new structures

### Configuration Options
- **Preserve Config**: Maintains existing configuration files
- **Database Settings**: Keeps current database connection settings
- **User Settings**: Preserves all user-configured options

## Database Update System

### How It Works

The update system uses the `billing.sql` file to add new tables and data to existing databases. This approach ensures:

1. **Complete Schema**: All new tables and data are included in one file
2. **Safe Execution**: Handles existing tables gracefully without data loss
3. **Consistent Updates**: All installations get the same database structure

### Adding New Tables

1. **Update billing.sql**: Add new table definitions to the SQL file
2. **Test Locally**: Test the SQL file on a development database
3. **Deploy**: The update system will automatically execute the new SQL

### Example SQL Addition

```sql
-- Add this to billing.sql for new tables
CREATE TABLE IF NOT EXISTS `db_new_feature` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(100) NOT NULL,
    `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Add sample data
INSERT INTO `db_new_feature` (`name`) VALUES 
('Sample Feature 1'),
('Sample Feature 2');
```

### Best Practices

1. **Use IF NOT EXISTS**: Always use `CREATE TABLE IF NOT EXISTS` to avoid errors
2. **Test Thoroughly**: Test SQL on development database first
3. **Backup First**: Always backup before running updates
4. **Document Changes**: Include comments explaining new features
5. **Version Control**: Keep billing.sql in version control

## Safety Features

### Data Protection
- **No Data Loss**: Updates never modify existing data
- **Backup Creation**: Automatic backups before any changes
- **Transaction Support**: Database changes are wrapped in transactions
- **Rollback Capability**: Failed updates can be rolled back

### Error Handling
- **Validation**: Validates database connections before proceeding
- **Error Logging**: Comprehensive error logging for troubleshooting
- **Graceful Failure**: Updates fail gracefully without corrupting the system
- **Status Reporting**: Clear status messages throughout the process

## Troubleshooting

### Common Issues

1. **Database Connection Failed**:
   - Verify database credentials
   - Check database server status
   - Ensure database exists

2. **Permission Errors**:
   - Check file permissions (755 for directories, 644 for files)
   - Ensure web server has write access to application directory
   - Verify backup directory is writable

3. **Migration Failures**:
   - Check migration file syntax
   - Verify database user has ALTER/CREATE permissions
   - Review error logs for specific issues

### Log Files

- **Update Logs**: `application/logs/log-YYYY-MM-DD.php`
- **Error Logs**: `application/logs/`
- **Backup Logs**: Included in backup directory

### Recovery Procedures

1. **Restore from Backup**:
   - Copy files from `backups/YYYY-MM-DD_HH-MM-SS/`
   - Restore database from backup if needed
   - Update version number in database

2. **Manual Rollback**:
   - Run migration down methods manually
   - Restore configuration files
   - Update version number

## Security Considerations

### Access Control
- **Restrict Access**: Limit access to update interface
- **Authentication**: Require admin authentication for updates
- **IP Restrictions**: Consider IP-based access restrictions

### File Permissions
- **Minimal Permissions**: Use least privilege principle
- **Secure Backups**: Store backups in secure locations
- **Cleanup**: Remove old backup files regularly

## Maintenance

### Regular Tasks
1. **Clean Old Backups**: Remove backups older than 30 days
2. **Monitor Logs**: Review update logs for issues
3. **Test Updates**: Test updates in staging environment first
4. **Document Changes**: Keep track of all updates applied

### Best Practices
1. **Always Backup**: Create manual backups before major updates
2. **Test First**: Test updates in development environment
3. **Monitor System**: Watch system performance after updates
4. **Keep Updated**: Apply updates regularly to maintain security

## Support

For technical support or questions about the update system:
- **Email**: admin@nanzige.com
- **Documentation**: Check this README file
- **Logs**: Review system logs for error details

## Version History

- **v3.3**: Initial release with comprehensive update system
- **v3.2**: Basic update functionality
- **v3.1**: Migration system implementation
- **v3.0**: Core system foundation
