<?php
// Check if user is authenticated
if (!defined('AUTH_USER')) {
    header('Location: login.php');
    exit();
}

require_once 'libs/BackupTarget.php';
require_once 'libs/BackupHistory.php';
require_once 'libs/BackupEngine.php';
require_once 'libs/BackupSchedule.php';

use WHPBackup\BackupTarget;
use WHPBackup\BackupHistory;
use WHPBackup\BackupEngine;
use WHPBackup\BackupSchedule;

$engine = new BackupEngine();
$targets = BackupTarget::listTargets(null, AUTH_USER);
$isRoot = AUTH_USER === 'root';

// Get user's sites and databases
if ($isRoot) {
    // Root can see all sites and databases
    $sites = [];
    $databases = [];
    // Get all users
    $allUsersList = [];
    $userDir = '/docker/users';
    if (is_dir($userDir)) {
        $directories = glob($userDir . '/*', GLOB_ONLYDIR);
        foreach ($directories as $dir) {
            $allUsersList[] = basename($dir);
        }
    }
    // Get sites for all users
    foreach ($allUsersList as $user) {
        $userSites = $engine->getUserSites($user);
        foreach ($userSites as $site) {
            $sites[] = $user . '/' . $site;
        }
    }
    // Get databases for all users
    foreach ($allUsersList as $user) {
        $userDatabases = $engine->getUserDatabases($user);
        foreach ($userDatabases as $database) {
            $databases[] = $database;
        }
    }
} else {
    // Regular users only see their own
    $sites = $engine->getUserSites(AUTH_USER);
    $databases = $engine->getUserDatabases(AUTH_USER);
}

// Get all users if root
$allUsers = [];
if ($isRoot) {
    $userDir = '/docker/users';
    if (is_dir($userDir)) {
        $directories = glob($userDir . '/*', GLOB_ONLYDIR);
        foreach ($directories as $dir) {
            $allUsers[] = basename($dir);
        }
    }
}

// Get schedules
$scheduleFilters = ['user' => AUTH_USER, 'limit' => 20];
if ($isRoot) {
    unset($scheduleFilters['user']); // Root can see all schedules
}
$schedules = BackupSchedule::listSchedules(null, $scheduleFilters);

// Get recent backups
$backupFilters = ['user' => AUTH_USER, 'exclude_deleted' => true, 'limit' => 20];
if ($isRoot) {
    unset($backupFilters['user']); // Root can see all backups
}
$recentBackups = BackupHistory::listBackups(null, $backupFilters);

// Get backup statistics
$completedFilters = $isRoot ? ['status' => 'completed'] : ['user' => AUTH_USER, 'status' => 'completed'];
$stats = [
    'total_backups' => BackupHistory::countBackups(null, $completedFilters),
    'total_size' => BackupHistory::getTotalSize(null, $isRoot ? [] : ['user' => AUTH_USER])
];
?>

<div class="container-fluid">

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5>Total Backups</h5>
                            <h3><?php echo number_format($stats['total_backups']); ?></h3>
                        </div>
                        <i class="fa fa-archive fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5>Total Size</h5>
                            <h3><?php echo formatBytes($stats['total_size']); ?></h3>
                        </div>
                        <i class="fa fa-hdd-o fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5>Sites</h5>
                            <h3><?php echo count($sites); ?></h3>
                        </div>
                        <i class="fa fa-globe fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5>Databases</h5>
                            <h3><?php echo count($databases); ?></h3>
                        </div>
                        <i class="fa fa-database fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Create Backup Section -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5><i class="fa fa-plus-circle"></i> Create New Backup</h5>
                </div>
                <div class="card-body">
                    <form id="backupForm">
                        <div class="row">
                            <?php if ($isRoot): ?>
                            <div class="col-md-3">
                                <label for="backupUser" class="form-label">User</label>
                                <select class="form-select" id="backupUser" required>
                                    <option value="">Select User</option>
                                    <?php foreach ($allUsers as $user): ?>
                                    <option value="<?php echo htmlspecialchars($user); ?>"><?php echo htmlspecialchars($user); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <?php endif; ?>
                            <div class="col-md-3">
                                <label for="backupType" class="form-label">Backup Type</label>
                                <select class="form-select" id="backupType" required>
                                    <option value="">Select Type</option>
                                    <option value="site">Site</option>
                                    <option value="userfiles">User Files</option>
                                    <option value="database">Database</option>
                                </select>
                            </div>
                            <div class="col-md-3" id="siteSelect" style="display: none;">
                                <label for="siteSelection" class="form-label">Select Site</label>
                                <select class="form-select" id="siteSelection">
                                    <option value="">Select Site</option>
                                    <option value="*">All Sites</option>
                                    <?php foreach ($sites as $site): ?>
                                    <option value="<?php echo htmlspecialchars($site); ?>"><?php echo htmlspecialchars($site); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3" id="dbSelect" style="display: none;">
                                <label for="dbSelection" class="form-label">Select Database</label>
                                <select class="form-select" id="dbSelection">
                                    <option value="">Select Database</option>
                                    <option value="*">All Databases</option>
                                    <?php foreach ($databases as $db): ?>
                                    <option value="<?php echo htmlspecialchars($db); ?>"><?php echo htmlspecialchars($db); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="targetSelection" class="form-label">Backup Target</label>
                                <select class="form-select" id="targetSelection" required>
                                    <option value="">Select Target</option>
                                    <?php foreach ($targets as $target): ?>
                                    <option value="<?php echo $target['id']; ?>">
                                        <?php echo htmlspecialchars($target['name']); ?>
                                        <?php if ($target['is_global']): ?>(Global)<?php endif; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-12 mt-3">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fa fa-play"></i> Start Backup
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Backup Targets Section -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fa fa-bullseye"></i> Backup Targets</h5>
                        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#targetModal" onclick="clearTargetForm()">
                            <i class="fa fa-plus"></i> Add Backup Target
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" data-whp-table data-whp-page-size="25">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Type</th>
                                    <th>Connection</th>
                                    <th>Retention</th>
                                    <th>Max Backups</th>
                                    <th>Global</th>
                                    <th data-whp-nosort>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($targets as $target): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($target['name']); ?></td>
                                    <td><span class="badge bg-secondary"><?php echo strtoupper($target['type']); ?></span></td>
                                    <td>
                                        <?php if ($target['type'] === 's3'): ?>
                                            <?php echo htmlspecialchars($target['endpoint']); ?> / <?php echo htmlspecialchars($target['bucket']); ?>
                                        <?php elseif ($target['type'] === 'ftp' || $target['type'] === 'sftp'): ?>
                                            <?php echo htmlspecialchars($target['host']); ?><?php if ($target['port']): ?>:<?php echo $target['port']; ?><?php endif; ?>
                                            <?php echo htmlspecialchars($target['remote_path'] ?? '/'); ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo $target['retention_days']; ?> days</td>
                                    <td><?php echo $target['max_backups']; ?></td>
                                    <td>
                                        <?php if ($target['is_global']): ?>
                                        <span class="badge bg-success">Yes</span>
                                        <?php else: ?>
                                        <span class="badge bg-secondary">No</span>
                                        <?php endif; ?>
                                        <?php if (!$target['is_global'] && $target['owner']): ?>
                                        <small class="text-muted d-block">(<?php echo htmlspecialchars($target['owner']); ?>)</small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <button class="btn btn-outline-primary" onclick="testTarget(<?php echo $target['id']; ?>)">
                                                <i class="fa fa-check"></i> Test
                                            </button>
                                            <?php if ($isRoot || $target['owner'] === AUTH_USER): ?>
                                            <button class="btn btn-outline-warning" onclick="editTarget(<?php echo $target['id']; ?>)">
                                                <i class="fa fa-edit"></i> Edit
                                            </button>
                                            <button class="btn btn-outline-danger" onclick="deleteTarget(<?php echo $target['id']; ?>)">
                                                <i class="fa fa-trash"></i> Delete
                                            </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scheduled Backups Section -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5><i class="fa fa-clock-o"></i> Scheduled Backups</h5>
                            <small class="text-muted">
                                <i class="fa fa-info-circle"></i> Next run times shown in your local timezone
                            </small>
                        </div>
                        <div>
                            <?php if ($isRoot): ?>
                            <button class="btn btn-outline-info btn-sm me-2" onclick="runSchedulerNow()">
                                <i class="fa fa-refresh"></i> Run Scheduler Now
                            </button>
                            <?php endif; ?>
                            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#scheduleModal" onclick="clearScheduleForm()">
                                <i class="fa fa-plus"></i> Add Schedule
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" data-whp-table data-whp-page-size="25">
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>Resource</th>
                                    <?php if ($isRoot): ?><th>User</th><?php endif; ?>
                                    <th>Target</th>
                                    <th>Schedule</th>
                                    <th>Next Run</th>
                                    <th>Status</th>
                                    <th data-whp-nosort>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($schedules as $schedule): ?>
                                <tr>
                                    <td>
                                        <span class="badge bg-<?php echo getBackupTypeColor($schedule['backup_type']); ?>">
                                            <?php echo ucfirst($schedule['backup_type']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo htmlspecialchars($schedule['resource_name'] ?? 'All'); ?></td>
                                    <?php if ($isRoot): ?>
                                    <td><?php echo htmlspecialchars($schedule['user']); ?></td>
                                    <?php endif; ?>
                                    <td><?php echo htmlspecialchars($schedule['target_name']); ?></td>
                                    <td>
                                        <?php 
                                        $scheduleText = ucfirst($schedule['schedule_type']);
                                        if ($schedule['schedule_type'] === 'weekly' && $schedule['schedule_day'] !== null) {
                                            $days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
                                            $scheduleText .= ' (' . $days[$schedule['schedule_day']] . ')';
                                        } elseif ($schedule['schedule_type'] === 'monthly' && $schedule['schedule_day'] !== null) {
                                            $scheduleText .= ' (' . $schedule['schedule_day'] . ')';
                                        }
                                        echo $scheduleText . ' at ' . date('H:i', strtotime($schedule['schedule_time']));
                                        ?>
                                    </td>
                                    <td>
                                        <?php if ($schedule['next_run_at']): ?>
                                            <?php echo whp_local_time($schedule['next_run_at'], 'Y-m-d H:i'); ?>
                                        <?php else: ?>
                                        N/A
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo $schedule['is_active'] ? 'success' : 'secondary'; ?>">
                                            <?php echo $schedule['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($isRoot || $schedule['user'] === AUTH_USER): ?>
                                        <div class="btn-group btn-group-sm">
                                            <button class="btn btn-outline-success" onclick="testSchedule(<?php echo $schedule['id']; ?>)">
                                                <i class="fa fa-play"></i> Test
                                            </button>
                                            <button class="btn btn-outline-warning" onclick="editSchedule(<?php echo $schedule['id']; ?>)">
                                                <i class="fa fa-edit"></i> Edit
                                            </button>
                                            <button class="btn btn-outline-danger" onclick="deleteSchedule(<?php echo $schedule['id']; ?>)">
                                                <i class="fa fa-trash"></i> Delete
                                            </button>
                                        </div>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- All Backups Section -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5><i class="fa fa-history"></i> All Backups</h5>
                        <small class="text-muted">
                            <i class="fa fa-clock-o"></i> Times shown in your local timezone
                        </small>
                    </div>
                </div>
                <div class="card-body">
                    <!-- Search and Filter Bar -->
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <input type="text" class="form-control" id="backupSearch" placeholder="Search backup name...">
                        </div>
                        <?php if ($isRoot): ?>
                        <div class="col-md-2">
                            <select class="form-select" id="backupUserFilter">
                                <option value="">All Users</option>
                                <?php foreach ($allUsers as $user): ?>
                                <option value="<?php echo htmlspecialchars($user); ?>"><?php echo htmlspecialchars($user); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php endif; ?>
                        <div class="col-md-2">
                            <select class="form-select" id="backupTypeFilter">
                                <option value="">All Types</option>
                                <option value="site">Site</option>
                                <option value="userfiles">User Files</option>
                                <option value="database">Database</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <select class="form-select" id="backupStatusFilter">
                                <option value="">All Status</option>
                                <option value="completed">Completed</option>
                                <option value="running">Running</option>
                                <option value="failed">Failed</option>
                                <option value="pending">Pending</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <select class="form-select" id="backupLimitFilter">
                                <option value="20">20 per page</option>
                                <option value="50" selected>50 per page</option>
                                <option value="100">100 per page</option>
                                <option value="200">200 per page</option>
                            </select>
                        </div>
                        <div class="col-md-1">
                            <button class="btn btn-primary w-100" onclick="loadBackups(1)">Search</button>
                        </div>
                    </div>
                    
                    <!-- Bulk Actions -->
                    <div class="row mb-3" id="bulkActions" style="display: none;">
                        <div class="col-12">
                            <div class="alert alert-light border">
                                <span id="selectedCount">0</span> backup(s) selected
                                <button class="btn btn-sm btn-outline-danger ms-3" onclick="deleteSelectedBackups()">
                                    <i class="fa fa-trash"></i> Delete Selected
                                </button>
                                <button class="btn btn-sm btn-outline-secondary ms-2" onclick="clearSelection()">
                                    Clear Selection
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Backup Table -->
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th style="width: 40px;">
                                        <input type="checkbox" id="selectAllBackups" onchange="toggleSelectAll()" title="Select all" aria-label="Select all backups">
                                    </th>
                                    <th style="min-width: 150px; max-width: 300px;">Name</th>
                                    <th>Type</th>
                                    <th>User</th>
                                    <th>Target</th>
                                    <th>Size</th>
                                    <th>Status</th>
                                    <th>Created</th>
                                    <th style="white-space: nowrap;">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="backupsList">
                                <!-- Will be populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Pagination -->
                    <div class="d-flex justify-content-between align-items-center mt-3">
                        <div id="backupInfo"></div>
                        <nav>
                            <ul class="pagination mb-0" id="backupPagination">
                                <!-- Will be populated by JavaScript -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Backup Target Modal -->
<div class="modal fade" id="targetModal" tabindex="-1" aria-labelledby="targetModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="targetModalLabel"><i class="fa fa-bullseye me-2"></i><span id="targetModalTitleText">Add Backup Target</span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="targetForm">
                <div class="modal-body">
                    <input type="hidden" id="targetId" name="targetId">
                    <div class="row">
                        <div class="col-md-6">
                            <label for="targetName" class="form-label">Name</label>
                            <input type="text" class="form-control" id="targetName" name="name" required>
                        </div>
                        <div class="col-md-6">
                            <label for="targetType" class="form-label">Type</label>
                            <select class="form-select" id="targetType" name="type" required>
                                <option value="s3">S3 Compatible</option>
                                <option value="ftp">FTP</option>
                                <option value="sftp">SFTP</option>
                            </select>
                        </div>
                    </div>
                    <!-- Connection Settings separator -->
                    <div class="row mt-3">
                        <div class="col-12">
                            <hr class="mt-0 mb-2">
                            <small class="text-muted fw-semibold text-uppercase" style="letter-spacing: 0.05em;">Connection Settings</small>
                        </div>
                    </div>
                    <!-- S3 Fields -->
                    <div id="s3Fields">
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <label for="targetEndpoint" class="form-label">Endpoint</label>
                                <input type="url" class="form-control" id="targetEndpoint" name="endpoint">
                            </div>
                            <div class="col-md-6">
                                <label for="targetBucket" class="form-label">Bucket</label>
                                <input type="text" class="form-control" id="targetBucket" name="bucket">
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <label for="targetAccessKey" class="form-label">Access Key</label>
                                <input type="text" class="form-control" id="targetAccessKey" name="access_key">
                            </div>
                            <div class="col-md-6">
                                <label for="targetSecretKey" class="form-label">Secret Key</label>
                                <input type="password" class="form-control" id="targetSecretKey" name="secret_key">
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <label for="targetRegion" class="form-label">Region</label>
                                <input type="text" class="form-control" id="targetRegion" name="region" value="us-east-1">
                            </div>
                        </div>
                    </div>
                    <!-- FTP/SFTP Fields -->
                    <div id="ftpFields" style="display: none;">
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <label for="targetHost" class="form-label">Host</label>
                                <input type="text" class="form-control" id="targetHost" name="host" placeholder="ftp.example.com">
                            </div>
                            <div class="col-md-3">
                                <label for="targetPort" class="form-label">Port</label>
                                <input type="number" class="form-control" id="targetPort" name="port" placeholder="21">
                                <small class="form-text text-muted">Default: 21 for FTP, 22 for SFTP</small>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <label for="targetUsername" class="form-label">Username</label>
                                <input type="text" class="form-control" id="targetUsername" name="username">
                            </div>
                            <div class="col-md-6">
                                <label for="targetPassword" class="form-label">Password</label>
                                <input type="password" class="form-control" id="targetPassword" name="password">
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <label for="targetRemotePath" class="form-label">Remote Path</label>
                                <input type="text" class="form-control" id="targetRemotePath" name="remote_path" value="/" placeholder="/backups">
                            </div>
                        </div>
                    </div>
                    <!-- Retention Settings separator -->
                    <div class="row mt-3">
                        <div class="col-12">
                            <hr class="mt-0 mb-2">
                            <small class="text-muted fw-semibold text-uppercase" style="letter-spacing: 0.05em;">Retention Settings</small>
                        </div>
                    </div>
                    <!-- Common Fields -->
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label for="targetPathPrefix" class="form-label">Path Prefix</label>
                            <input type="text" class="form-control" id="targetPathPrefix" name="path_prefix" placeholder="whp-backups">
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label for="targetRetention" class="form-label">Retention Days</label>
                            <input type="number" class="form-control" id="targetRetention" name="retention_days" value="30" min="1">
                        </div>
                        <div class="col-md-6">
                            <label for="targetMaxBackups" class="form-label">Max Backups <span id="maxBackupsHint"></span></label>
                            <input type="number" class="form-control" id="targetMaxBackups" name="max_backups" value="10" min="1">
                            <small class="form-text text-muted" id="maxBackupsHelp">Maximum backups to keep per backup type</small>
                        </div>
                    </div>
                    <?php if ($isRoot): ?>
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="targetGlobal" name="is_global">
                                <label class="form-check-label" for="targetGlobal">
                                    Global target (available to all users)
                                </label>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Target</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Schedule Modal -->
<div class="modal fade" id="scheduleModal" tabindex="-1" aria-labelledby="scheduleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="scheduleModalLabel"><i class="fa fa-clock-o me-2"></i><span id="scheduleModalTitleText">Add Backup Schedule</span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="scheduleForm">
                <div class="modal-body">
                    <input type="hidden" id="scheduleId" name="schedule_id">
                    <div class="row">
                        <?php if ($isRoot): ?>
                        <div class="col-md-6">
                            <label for="scheduleUser" class="form-label">User</label>
                            <select class="form-select" id="scheduleUser" name="schedule_user" required>
                                <option value="">Select User</option>
                                <?php foreach ($allUsers as $user): ?>
                                <option value="<?php echo htmlspecialchars($user); ?>"><?php echo htmlspecialchars($user); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php endif; ?>
                        <div class="col-md-6">
                            <label for="scheduleBackupType" class="form-label">Backup Type</label>
                            <select class="form-select" id="scheduleBackupType" name="backup_type" required>
                                <option value="">Select Type</option>
                                <option value="site">Site</option>
                                <option value="userfiles">User Files</option>
                                <option value="database">Database</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label for="scheduleResource" class="form-label">Resource Name</label>
                            <input type="text" class="form-control" id="scheduleResource" name="resource_name" placeholder="Leave blank to backup all">
                            <small class="form-text text-muted">For sites: domain name, for databases: database name. Leave blank to backup all sites/databases for the user.</small>
                        </div>
                        <div class="col-md-6">
                            <label for="scheduleTarget" class="form-label">Backup Target</label>
                            <select class="form-select" id="scheduleTarget" name="target_id" required>
                                <option value="">Select Target</option>
                                <?php foreach ($targets as $target): ?>
                                <option value="<?php echo $target['id']; ?>">
                                    <?php echo htmlspecialchars($target['name']); ?>
                                    <?php if ($target['is_global']): ?>(Global)<?php endif; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-4">
                            <label for="scheduleType" class="form-label">Schedule Type</label>
                            <select class="form-select" id="scheduleType" name="schedule_type" required>
                                <option value="">Select Type</option>
                                <option value="daily">Daily</option>
                                <option value="weekly">Weekly</option>
                                <option value="monthly">Monthly</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="scheduleTime" class="form-label">Time</label>
                            <input type="time" class="form-control" id="scheduleTime" name="schedule_time" value="02:00">
                        </div>
                        <div class="col-md-4" id="scheduleDayContainer" style="display: none;">
                            <label for="scheduleDay" class="form-label">Day</label>
                            <select class="form-select" id="scheduleDay" name="schedule_day">
                                <option value="">Select Day</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label for="scheduleRetention" class="form-label">Max Retention</label>
                            <input type="number" class="form-control" id="scheduleRetention" name="max_retention" value="30" min="1">
                            <small class="form-text text-muted">Maximum number of backups to keep</small>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" id="scheduleActive" name="is_active" checked>
                                <label class="form-check-label" for="scheduleActive">
                                    Active
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Schedule</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Define CSRF token for AJAX requests
const csrfToken = '<?php echo get_csrf_token(); ?>';

// Show/hide selection fields based on backup type
document.getElementById('backupType').addEventListener('change', function() {
    const siteSelect = document.getElementById('siteSelect');
    const dbSelect = document.getElementById('dbSelect');
    
    siteSelect.style.display = 'none';
    dbSelect.style.display = 'none';
    
    if (this.value === 'site') {
        siteSelect.style.display = 'block';
    } else if (this.value === 'database') {
        dbSelect.style.display = 'block';
    }
});

// Handle backup form submission
document.getElementById('backupForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData();
    formData.append('action', 'create_backup');
    formData.append('backup_type', document.getElementById('backupType').value);
    formData.append('target_id', document.getElementById('targetSelection').value);
    // CSRF token will be added via header
    
    <?php if ($isRoot): ?>
    if (document.getElementById('backupUser')) {
        formData.append('backup_user', document.getElementById('backupUser').value);
    }
    <?php endif; ?>
    
    if (document.getElementById('backupType').value === 'site') {
        formData.append('site', document.getElementById('siteSelection').value);
    } else if (document.getElementById('backupType').value === 'database') {
        formData.append('database', document.getElementById('dbSelection').value);
    }
    
    fetch('api/backup-actions.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': csrfToken
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('Backup started successfully!', 'success');
            setTimeout(() => location.reload(), 2000);
        } else {
            showAlert('Error: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('Error: ' + error.message, 'danger');
    });
});

// Handle target type switching
document.getElementById('targetType').addEventListener('change', function() {
    const type = this.value;
    const s3Fields = document.getElementById('s3Fields');
    const ftpFields = document.getElementById('ftpFields');

    if (type === 's3') {
        s3Fields.style.display = '';
        ftpFields.style.display = 'none';
        // Set required for S3 fields
        document.getElementById('targetEndpoint').required = true;
        document.getElementById('targetBucket').required = true;
        document.getElementById('targetAccessKey').required = true;
        document.getElementById('targetSecretKey').required = !document.getElementById('targetId').value; // Not required on edit
        // Remove required from FTP fields
        document.getElementById('targetHost').required = false;
        document.getElementById('targetUsername').required = false;
        document.getElementById('targetPassword').required = false;
    } else {
        s3Fields.style.display = 'none';
        ftpFields.style.display = '';
        // Set default port
        const portField = document.getElementById('targetPort');
        if (!portField.value) {
            portField.placeholder = type === 'ftp' ? '21' : '22';
        }
        // Set required for FTP/SFTP fields
        document.getElementById('targetHost').required = true;
        document.getElementById('targetUsername').required = true;
        document.getElementById('targetPassword').required = !document.getElementById('targetId').value;
        // Remove required from S3 fields
        document.getElementById('targetEndpoint').required = false;
        document.getElementById('targetBucket').required = false;
        document.getElementById('targetAccessKey').required = false;
        document.getElementById('targetSecretKey').required = false;
    }
});

// Trigger initial state
document.getElementById('targetType').dispatchEvent(new Event('change'));

// Handle target form submission
document.getElementById('targetForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', document.getElementById('targetId').value ? 'update_target' : 'create_target');
    // CSRF token will be added via header
    
    fetch('api/backup-actions.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': csrfToken
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('Target saved successfully!', 'success');
            bootstrap.Modal.getInstance(document.getElementById('targetModal')).hide();
            setTimeout(() => location.reload(), 1000);
        } else {
            showAlert('Error: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('Error: ' + error.message, 'danger');
    });
});

// Utility functions
function testTarget(targetId) {
    fetch('api/backup-actions.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRF-Token': csrfToken
        },
        body: `action=test_target&target_id=${targetId}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('Connection test successful!', 'success');
        } else {
            showAlert('Connection test failed: ' + data.message, 'danger');
        }
    });
}

function downloadBackup(backupId) {
    window.location.href = 'api/backup-actions.php?action=download&backup_id=' + backupId + '&csrf_token=<?php echo get_csrf_token(); ?>';
}

function deleteBackup(backupId) {
    deleteBackups([backupId]);
}

function retryBackup(backupId) {
    if (!confirm('Retry this failed backup?')) return;

    showAlert('Retrying backup...', 'info');

    fetch('api/backup-actions.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRF-Token': csrfToken
        },
        body: `action=retry_backup&backup_id=${backupId}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('Backup queued for retry!', 'success');
            loadBackups(currentPage);
        } else {
            showAlert(data.message || 'Failed to retry backup', 'danger');
        }
    })
    .catch(error => {
        showAlert('Error retrying backup: ' + error.message, 'danger');
    });
}

function deleteSelectedBackups() {
    const selectedCheckboxes = document.querySelectorAll('.backup-checkbox:checked');
    const backupIds = Array.from(selectedCheckboxes).map(cb => cb.value);
    
    if (backupIds.length === 0) {
        showAlert('Please select at least one backup to delete.', 'warning');
        return;
    }
    
    deleteBackups(backupIds);
}

function deleteBackups(backupIds) {
    const count = backupIds.length;
    const message = count === 1 ? 'Are you sure you want to delete this backup?' : `Are you sure you want to delete these ${count} backups?`;
    
    if (confirm(message)) {
        // Show loading state
        showAlert('Deleting backup(s)...', 'info');
        
        fetch('api/backup-actions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': csrfToken
            },
            body: `action=delete_backups&backup_ids=${backupIds.join(',')}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert(`${count === 1 ? 'Backup' : 'Backups'} deleted successfully!`, 'success');
                // Reload the current page without losing search/filter state
                loadBackups(currentPage);
                // Clear any selected checkboxes
                document.querySelectorAll('.backup-checkbox:checked').forEach(cb => cb.checked = false);
                updateBulkActionButtons();
            } else {
                showAlert('Error: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('Error deleting backup(s): ' + error.message, 'danger');
        });
    }
}

function editTarget(targetId) {
    // Fetch target details and populate the form
    fetch('api/backup-actions.php?action=get_target&target_id=' + targetId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const target = data.target;

                // Populate common form fields
                document.getElementById('targetId').value = target.id;
                document.getElementById('targetName').value = target.name;
                document.getElementById('targetType').value = target.type;
                document.getElementById('targetPathPrefix').value = target.path_prefix || '';
                document.getElementById('targetRetention').value = target.retention_days;
                document.getElementById('targetMaxBackups').value = target.max_backups;

                // Populate S3 fields
                document.getElementById('targetEndpoint').value = target.endpoint || '';
                document.getElementById('targetBucket').value = target.bucket || '';
                document.getElementById('targetAccessKey').value = target.access_key || '';
                document.getElementById('targetSecretKey').value = target.secret_key || '';
                document.getElementById('targetRegion').value = target.region || 'us-east-1';

                // Populate FTP/SFTP fields
                document.getElementById('targetHost').value = target.host || '';
                document.getElementById('targetPort').value = target.port || '';
                document.getElementById('targetUsername').value = target.username || '';
                document.getElementById('targetPassword').value = target.password || '';
                document.getElementById('targetRemotePath').value = target.remote_path || '/';

                if (document.getElementById('targetGlobal')) {
                    document.getElementById('targetGlobal').checked = target.is_global == 1;
                }

                // Trigger type change to show/hide correct fields
                document.getElementById('targetType').dispatchEvent(new Event('change'));

                // Update modal title
                document.getElementById('targetModalTitleText').textContent = 'Edit Backup Target';

                // Show modal
                new bootstrap.Modal(document.getElementById('targetModal')).show();
            } else {
                showAlert('Error loading target details: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('Error loading target details', 'danger');
        });
}

function deleteTarget(targetId) {
    if (confirm('Are you sure you want to delete this backup target?')) {
        fetch('api/backup-actions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': csrfToken
            },
            body: `action=delete_target&target_id=${targetId}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('Target deleted successfully!', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert('Error: ' + data.message, 'danger');
            }
        });
    }
}

function clearTargetForm() {
    // Clear all form fields
    document.getElementById('targetId').value = '';
    document.getElementById('targetName').value = '';
    document.getElementById('targetType').value = 's3';
    // S3 fields
    document.getElementById('targetEndpoint').value = '';
    document.getElementById('targetBucket').value = '';
    document.getElementById('targetAccessKey').value = '';
    document.getElementById('targetSecretKey').value = '';
    document.getElementById('targetRegion').value = 'us-east-1';
    // FTP/SFTP fields
    document.getElementById('targetHost').value = '';
    document.getElementById('targetPort').value = '';
    document.getElementById('targetUsername').value = '';
    document.getElementById('targetPassword').value = '';
    document.getElementById('targetRemotePath').value = '/';
    // Common fields
    document.getElementById('targetPathPrefix').value = '';
    document.getElementById('targetRetention').value = '30';
    document.getElementById('targetMaxBackups').value = '10';

    if (document.getElementById('targetGlobal')) {
        document.getElementById('targetGlobal').checked = false;
    }

    // Trigger type change to show S3 fields by default
    document.getElementById('targetType').dispatchEvent(new Event('change'));

    // Reset modal title
    document.getElementById('targetModalTitleText').textContent = 'Add Backup Target';
}

// Schedule functions
document.getElementById('scheduleType').addEventListener('change', function() {
    const dayContainer = document.getElementById('scheduleDayContainer');
    const daySelect = document.getElementById('scheduleDay');
    
    daySelect.innerHTML = '<option value="">Select Day</option>';
    
    if (this.value === 'weekly') {
        dayContainer.style.display = 'block';
        const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        days.forEach((day, index) => {
            const option = document.createElement('option');
            option.value = index;
            option.textContent = day;
            daySelect.appendChild(option);
        });
    } else if (this.value === 'monthly') {
        dayContainer.style.display = 'block';
        for (let i = 1; i <= 31; i++) {
            const option = document.createElement('option');
            option.value = i;
            option.textContent = i;
            daySelect.appendChild(option);
        }
    } else {
        dayContainer.style.display = 'none';
    }
});

document.getElementById('scheduleForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', document.getElementById('scheduleId').value ? 'update_schedule' : 'create_schedule');
    
    // Explicitly add checkbox value since unchecked checkboxes aren't included in FormData
    if (!formData.has('is_active')) {
        formData.append('is_active', '0');
    }
    // CSRF token will be added via header
    
    fetch('api/backup-actions.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': csrfToken
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('Schedule saved successfully!', 'success');
            bootstrap.Modal.getInstance(document.getElementById('scheduleModal')).hide();
            setTimeout(() => location.reload(), 1000);
        } else {
            showAlert('Error: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('Error: ' + error.message, 'danger');
    });
});

function editSchedule(scheduleId) {
    // Fetch schedule details and populate the form
    fetch('api/backup-actions.php?action=get_schedule&schedule_id=' + scheduleId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const schedule = data.schedule;
                
                // Populate form fields
                document.getElementById('scheduleId').value = schedule.id;
                document.getElementById('scheduleBackupType').value = schedule.backup_type;
                document.getElementById('scheduleResource').value = schedule.resource_name || '';
                document.getElementById('scheduleTarget').value = schedule.target_id;
                document.getElementById('scheduleType').value = schedule.schedule_type;
                document.getElementById('scheduleTime').value = schedule.schedule_time;
                document.getElementById('scheduleRetention').value = schedule.max_retention;
                document.getElementById('scheduleActive').checked = schedule.is_active == 1;
                
                <?php if ($isRoot): ?>
                if (document.getElementById('scheduleUser')) {
                    document.getElementById('scheduleUser').value = schedule.user;
                }
                <?php endif; ?>
                
                // Handle schedule day based on type
                const scheduleTypeElement = document.getElementById('scheduleType');
                const dayContainer = document.getElementById('scheduleDayContainer');
                const daySelect = document.getElementById('scheduleDay');
                
                daySelect.innerHTML = '<option value="">Select Day</option>';
                
                if (schedule.schedule_type === 'weekly') {
                    dayContainer.style.display = 'block';
                    const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
                    days.forEach((day, index) => {
                        const option = document.createElement('option');
                        option.value = index;
                        option.textContent = day;
                        if (schedule.schedule_day == index) {
                            option.selected = true;
                        }
                        daySelect.appendChild(option);
                    });
                } else if (schedule.schedule_type === 'monthly') {
                    dayContainer.style.display = 'block';
                    for (let i = 1; i <= 31; i++) {
                        const option = document.createElement('option');
                        option.value = i;
                        option.textContent = i;
                        if (schedule.schedule_day == i) {
                            option.selected = true;
                        }
                        daySelect.appendChild(option);
                    }
                } else {
                    dayContainer.style.display = 'none';
                }
                
                // Update modal title
                document.getElementById('scheduleModalTitleText').textContent = 'Edit Backup Schedule';
                
                // Show modal
                new bootstrap.Modal(document.getElementById('scheduleModal')).show();
            } else {
                showAlert('Error loading schedule details: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('Error loading schedule details', 'danger');
        });
}

function testSchedule(scheduleId) {
    if (confirm('This will create a test backup based on this schedule. Continue?')) {
        fetch('api/backup-actions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': csrfToken
            },
            body: `action=test_schedule&schedule_id=${scheduleId}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('Test backup started successfully! Backup ID: ' + data.backup_id, 'success');
                setTimeout(() => location.reload(), 2000);
            } else {
                showAlert('Error: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('Error: ' + error.message, 'danger');
        });
    }
}

function deleteSchedule(scheduleId) {
    if (confirm('Are you sure you want to delete this schedule?')) {
        fetch('api/backup-actions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': csrfToken
            },
            body: `action=delete_schedule&schedule_id=${scheduleId}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('Schedule deleted successfully!', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert('Error: ' + data.message, 'danger');
            }
        });
    }
}

function clearScheduleForm() {
    document.getElementById('scheduleId').value = '';
    document.getElementById('scheduleBackupType').value = '';
    document.getElementById('scheduleResource').value = '';
    document.getElementById('scheduleTarget').value = '';
    document.getElementById('scheduleType').value = '';
    document.getElementById('scheduleTime').value = '02:00';
    document.getElementById('scheduleDay').value = '';
    document.getElementById('scheduleRetention').value = '30';
    document.getElementById('scheduleActive').checked = true;
    document.getElementById('scheduleDayContainer').style.display = 'none';
    
    <?php if ($isRoot): ?>
    if (document.getElementById('scheduleUser')) {
        document.getElementById('scheduleUser').value = '';
    }
    <?php endif; ?>
    
    document.getElementById('scheduleModalTitleText').textContent = 'Add Backup Schedule';
}

function runSchedulerNow() {
    if (confirm('This will run the backup scheduler immediately to process any due scheduled backups. Continue?')) {
        fetch('api/backup-actions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': csrfToken
            },
            body: `action=run_scheduler`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('Scheduler started successfully! Check recent backups for results.', 'success');
                setTimeout(() => location.reload(), 3000);
            } else {
                showAlert('Error: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('Error: ' + error.message, 'danger');
        });
    }
}

function showAlert(message, type) {
    const icons = {
        'success': 'fa-check-circle',
        'danger': 'fa-exclamation-triangle',
        'warning': 'fa-warning',
        'info': 'fa-info-circle'
    };
    const icon = icons[type] || 'fa-info-circle';

    // Create or get the floating alert container
    let alertContainer = document.getElementById('floating-alert-container');
    if (!alertContainer) {
        alertContainer = document.createElement('div');
        alertContainer.id = 'floating-alert-container';
        alertContainer.style.cssText = `
            position: fixed;
            top: 80px;
            right: 20px;
            max-width: 400px;
            z-index: 9999;
            pointer-events: none;
        `;
        document.body.appendChild(alertContainer);
    }

    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.style.cssText = `
        pointer-events: auto;
        margin-bottom: 10px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        animation: slideInRight 0.3s ease-out;
    `;
    alertDiv.innerHTML = `
        <i class="fa ${icon} me-1"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    alertContainer.appendChild(alertDiv);

    // Auto-dismiss after 15 seconds
    setTimeout(() => {
        if (alertDiv && alertDiv.parentNode) {
            alertDiv.classList.add('fade');
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 150);
        }
    }, 15000);
}

// Convert times when page loads. The global js/whp-times.js handler
// rewrites .local-time elements automatically and observes DOM changes,
// so we only need to kick off the initial backup load here.
document.addEventListener('DOMContentLoaded', function() {
    loadBackups(1); // Load first page of backups
});

// Pagination and search functionality
let currentPage = 1;
let totalPages = 1;
let totalBackups = 0;

function loadBackups(page = 1) {
    currentPage = page;
    
    const searchTerm = document.getElementById('backupSearch').value;
    const userFilter = document.getElementById('backupUserFilter')?.value || '';
    const typeFilter = document.getElementById('backupTypeFilter').value;
    const statusFilter = document.getElementById('backupStatusFilter').value;
    const limit = document.getElementById('backupLimitFilter').value;
    const offset = (page - 1) * limit;
    
    // Build query parameters
    const params = new URLSearchParams({
        action: 'list_backups',
        limit: limit,
        offset: offset
    });
    
    if (searchTerm) params.append('search', searchTerm);
    if (userFilter) params.append('user', userFilter);
    if (typeFilter) params.append('backup_type', typeFilter);
    if (statusFilter) params.append('status', statusFilter);
    
    // Show loading indicator
    document.getElementById('backupsList').innerHTML = '<tr><td colspan="9" class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading backups...</td></tr>';
    
    fetch('api/backup-actions.php?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                totalBackups = data.total;
                totalPages = Math.ceil(totalBackups / limit);
                displayBackups(data.backups);
                updatePagination();
                updateBackupInfo(offset, limit);
            } else {
                showAlert('Error loading backups: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('Error loading backups: ' + error.message, 'danger');
        });
}

function displayBackups(backups) {
    const tbody = document.getElementById('backupsList');
    
    if (backups.length === 0) {
        tbody.innerHTML = '<tr><td colspan="9" class="text-center text-muted">No backups found</td></tr>';
        return;
    }
    
    tbody.innerHTML = backups.map(backup => `
        <tr>
            <td>
                ${<?php echo $isRoot ? 'true' : 'false'; ?> || backup.user === '<?php echo AUTH_USER; ?>' ? `
                    <input type="checkbox" class="backup-checkbox" value="${backup.id}" onchange="updateBulkActionButtons()">
                ` : ''}
            </td>
            <td class="backup-name-cell" title="${escapeHtml(backup.backup_name)}">
                <i class="fa fa-${getBackupTypeIconJS(backup.backup_type)}"></i>
                ${escapeHtml(backup.backup_name)}
            </td>
            <td>
                <span class="badge bg-${getBackupTypeColorJS(backup.backup_type)}">
                    ${backup.backup_type.charAt(0).toUpperCase() + backup.backup_type.slice(1)}
                </span>
            </td>
            <td>${escapeHtml(backup.user)}</td>
            <td>${escapeHtml(backup.target_name)}</td>
            <td>${formatBytesJS(backup.backup_size)}</td>
            <td>
                <span class="badge bg-${getStatusColorJS(backup.status)}">
                    ${backup.status.charAt(0).toUpperCase() + backup.status.slice(1)}
                </span>
                ${backup.status === 'failed' && backup.error_message ? `
                    <i class="fa fa-info-circle text-danger ms-1" data-bs-toggle="tooltip" data-bs-placement="top" title="${escapeHtml(backup.error_message)}"></i>
                ` : ''}
                ${backup.upload_status && backup.upload_status !== 'uploaded' && backup.status === 'completed' ? `
                    <span class="badge bg-${backup.upload_status === 'failed' ? 'danger' : 'secondary'} ms-1" style="font-size: 0.7em;">
                        Upload: ${backup.upload_status}
                    </span>
                ` : ''}
            </td>
            <td>
                <span class="local-time" data-utc="${backup.started_at}" data-format="datetime-seconds">
                    ${backup.started_at}
                </span>
            </td>
            <td>
                <div class="btn-group btn-group-sm">
                ${backup.status === 'completed' ? `
                    <button class="btn btn-outline-success" onclick="downloadBackup(${backup.id})">
                        <i class="fa fa-download"></i> Download
                    </button>
                ` : ''}
                ${backup.status === 'failed' ? `
                    <button class="btn btn-outline-warning" onclick="retryBackup(${backup.id})">
                        <i class="fa fa-refresh"></i> Retry
                    </button>
                ` : ''}
                ${<?php echo $isRoot ? 'true' : 'false'; ?> || backup.user === '<?php echo AUTH_USER; ?>' ? `
                    <button class="btn btn-outline-danger" onclick="deleteBackup(${backup.id})">
                        <i class="fa fa-trash"></i> Delete
                    </button>
                ` : ''}
                </div>
            </td>
        </tr>
    `).join('');
    
    // The global whp-times.js MutationObserver picks up inserted rows
    // automatically; this explicit call is a belt-and-suspenders for
    // browsers without MutationObserver (extremely old) and a no-op
    // otherwise.
    if (window.whpRefreshTimes) window.whpRefreshTimes();

    // Initialize Bootstrap tooltips for error messages
    const tooltipElements = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    tooltipElements.forEach(el => new bootstrap.Tooltip(el));
}

function updatePagination() {
    const pagination = document.getElementById('backupPagination');
    const pages = [];
    
    // Previous button
    pages.push(`
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadBackups(${currentPage - 1}); return false;">Previous</a>
        </li>
    `);
    
    // Calculate page range
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);
    
    // First page if not in range
    if (startPage > 1) {
        pages.push(`
            <li class="page-item">
                <a class="page-link" href="#" onclick="loadBackups(1); return false;">1</a>
            </li>
        `);
        if (startPage > 2) {
            pages.push(`<li class="page-item disabled"><span class="page-link">...</span></li>`);
        }
    }
    
    // Page numbers
    for (let i = startPage; i <= endPage; i++) {
        pages.push(`
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" onclick="loadBackups(${i}); return false;">${i}</a>
            </li>
        `);
    }
    
    // Last page if not in range
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            pages.push(`<li class="page-item disabled"><span class="page-link">...</span></li>`);
        }
        pages.push(`
            <li class="page-item">
                <a class="page-link" href="#" onclick="loadBackups(${totalPages}); return false;">${totalPages}</a>
            </li>
        `);
    }
    
    // Next button
    pages.push(`
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadBackups(${currentPage + 1}); return false;">Next</a>
        </li>
    `);
    
    pagination.innerHTML = pages.join('');
}

function updateBackupInfo(offset, limit) {
    const info = document.getElementById('backupInfo');
    const start = offset + 1;
    const end = Math.min(offset + parseInt(limit), totalBackups);
    
    if (totalBackups === 0) {
        info.textContent = 'No backups found';
    } else {
        info.textContent = `Showing ${start} to ${end} of ${totalBackups} backups`;
    }
}

// Helper functions
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function getBackupTypeColorJS(type) {
    switch (type) {
        case 'site': return 'primary';
        case 'userfiles': return 'info';
        case 'database': return 'warning';
        default: return 'secondary';
    }
}

function getBackupTypeIconJS(type) {
    switch (type) {
        case 'site': return 'globe';
        case 'userfiles': return 'folder';
        case 'database': return 'database';
        default: return 'file';
    }
}

function getStatusColorJS(status) {
    switch (status) {
        case 'completed': return 'success';
        case 'running': return 'warning';
        case 'failed': return 'danger';
        case 'pending': return 'info';
        default: return 'secondary';
    }
}

function formatBytesJS(bytes, precision = 2) {
    // Handle null, undefined, or invalid values
    if (bytes === null || bytes === undefined || isNaN(bytes) || bytes < 0) {
        return '0 B';
    }
    
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let unitIndex = 0;
    
    // Convert bytes to appropriate unit
    while (bytes >= 1024 && unitIndex < units.length - 1) {
        bytes /= 1024;
        unitIndex++;
    }
    
    return bytes.toFixed(precision) + ' ' + units[unitIndex];
}

// Search on enter key
document.getElementById('backupSearch').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        loadBackups(1);
    }
});

// Multi-select functionality
function toggleSelectAll() {
    const selectAll = document.getElementById('selectAllBackups');
    const checkboxes = document.querySelectorAll('.backup-checkbox');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll.checked;
    });
    
    updateBulkActionButtons();
}

function updateBulkActionButtons() {
    const selectedCheckboxes = document.querySelectorAll('.backup-checkbox:checked');
    const bulkActions = document.getElementById('bulkActions');
    const selectedCount = document.getElementById('selectedCount');
    const selectAllCheckbox = document.getElementById('selectAllBackups');
    const allCheckboxes = document.querySelectorAll('.backup-checkbox');
    
    // Update selected count
    selectedCount.textContent = selectedCheckboxes.length;
    
    // Show/hide bulk actions
    if (selectedCheckboxes.length > 0) {
        bulkActions.style.display = 'block';
    } else {
        bulkActions.style.display = 'none';
    }
    
    // Update select all checkbox state
    if (selectedCheckboxes.length === 0) {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
    } else if (selectedCheckboxes.length === allCheckboxes.length) {
        selectAllCheckbox.checked = true;
        selectAllCheckbox.indeterminate = false;
    } else {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = true;
    }
}

function clearSelection() {
    document.querySelectorAll('.backup-checkbox:checked').forEach(cb => cb.checked = false);
    document.getElementById('selectAllBackups').checked = false;
    updateBulkActionButtons();
}

// Update help text for global targets
<?php if ($isRoot): ?>
document.getElementById('targetGlobal').addEventListener('change', function() {
    const helpText = document.getElementById('maxBackupsHelp');
    const hintText = document.getElementById('maxBackupsHint');
    if (this.checked) {
        helpText.textContent = 'Maximum backups to keep per user, per backup type';
        hintText.textContent = '(Per User)';
    } else {
        helpText.textContent = 'Maximum backups to keep per backup type';
        hintText.textContent = '';
    }
});
<?php endif; ?>
</script>

<script src="/js/whp-table.js"></script>

<style>
/* Truncate long backup names */
.backup-name-cell {
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* Animation for alerts sliding in */
@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

/* Responsive adjustments for alerts */
@media (max-width: 768px) {
    #floating-alert-container {
        right: 10px !important;
        left: 10px !important;
        max-width: none !important;
    }
}
</style>

<?php
function formatBytes($bytes, $precision = 2) {
    if ($bytes <= 0) {
        return '0 B';
    }
    
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    $unitIndex = 0;
    
    while ($bytes >= 1024 && $unitIndex < count($units) - 1) {
        $bytes /= 1024;
        $unitIndex++;
    }
    
    return round($bytes, $precision) . ' ' . $units[$unitIndex];
}

function getBackupTypeColor($type) {
    switch ($type) {
        case 'site': return 'primary';
        case 'userfiles': return 'info';
        case 'database': return 'warning';
        default: return 'secondary';
    }
}

function getStatusColor($status) {
    switch ($status) {
        case 'completed': return 'success';
        case 'running': return 'warning';
        case 'failed': return 'danger';
        case 'pending': return 'info';
        default: return 'secondary';
    }
}
?>