<?php
include realpath(dirname(__DIR__) . '/include/header.php');

// File size formatter function
function formatFileSize($size) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    for ($i = 0; $size > 1024 && $i < count($units) - 1; $i++) {
        $size /= 1024;
    }
    return round($size, 2) . ' ' . $units[$i];
}
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="page-title-box">
                <h4 class="page-title">System Files Manager</h4>
                <p class="text-muted">Manage phpnuxbill.sql and phpnuxbill.zip files</p>
            </div>
        </div>
    </div>

    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Upload Section -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-upload"></i> Upload System Files
                    </h5>
                </div>
                <div class="card-body">
                    <div class="alert alert-info">
                        <h6><i class="mdi mdi-information"></i> Important Notes:</h6>
                        <ul class="mb-0">
                            <li>Only files named <strong>phpnuxbill.sql</strong> and <strong>phpnuxbill.zip</strong> are allowed</li>
                            <li>Existing files will be automatically backed up before replacement</li>
                            <li>SQL files must contain valid CREATE TABLE or INSERT INTO statements</li>
                            <li>ZIP files will be validated for integrity</li>
                        </ul>
                    </div>

                    <form method="POST" action="?app_route=system_files_upload" enctype="multipart/form-data">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Select File</label>
                                    <input type="file" class="form-control" name="system_file" 
                                           accept=".sql,.zip" required>
                                    <small class="form-text text-muted">
                                        Accepted files: phpnuxbill.sql, phpnuxbill.zip
                                    </small>
                                </div>
                            </div>
                            <div class="col-md-6 d-flex align-items-end">
                                <div class="mb-3">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="mdi mdi-upload"></i> Upload File
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Current Files Section -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-file-multiple"></i> Current System Files
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($files)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>File Name</th>
                                        <th>Type</th>
                                        <th>Size</th>
                                        <th>Last Modified</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($files as $file): ?>
                                        <tr>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <div class="flex-shrink-0">
                                                        <?php
                                                        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                                                        $iconClass = $extension === 'sql' ? 'mdi-database' : 'mdi-zip-box';
                                                        $bgColor = $extension === 'sql' ? 'bg-primary' : 'bg-success';
                                                        ?>
                                                        <div class="avatar-xs">
                                                            <div class="avatar-title rounded <?php echo $bgColor; ?> text-white">
                                                                <i class="mdi <?php echo $iconClass; ?>"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="flex-grow-1 ms-3">
                                                        <h6 class="mb-0"><?php echo htmlspecialchars($file['name']); ?></h6>
                                                        <?php if (isset($file['is_backup'])): ?>
                                                            <span class="badge bg-warning font-size-11">Backup File</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <?php
                                                $typeLabel = strtoupper($extension);
                                                $typeColor = $extension === 'sql' ? 'info' : 'success';
                                                ?>
                                                <span class="badge bg-<?php echo $typeColor; ?>">
                                                    <?php echo $typeLabel; ?> File
                                                </span>
                                            </td>
                                            <td>
                                                <?php echo formatFileSize($file['size']); ?>
                                            </td>
                                            <td>
                                                <?php echo date('M j, Y H:i:s', $file['modified']); ?>
                                            </td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <a href="?app_route=system_files_download&file=<?php echo urlencode($file['name']); ?>" 
                                                       class="btn btn-sm btn-outline-primary">
                                                        <i class="mdi mdi-download"></i> Download
                                                    </a>
                                                    
                                                    <?php if (!isset($file['is_backup'])): ?>
                                                        <button type="button" class="btn btn-sm btn-outline-danger" 
                                                                onclick="confirmDelete('<?php echo htmlspecialchars($file['name']); ?>')">
                                                            <i class="mdi mdi-delete"></i> Delete
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-4">
                            <div class="avatar-lg mx-auto mb-3">
                                <div class="avatar-title rounded-circle bg-soft-info text-info">
                                    <i class="mdi mdi-file-question font-size-24"></i>
                                </div>
                            </div>
                            <h5>No System Files Found</h5>
                            <p class="text-muted">Upload phpnuxbill.sql or phpnuxbill.zip files to get started.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- File Operation Logs -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-history"></i> Recent File Operations
                    </h5>
                </div>
                <div class="card-body">
                    <?php
                    $systemFiles = new \App\Controllers\SystemFiles();
                    $logs = $systemFiles->getLogs();
                    ?>
                    
                    <?php if (!empty($logs)): ?>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Operation</th>
                                        <th>File</th>
                                        <th>User</th>
                                        <th>IP Address</th>
                                        <th>Date/Time</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach (array_slice($logs, 0, 10) as $log): ?>
                                        <tr>
                                            <td>
                                                <?php
                                                $operationColors = [
                                                    'upload' => 'success',
                                                    'delete' => 'danger',
                                                    'download' => 'info'
                                                ];
                                                $color = $operationColors[$log['operation']] ?? 'secondary';
                                                ?>
                                                <span class="badge bg-<?php echo $color; ?>">
                                                    <?php echo ucfirst($log['operation']); ?>
                                                </span>
                                            </td>
                                            <td><?php echo htmlspecialchars($log['file_name']); ?></td>
                                            <td><?php echo htmlspecialchars($log['username']); ?></td>
                                            <td><?php echo htmlspecialchars($log['ip_address']); ?></td>
                                            <td><?php echo date('M j, Y H:i:s', strtotime($log['created_at'])); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <p class="text-muted text-center">No file operations logged yet.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirm Deletion</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="mdi mdi-alert-triangle"></i>
                    <strong>Warning!</strong> You are about to delete the file: <span id="deleteFileName"></span>
                </div>
                <p>This action will:</p>
                <ul>
                    <li>Create a backup copy before deletion</li>
                    <li>Permanently remove the original file</li>
                    <li>Log this operation for audit purposes</li>
                </ul>
                <p><strong>Are you sure you want to continue?</strong></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <form method="POST" action="?app_route=system_files_delete" class="d-inline">
                    <input type="hidden" name="file_name" id="deleteFileInput">
                    <button type="submit" class="btn btn-danger">
                        <i class="mdi mdi-delete"></i> Delete File
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function confirmDelete(fileName) {
    document.getElementById('deleteFileName').textContent = fileName;
    document.getElementById('deleteFileInput').value = fileName;
    new bootstrap.Modal(document.getElementById('deleteModal')).show();
}
</script>

<?php
include realpath(dirname(__DIR__) . '/include/footer.php');
?>
