<?php

namespace PortalPeople\NgaugeBackupSql\components;

use Yii;

/**
 * Backup Static Facade
 * 
 * Provides static methods for easy backup/restore access from anywhere in the application.
 * 
 * Usage:
 * ```php
 * use PortalPeople\NgaugeBackupSql\components\Backup;
 * 
 * // Create backup
 * $file = Backup::SQLTable('pricing');
 * $file = Backup::SQLTable('pricing', 'pricing-ADP.zip');
 * 
 * // List restore points
 * $points = Backup::listRestorePoints('pricing');
 * 
 * // Restore
 * Backup::restore('pricing_20260210_1430.sql.gz');
 * ```
 */
class Backup
{
    /**
     * @var BackupManager Cached manager instance
     */
    private static $_manager;

    /**
     * Get or create BackupManager instance
     * 
     * @return BackupManager
     */
    protected static function getManager()
    {
        if (self::$_manager === null) {
            self::$_manager = Yii::createObject(BackupManager::class);
        }
        
        return self::$_manager;
    }

    /**
     * Create a backup of a SQL table
     * 
     * @param string $tableName Name of the table to backup
     * @param string|null $filename Custom filename (e.g., 'pricing-ADP.zip')
     * @return string Path to the created backup file
     * 
     * @throws \yii\base\Exception If backup fails
     */
    public static function SQLTable($tableName, $filename = null)
    {
        return self::getManager()->createBackup($tableName, $filename);
    }

    /**
     * List available restore points for a table
     * 
     * @param string|null $tablePrefix Filter by table name prefix (null = all backups)
     * @return array List of backup files with metadata
     */
    public static function listRestorePoints($tablePrefix = null)
    {
        return self::getManager()->listRestorePoints($tablePrefix);
    }

    /**
     * Restore database from a backup file
     * 
     * @param string $filename Backup filename (basename only)
     * @return bool Success status
     * 
     * @throws \yii\base\Exception If restore fails
     */
    public static function restore($filename)
    {
        return self::getManager()->restore($filename);
    }

    /**
     * Get list of all tables in the database
     * 
     * @param bool $excludeSystemTables Whether to exclude configured tables
     * @return array List of table names
     */
    public static function listTables($excludeSystemTables = true)
    {
        return self::getManager()->listTables($excludeSystemTables);
    }

    /**
     * Delete old backups based on retention policy
     * 
     * @param int|null $days Override retention days (null = use module setting)
     * @return int Number of files deleted
     */
    public static function cleanup($days = null)
    {
        return self::getManager()->cleanupOldBackups($days);
    }
}
