<?php
/**
 * Test upload script to diagnose and handle upload size issues
 */

// Set custom error handler to catch upload errors
set_error_handler(function($severity, $message, $file, $line) {
    if (strpos($message, 'Maximum') !== false && strpos($message, 'uploaded') !== false) {
        throw new ErrorException($message, 0, $severity, $file, $line);
    }
});

// Function to get human-readable file size
function formatBytes($size, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB');
    for ($i = 0; $size > 1024 && $i < count($units) - 1; $i++) {
        $size /= 1024;
    }
    return round($size, $precision) . ' ' . $units[$i];
}

// Check current PHP upload settings
$max_upload = (int)(ini_get('upload_max_filesize'));
$max_post = (int)(ini_get('post_max_size'));
$memory_limit = (int)(ini_get('memory_limit'));

$min_max_upload = min($max_upload, $max_post, $memory_limit);

// Handle form submission
$message = '';
$messageType = 'info';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['test_upload']) && $_FILES['test_upload']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['test_upload'];
        
        // Validate file
        if ($file['error'] === UPLOAD_ERR_INI_SIZE || $file['error'] === UPLOAD_ERR_FORM_SIZE) {
            $message = "File is too large. Maximum allowed size is " . formatBytes(min($max_upload * 1024 * 1024, $max_post * 1024 * 1024));
            $messageType = 'danger';
        } else if ($file['error'] !== UPLOAD_ERR_OK) {
            $message = "Upload error occurred. Error code: " . $file['error'];
            $messageType = 'danger';
        } else {
            $message = "Upload successful! File: " . htmlspecialchars($file['name']) . " (" . formatBytes($file['size']) . ")";
            $messageType = 'success';
        }
    } else if (isset($_FILES['test_upload'])) {
        $error = $_FILES['test_upload']['error'];
        
        switch ($error) {
            case UPLOAD_ERR_INI_SIZE:
                $message = "❌ File exceeds PHP upload_max_filesize limit (" . ini_get('upload_max_filesize') . ")";
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $message = "❌ File exceeds MAX_FILE_SIZE limit specified in HTML form";
                break;
            case UPLOAD_ERR_PARTIAL:
                $message = "❌ File was only partially uploaded";
                break;
            case UPLOAD_ERR_NO_FILE:
                $message = "❌ No file was uploaded";
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $message = "❌ Missing temporary folder";
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $message = "❌ Failed to write file to disk";
                break;
            case UPLOAD_ERR_EXTENSION:
                $message = "❌ File upload stopped by extension";
                break;
            default:
                $message = "❌ Unknown upload error";
        }
        
        // Check if this might be a nginx 413 error that was handled by PHP
        if ($error === UPLOAD_ERR_INI_SIZE) {
            $message .= "<br><br><strong>💡 This might be a nginx configuration issue.</strong><br>";
            $message .= "nginx may have rejected the request before it reached PHP. ";
            $message .= "Check your nginx configuration and ensure 'client_max_body_size' is set appropriately.";
        }
        
        $messageType = 'danger';
    } else {
        $message = "No file was uploaded.";
        $messageType = 'warning';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Test - Bidda School Management System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h3 class="mb-0"><i class="fas fa-cloud-upload-alt me-2"></i>Upload Test & Diagnosis</h3>
                    </div>
                    <div class="card-body">
                        <?php if ($message): ?>
                            <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                                <?php echo $message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        <?php endif; ?>

                        <h5><i class="fas fa-server me-2 text-info"></i>Current Server Upload Limits:</h5>
                        <ul class="list-group mb-4">
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                <span><i class="fas fa-file-upload me-2 text-primary"></i>upload_max_filesize</span>
                                <span class="badge bg-primary"><?php echo ini_get('upload_max_filesize'); ?></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                <span><i class="fas fa-envelope-open-text me-2 text-success"></i>post_max_size</span>
                                <span class="badge bg-success"><?php echo ini_get('post_max_size'); ?></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                <span><i class="fas fa-memory me-2 text-warning"></i>memory_limit</span>
                                <span class="badge bg-warning"><?php echo ini_get('memory_limit'); ?></span>
                            </li>
                        </ul>

                        <h5><i class="fas fa-tools me-2 text-info"></i>Upload Test:</h5>
                        <form method="POST" enctype="multipart/form-data" class="mb-4">
                            <div class="mb-3">
                                <label for="test_upload" class="form-label">Select a file to upload:</label>
                                <input type="file" class="form-control" id="test_upload" name="test_upload" accept="image/*,.pdf,.doc,.docx">
                                <div class="form-text">Try uploading a file larger than the limits above to test error handling.</div>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-paper-plane me-1"></i>Test Upload
                            </button>
                        </form>

                        <div class="alert alert-info">
                            <h6><i class="fas fa-info-circle me-2"></i>About the 413 Error</h6>
                            <p class="mb-2">The "413 Request Entity Too Large" error is generated by nginx (web server), not PHP.</p>
                            <p class="mb-0">To fix this issue:</p>
                            <ol>
                                <li>Locate your nginx configuration file (usually in C:\MAMP\conf\nginx\nginx.conf)</li>
                                <li>Add or modify the line: <code>client_max_body_size 50M;</code> inside the <code>http</code> block</li>
                                <li>Restart your MAMP servers</li>
                            </ol>
                        </div>

                        <div class="alert alert-light border">
                            <h6><i class="fas fa-lightbulb me-2 text-warning"></i>Quick Fix for Bidda Certificates</h6>
                            <p class="mb-2">If you're having issues with logo uploads in the certificates section:</p>
                            <ol>
                                <li>Open <code>C:\MAMP\conf\nginx\nginx.conf</code> as Administrator</li>
                                <li>Find the <code>http</code> block (usually around line 20-30)</li>
                                <li>Add this line: <code>client_max_body_size 50M;</code></li>
                                <li>Save the file and restart MAMP</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>