<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

header('Content-Type: application/json');
hw_require_auth(['admin']);

$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method === 'GET') {
        // Get media files from uploads directory
        $uploadDir = __DIR__ . '/../../uploads/cms';
        $files = [];
        
        if (is_dir($uploadDir)) {
            foreach (scandir($uploadDir) as $file) {
                if ($file !== '.' && $file !== '..') {
                    $filePath = $uploadDir . '/' . $file;
                    $files[] = [
                        'name' => $file,
                        'size' => filesize($filePath),
                        'type' => mime_content_type($filePath),
                        'url' => '/files/atasteofafricanmarketplace/uploads/cms/' . $file,
                        'date' => date('Y-m-d H:i:s', filemtime($filePath))
                    ];
                }
            }
        }
        
        echo json_encode([
            'success' => true,
            'files' => $files,
            'total' => count($files)
        ]);
    } 
    else if ($method === 'POST') {
        // Upload media file
        if (!isset($_FILES['file'])) {
            echo json_encode(['success' => false, 'error' => 'No file provided']);
            exit;
        }
        
        $file = $_FILES['file'];
        $uploadDir = __DIR__ . '/../../uploads/cms';
        
        // Create directory if it doesn't exist
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        // Validate file
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf', 'text/csv'];
        if (!in_array($file['type'], $allowedTypes)) {
            echo json_encode(['success' => false, 'error' => 'File type not allowed']);
            exit;
        }
        
        if ($file['size'] > 5000000) { // 5MB limit
            echo json_encode(['success' => false, 'error' => 'File too large']);
            exit;
        }
        
        // Generate unique filename
        $filename = uniqid() . '_' . basename($file['name']);
        $targetPath = $uploadDir . '/' . $filename;
        
        if (move_uploaded_file($file['tmp_name'], $targetPath)) {
            echo json_encode([
                'success' => true,
                'message' => 'File uploaded successfully',
                'file' => [
                    'name' => $filename,
                    'url' => '/files/atasteofafricanmarketplace/uploads/cms/' . $filename,
                    'size' => $file['size'],
                    'type' => $file['type']
                ]
            ]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Failed to upload file']);
        }
    } 
    else if ($method === 'DELETE') {
        // Delete media file
        $input = json_decode(file_get_contents('php://input'), true);
        $filename = $input['filename'] ?? '';
        
        if (!$filename || strpos($filename, '/') !== false) {
            echo json_encode(['success' => false, 'error' => 'Invalid filename']);
            exit;
        }
        
        $filePath = __DIR__ . '/../../uploads/cms/' . $filename;
        
        if (file_exists($filePath) && unlink($filePath)) {
            echo json_encode(['success' => true, 'message' => 'File deleted']);
        } else {
            echo json_encode(['success' => false, 'error' => 'Failed to delete file']);
        }
    }
    else {
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
