<?php
/**
 * Admin - File Manager
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'File Manager';
$errors = [];
$success = '';

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload_file'])) {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        $directory = sanitize($_POST['directory'] ?? 'general');
        $allowed_types = $_POST['file_type'] === 'image' ? ALLOWED_IMAGE_TYPES : ALLOWED_DOCUMENT_TYPES;
        
        $result = upload_file($_FILES['upload_file'], $directory, $allowed_types);
        if ($result['success']) {
            $success = 'File uploaded successfully: ' . $result['path'];
            log_activity('file_upload', 'Uploaded file: ' . $result['path'], $_SESSION['admin_id'], 'admin');
        } else {
            $errors[] = $result['message'];
        }
    }
}

// Handle file deletion
if (isset($_GET['delete'])) {
    $file = sanitize($_GET['delete']);
    $filepath = UPLOADS_PATH . $file;
    if (file_exists($filepath) && strpos($file, '..') === false) {
        unlink($filepath);
        log_activity('file_delete', 'Deleted file: ' . $file, $_SESSION['admin_id'], 'admin');
        redirect(BASE_URL . 'admin/file-manager.php', 'success', 'File deleted');
    }
}

// Scan uploads directory
$directories = [];
$files = [];
if (is_dir(UPLOADS_PATH)) {
    $dirs = glob(UPLOADS_PATH . '*', GLOB_ONLYDIR);
    foreach ($dirs as $dir) {
        $dir_name = basename($dir);
        $directories[] = $dir_name;
        
        $dir_files = glob($dir . '/*');
        foreach ($dir_files as $file) {
            if (is_file($file)) {
                $files[] = [
                    'name' => basename($file),
                    'path' => $dir_name . '/' . basename($file),
                    'directory' => $dir_name,
                    'size' => filesize($file),
                    'modified' => filemtime($file)
                ];
            }
        }
    }
}

// Sort files by modified date
glob($files, function($a, $b) {
    return $b['modified'] - $a['modified'];
});

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';

function format_bytes($bytes) {
    $units = ['B', 'KB', 'MB', 'GB'];
    $unit = 0;
    while ($bytes >= 1024 && $unit < count($units) - 1) {
        $bytes /= 1024;
        $unit++;
    }
    return round($bytes, 2) . ' ' . $units[$unit];
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">File Manager</h2>
</div>

<div class="row">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white">
                <h5 class="mb-0">Upload File</h5>
            </div>
            <div class="card-body">
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger"><?php foreach ($errors as $error): ?><p class="mb-0"><?php echo $error; ?></p><?php endforeach; ?></div>
                <?php endif; ?>
                <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                <?php endif; ?>
                
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                    <div class="mb-3">
                        <label class="form-label">Select File</label>
                        <input type="file" name="upload_file" class="form-control" required>
                        <small class="text-muted">Max size: <?php echo MAX_FILE_UPLOAD_SIZE_MB; ?>MB</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">File Type</label>
                        <select name="file_type" class="form-select">
                            <option value="image">Image (jpg, png, gif, webp)</option>
                            <option value="document">Document (pdf, doc, docx)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Directory</label>
                        <select name="directory" class="form-select">
                            <option value="general">General</option>
                            <option value="blog">Blog</option>
                            <option value="services">Services</option>
                            <option value="software">Software</option>
                            <option value="testimonials">Testimonials</option>
                            <option value="users">Users</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary w-100"><i class="bi bi-upload me-2"></i>Upload</button>
                </form>
            </div>
        </div>
        
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h5 class="mb-0">Directories</h5>
            </div>
            <div class="list-group list-group-flush">
                <?php foreach ($directories as $dir): ?>
                <div class="list-group-item d-flex justify-content-between align-items-center">
                    <span><i class="bi bi-folder me-2 text-warning"></i><?php echo $dir; ?></span>
                    <span class="badge bg-secondary">
                        <?php echo count(array_filter($files, fn($f) => $f['directory'] === $dir)); ?> files
                    </span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    
    <div class="col-md-8">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Uploaded Files</h5>
                <span class="text-muted"><?php echo count($files); ?> files</span>
            </div>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>File</th>
                            <th>Directory</th>
                            <th>Size</th>
                            <th>Modified</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach (array_slice($files, 0, 50) as $file): 
                            $is_image = in_array(strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)), ['jpg', 'jpeg', 'png', 'gif', 'webp']);
                        ?>
                        <tr>
                            <td>
                                <?php if ($is_image): ?>
                                    <i class="bi bi-image me-2 text-primary"></i>
                                <?php else: ?>
                                    <i class="bi bi-file-earmark me-2 text-secondary"></i>
                                <?php endif; ?>
                                <?php echo $file['name']; ?>
                            </td>
                            <td><?php echo $file['directory']; ?></td>
                            <td><?php echo format_bytes($file['size']); ?></td>
                            <td><?php echo date('d M Y H:i', $file['modified']); ?></td>
                            <td>
                                <a href="<?php echo UPLOADS_URL . $file['path']; ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-eye"></i>
                                </a>
                                <a href="file-manager.php?delete=<?php echo urlencode($file['path']); ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this file?')">
                                    <i class="bi bi-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($files)): ?>
                        <tr><td colspan="5" class="text-center py-4 text-muted">No files uploaded yet</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
