<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/functions.php';
require_admin();

// Handle file uploads
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    ensure_csrf();
    
    $file = $_FILES['file'];
    $fieldName = $_POST['field_name'] ?? 'file';
    $uploadDir = __DIR__ . '/../uploads/settings/';
    
    // Create upload directory if it doesn't exist
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // Validate file
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/x-icon', 'image/vnd.microsoft.icon', 'image/ico'];
    $maxSize = 5 * 1024 * 1024; // 5MB increased for better support
    
    if (!in_array($file['type'], $allowedTypes)) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Invalid file type. Only JPG, PNG, GIF, SVG, and ICO files allowed.']);
        exit;
    }
    
    if ($file['size'] > $maxSize) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'File too large. Maximum 5MB allowed.']);
        exit;
    }
    
    // Check for upload errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errorMessages = [
            UPLOAD_ERR_INI_SIZE => 'File too large (server limit)',
            UPLOAD_ERR_FORM_SIZE => 'File too large (form limit)',
            UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
            UPLOAD_ERR_NO_FILE => 'No file was uploaded',
            UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
            UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
            UPLOAD_ERR_EXTENSION => 'File upload stopped by extension',
        ];
        
        $errorMsg = $errorMessages[$file['error']] ?? 'Unknown upload error';
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => $errorMsg]);
        exit;
    }
    
    // Generate filename based on field type for overwriting
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    
    // Use consistent naming for logo/favicon to enable overwriting
    if ($fieldName === 'site_logo') {
        $filename = 'logo.' . $extension;
    } elseif ($fieldName === 'site_favicon') {
        $filename = 'favicon.' . $extension;
    } elseif ($fieldName === 'og_image') {
        $filename = 'og-image.' . $extension;
    } else {
        // For other fields, use unique filename
        $filename = uniqid() . '.' . $extension;
    }
    
    $filepath = $uploadDir . $filename;
    
    // Delete existing file with same name (for overwrite functionality)
    if (file_exists($filepath)) {
        unlink($filepath);
    }
    
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        $url = '/uploads/settings/' . $filename;
        
        // Set proper permissions
        chmod($filepath, 0644);
        
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true, 
            'url' => $url, 
            'filename' => $filename,
            'message' => 'File uploaded successfully',
            'field_name' => $fieldName
        ]);
    } else {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Failed to upload file. Check directory permissions.']);
    }
    exit;
}

header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'No file uploaded']);
?>
