<?php
// Auto Backup Function
// This file will be called after saving data

function createAutoBackup() {
    $backupDir = 'backup_data';

    // Ensure backup directory exists
    if (!file_exists($backupDir)) {
        @mkdir($backupDir, 0777, true);
    }

    // Create backup filename with timestamp
    $backupFile = $backupDir . '/backup_' . date('Y-m-d_H-i-s') . '.zip';

    // Prevent duplicate backup in same second
    if (file_exists($backupFile)) {
        usleep(100000); // Wait 0.1 second
        $backupFile = $backupDir . '/backup_' . date('Y-m-d_H-i-s') . '_' . uniqid() . '.zip';
    }

    // Create zip file
    $zip = new ZipArchive();

    if ($zip->open($backupFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
        // Add transactions.json
        if (file_exists('data/transactions.json')) {
            $zip->addFile('data/transactions.json', 'transactions.json');
        }

        // Add reminders.json
        if (file_exists('data/reminders.json')) {
            $zip->addFile('data/reminders.json', 'reminders.json');
        }

        $zip->close();

        // Clear cache
        clearstatcache();

        return true;
    }

    return false;
}
?>
