<?php

namespace PortalPeople\NgaugeBackupSql\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use PortalPeople\NgaugeBackupSql\components\BackupManager;
use PortalPeople\NgaugeBackupSql\models\BackupHistory;

/**
 * Default Controller for Backup Module
 * 
 * Provides web interface for database backup and restore operations.
 */
class DefaultController extends Controller
{
    /**
     * @var BackupManager
     */
    private $_manager;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'], // Only authenticated users
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'create-backup' => ['post'],
                    'restore' => ['post'],
                    'delete' => ['post'],
                    'download' => ['get'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $this->_manager = Yii::createObject(BackupManager::class);
    }

    /**
     * Index page - displays backup management interface
     * 
     * @return string
     */
    public function actionIndex()
    {
        $tables = $this->_manager->listTables();
        $restorePoints = $this->_manager->listRestorePoints();
        $statistics = BackupHistory::getStatistics();
        
        return $this->render('index', [
            'tables' => $tables,
            'restorePoints' => $restorePoints,
            'statistics' => $statistics,
        ]);
    }

    /**
     * Create backup via AJAX
     * 
     * @return array JSON response
     */
    public function actionCreateBackup()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        $tables = Yii::$app->request->post('tables', []);
        $compress = Yii::$app->request->post('compress', true);
        
        if (empty($tables)) {
            return [
                'success' => false,
                'message' => 'No tables selected.',
            ];
        }
        
        $results = [];
        $successCount = 0;
        $failedCount = 0;
        
        foreach ($tables as $table) {
            try {
                $backupFile = $this->_manager->createBackup($table, null, $compress);
                $results[] = [
                    'table' => $table,
                    'success' => true,
                    'filename' => basename($backupFile),
                    'size' => filesize($backupFile),
                ];
                $successCount++;
                
            } catch (\Exception $e) {
                $results[] = [
                    'table' => $table,
                    'success' => false,
                    'error' => $e->getMessage(),
                ];
                $failedCount++;
            }
        }
        
        return [
            'success' => true,
            'message' => "Backup completed: {$successCount} successful, {$failedCount} failed.",
            'results' => $results,
            'successCount' => $successCount,
            'failedCount' => $failedCount,
        ];
    }

    /**
     * List restore points for a specific table via AJAX
     * 
     * @return array JSON response
     */
    public function actionListRestorePoints()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        $table = Yii::$app->request->get('table');
        $restorePoints = $this->_manager->listRestorePoints($table);
        
        return [
            'success' => true,
            'restorePoints' => $restorePoints,
        ];
    }

    /**
     * Restore from backup via AJAX
     * 
     * @return array JSON response
     */
    public function actionRestore()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        $filename = Yii::$app->request->post('filename');
        
        if (empty($filename)) {
            return [
                'success' => false,
                'message' => 'Backup filename is required.',
            ];
        }
        
        try {
            $this->_manager->restore($filename);
            
            return [
                'success' => true,
                'message' => 'Database restored successfully from: ' . $filename,
            ];
            
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Restore failed: ' . $e->getMessage(),
            ];
        }
    }

    /**
     * Download backup file
     * 
     * @param string $filename Backup filename
     * @return Response
     * @throws NotFoundHttpException
     */
    public function actionDownload($filename)
    {
        $backupPath = $this->module->getBackupPath();
        $filePath = $backupPath . DIRECTORY_SEPARATOR . $filename;
        
        if (!file_exists($filePath)) {
            throw new NotFoundHttpException('Backup file not found.');
        }
        
        return Yii::$app->response->sendFile($filePath);
    }

    /**
     * Delete backup file via AJAX
     * 
     * @return array JSON response
     */
    public function actionDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        $filename = Yii::$app->request->post('filename');
        
        if (empty($filename)) {
            return [
                'success' => false,
                'message' => 'Backup filename is required.',
            ];
        }
        
        $backupPath = $this->module->getBackupPath();
        $filePath = $backupPath . DIRECTORY_SEPARATOR . $filename;
        
        if (!file_exists($filePath)) {
            return [
                'success' => false,
                'message' => 'Backup file not found.',
            ];
        }
        
        if (@unlink($filePath)) {
            return [
                'success' => true,
                'message' => 'Backup file deleted successfully.',
            ];
        } else {
            return [
                'success' => false,
                'message' => 'Failed to delete backup file.',
            ];
        }
    }

    /**
     * View backup history
     * 
     * @return string
     */
    public function actionHistory()
    {
        $table = Yii::$app->request->get('table');
        $history = BackupHistory::getRecent($table, 100);
        
        return $this->render('history', [
            'history' => $history,
            'table' => $table,
        ]);
    }

    /**
     * Run cleanup
     * 
     * @return array JSON response
     */
    public function actionCleanup()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        try {
            $deleted = $this->_manager->cleanupOldBackups();
            
            return [
                'success' => true,
                'message' => $deleted > 0 
                    ? "Deleted {$deleted} old backup file(s)." 
                    : "No old backups to delete.",
                'deleted' => $deleted,
            ];
            
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Cleanup failed: ' . $e->getMessage(),
            ];
        }
    }
}
