<?php
require_once __DIR__ . '/../base_api.php';

class BackupAPI extends BaseAPI {
    public function getBackups() {
        $this->debug_log('BackupAPI: getBackups called.');
        
        $webid = $this->getWebId();
        $all_backups = array();
        
        $site_result = $this->bt_api->GetBackupList(0, $webid);
        $this->debug_log('BackupAPI: Site backup result: ' . print_r($site_result, true));

        if (isset($site_result['status']) && $site_result['status'] === false) {
            $this->error('获取备份列表失败：' . (isset($site_result['msg']) ? $site_result['msg'] : '无法连接宝塔面板'));
        }

        if (isset($site_result['data']) && is_array($site_result['data'])) {
            foreach ($site_result['data'] as $item) {
                $all_backups[] = $this->mapBackupItem($item, 0);
            }
        }

        $db_id = $this->getUserDbId();
        if ($db_id) {
            $db_result = $this->bt_api->GetBackupList(1, $db_id);
            if (isset($db_result['data']) && is_array($db_result['data'])) {
                foreach ($db_result['data'] as $item) {
                    $all_backups[] = $this->mapBackupItem($item, 1);
                }
            }
        }

        usort($all_backups, function($a, $b) {
            $t1 = isset($b['create_time']) ? $b['create_time'] : '0';
            $t2 = isset($a['create_time']) ? $a['create_time'] : '0';
            return strtotime($t1) - strtotime($t2);
        });
        
        $this->success(array('backups' => $all_backups));
    }

    private function mapBackupItem($item, $type) {
        $status = 'success';
        if (isset($item['backup_status']) && $item['backup_status'] == 1) {
            $status = 'pending';
        } elseif (isset($item['localexist']) && $item['localexist'] == 0) {
            $status = 'failed';
        }
        return array(
            'id' => isset($item['id']) ? $item['id'] : 0,
            'backup_name' => isset($item['name']) ? $item['name'] : '-',
            'backup_type' => $type == 0 ? 'files' : 'database',
            'backup_size' => isset($item['size']) ? intval($item['size']) : 0,
            'create_time' => isset($item['addtime']) ? $item['addtime'] : '-',
            'complete_time' => $status == 'success' ? (isset($item['addtime']) ? $item['addtime'] : '-') : '-',
            'status' => $status,
            'error_message' => isset($item['ps']) && strpos($item['ps'], '不存在') !== false ? $item['ps'] : '',
            'filename' => isset($item['filename']) ? $item['filename'] : ''
        );
    }

    private function getUserDbId() {
        $username = isset($this->user['user']) ? $this->user['user'] : (isset($this->user->user) ? $this->user->user : null);
        if (!$username) return null;
        $db_name = isset($this->user['sqldb']) ? $this->user['sqldb'] : (isset($this->user->sqldb) ? $this->user->sqldb : $username);
        if (!$db_name) return null;
        $url = $this->bt_api->BT_PANEL . '/data?action=getData';
        $p_data = $this->bt_api->GetKeyData();
        $p_data['table'] = 'databases';
        $p_data['search'] = $db_name;
        $p_data['limit'] = 10;
        $p_data['p'] = 1;
        $result = $this->bt_api->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        if (isset($data['data']) && is_array($data['data'])) {
            foreach ($data['data'] as $row) {
                if (isset($row['name']) && $row['name'] === $db_name && isset($row['id'])) {
                    return $row['id'];
                }
            }
            if (isset($data['data'][0]['id'])) return $data['data'][0]['id'];
        }
        return null;
    }

    public function createBackup() {
        $backup_name = isset($_POST['backup_name']) ? trim($_POST['backup_name']) : '';
        $backup_type = isset($_POST['backup_type']) ? $_POST['backup_type'] : 'full';
        if (empty($backup_name)) {
            $backup_name = date('Y-m-d_H-i-s') . '_' . ($backup_type == 'database' ? '数据库备份' : '文件备份');
        }
        $webid = $this->getWebId();
        if ($backup_type == 'database') {
            $db_id = $this->getUserDbId();
            if (!$db_id) $this->error('未找到您的数据库');
            $result = $this->bt_api->ToBackupDatabase($db_id);
        } else {
            $result = $this->bt_api->ToBackupSite($webid);
        }
        if (isset($result['status']) && $result['status'] === false) {
            $this->error(isset($result['msg']) ? $result['msg'] : '创建备份失败');
        }
        $this->success(array('msg' => isset($result['msg']) ? $result['msg'] : '备份任务已提交'));
    }

    public function downloadBackup($id) {
        $webid = $this->getWebId();
        $filename = '';
        $result = $this->bt_api->GetBackupList(0, $webid);
        if (isset($result['data'])) {
            foreach ($result['data'] as $item) {
                if (isset($item['id']) && $item['id'] == $id && isset($item['filename'])) {
                    $filename = $item['filename'];
                    break;
                }
            }
        }
        if (empty($filename) && ($db_id = $this->getUserDbId())) {
            $db_result = $this->bt_api->GetBackupList(1, $db_id);
            if (isset($db_result['data'])) {
                foreach ($db_result['data'] as $item) {
                    if (isset($item['id']) && $item['id'] == $id && isset($item['filename'])) {
                        $filename = $item['filename'];
                        break;
                    }
                }
            }
        }
        if (empty($filename)) $this->error('备份文件不存在或无权访问');
        $protocol = isset($this->bt_info['aqfw']) && $this->bt_info['aqfw'] == 'true' ? 'https' : 'http';
        $url = $protocol . '://' . $this->bt_info['ip'] . ':' . $this->bt_info['dk'] . '/download?filename=' . urlencode($filename);
        header('Location: ' . $url);
        exit;
    }

    public function deleteBackup($id) {
        $webid = $this->getWebId();
        $backup_type = 0;
        $found = false;
        $result = $this->bt_api->GetBackupList(0, $webid);
        if (isset($result['data'])) {
            foreach ($result['data'] as $item) {
                if (isset($item['id']) && $item['id'] == $id) { $found = true; break; }
            }
        }
        if (!$found && ($db_id = $this->getUserDbId())) {
            $db_result = $this->bt_api->GetBackupList(1, $db_id);
            if (isset($db_result['data'])) {
                foreach ($db_result['data'] as $item) {
                    if (isset($item['id']) && $item['id'] == $id) { $found = true; $backup_type = 1; break; }
                }
            }
        }
        if (!$found) $this->error('备份不存在或无权操作');
        $result = $this->bt_api->DelBackupById($id, $backup_type);
        if (isset($result['status']) && $result['status'] === false) {
            $this->error(isset($result['msg']) ? $result['msg'] : '删除失败');
        }
        $this->success(array('msg' => '删除成功'));
    }

    public function restoreBackup($id) {
        $id = intval($id);
        if ($id <= 0) {
            $this->error('参数错误');
        }

        $this->debug_log('BackupAPI: restoreBackup id=' . $id);

        $webid = $this->getWebId();

        $site_file = '';
        $site_result = $this->bt_api->GetBackupList(0, $webid);
        if (isset($site_result['data']) && is_array($site_result['data'])) {
            foreach ($site_result['data'] as $item) {
                if (isset($item['id']) && intval($item['id']) === $id) {
                    $site_file = isset($item['filename']) ? $item['filename'] : '';
                    break;
                }
            }
        }

        if (!empty($site_file)) {
            $this->debug_log('BackupAPI: restoreBackup detected site backup, file=' . $site_file);
            $result = $this->bt_api->Restore($site_file);
            $this->debug_log('BackupAPI: restoreBackup site result=' . print_r($result, true));
            if (isset($result['status']) && $result['status'] === false) {
                $this->error(isset($result['msg']) ? $result['msg'] : '恢复失败');
            }
            $this->success(array('msg' => isset($result['msg']) ? $result['msg'] : '恢复任务已提交'));
        }

        $db_id = $this->getUserDbId();
        if (!$db_id) {
            $this->error('未找到您的数据库');
        }

        $db_name = isset($this->user['sqldb']) ? $this->user['sqldb'] : (isset($this->user->sqldb) ? $this->user->sqldb : '');
        if (!$db_name) {
            $db_name = isset($this->user['user']) ? $this->user['user'] : (isset($this->user->user) ? $this->user->user : '');
        }

        $db_file = '';
        $db_result = $this->bt_api->GetBackupList(1, $db_id);
        if (isset($db_result['data']) && is_array($db_result['data'])) {
            foreach ($db_result['data'] as $item) {
                if (isset($item['id']) && intval($item['id']) === $id) {
                    $db_file = isset($item['filename']) ? $item['filename'] : '';
                    break;
                }
            }
        }

        if (empty($db_file)) {
            $this->error('备份不存在或无权恢复');
        }

        $this->debug_log('BackupAPI: restoreBackup detected db backup, db_id=' . $db_id . ', name=' . $db_name . ', file=' . $db_file);
        $result = $this->bt_api->InputSql($db_id, $db_file, $db_name);
        $this->debug_log('BackupAPI: restoreBackup db result=' . print_r($result, true));
        if (isset($result['status']) && $result['status'] === false) {
            $this->error(isset($result['msg']) ? $result['msg'] : '数据库导入失败');
        }

        $this->success(array('msg' => isset($result['msg']) ? $result['msg'] : '数据库导入任务已提交'));
    }
}
?>
