<?php
/**
 * Category Image Upload Test & Diagnostic Tool
 * Use this to verify image uploads are working correctly
 */

date_default_timezone_set('Asia/Colombo');
require_once '../config.php';
require_once '../auth.php';
checkAuth();

$result = '';
$upload_info = [];

// Check upload directory
$uploadDir = __DIR__ . '/uploads';
$upload_info['Directory Exists'] = is_dir($uploadDir) ? '✓ Yes' : '✗ No';
$upload_info['Directory Writable'] = is_writable($uploadDir) ? '✓ Yes' : '✗ No';
$upload_info['Directory Path'] = $uploadDir;

// Check PHP settings
$upload_info['upload_max_filesize'] = ini_get('upload_max_filesize');
$upload_info['post_max_size'] = ini_get('post_max_size');
$upload_info['max_file_uploads'] = ini_get('max_file_uploads');
$upload_info['file_uploads'] = ini_get('file_uploads') ? 'Enabled' : 'Disabled';

// Test upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['test_image'])) {
    $result .= "<h5 class='text-info'>Upload Attempt Details:</h5>";
    $result .= "<pre>" . print_r($_FILES['test_image'], true) . "</pre>";
    
    if ($_FILES['test_image']['error'] === UPLOAD_ERR_OK) {
        $allowed = ['jpg','jpeg','png','gif','webp'];
        $ext = strtolower(pathinfo($_FILES['test_image']['name'], PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $filename = 'test_' . time() . '_' . random_int(1000,9999) . '.' . $ext;
            $dest = $uploadDir . '/' . $filename;
            
            if (move_uploaded_file($_FILES['test_image']['tmp_name'], $dest)) {
                $result .= "<div class='alert alert-success'>";
                $result .= "<h5>✓ Upload Successful!</h5>";
                $result .= "<p>File saved to: <code>$dest</code></p>";
                $result .= "<p>File size: " . filesize($dest) . " bytes</p>";
                $result .= "<p>Image: <img src='uploads/$filename' style='max-width:200px;max-height:200px;'></p>";
                $result .= "</div>";
            } else {
                $result .= "<div class='alert alert-danger'>";
                $result .= "<h5>✗ Upload Failed</h5>";
                $result .= "<p>move_uploaded_file() failed</p>";
                $result .= "<p>Check folder permissions and PHP error log</p>";
                $result .= "</div>";
            }
        } else {
            $result .= "<div class='alert alert-warning'>Invalid file type: $ext</div>";
        }
    } else {
        $errors = [
            UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize',
            UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE',
            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 => 'Upload stopped by extension'
        ];
        $error_msg = $errors[$_FILES['test_image']['error']] ?? 'Unknown error';
        $result .= "<div class='alert alert-danger'>Upload Error: $error_msg (Code: {$_FILES['test_image']['error']})</div>";
    }
}

// List existing uploads
$existing_files = [];
if (is_dir($uploadDir)) {
    $files = scandir($uploadDir);
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..' && is_file($uploadDir . '/' . $file)) {
            $existing_files[] = [
                'name' => $file,
                'size' => filesize($uploadDir . '/' . $file),
                'modified' => date('Y-m-d H:i:s', filemtime($uploadDir . '/' . $file)),
                'url' => 'uploads/' . $file
            ];
        }
    }
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Category Image Upload Test</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">📸 Category Image Upload Diagnostic</h4>
                    </div>
                    <div class="card-body">
                        
                        <!-- System Info -->
                        <h5 class="mb-3">System Configuration</h5>
                        <table class="table table-bordered table-sm">
                            <?php foreach ($upload_info as $key => $value): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($key) ?></strong></td>
                                <td><?= htmlspecialchars($value) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </table>

                        <!-- Upload Result -->
                        <?= $result ?>

                        <!-- Test Upload Form -->
                        <h5 class="mt-4 mb-3">Test Image Upload</h5>
                        <form method="post" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label class="form-label">Select Image</label>
                                <input type="file" name="test_image" accept="image/jpeg,image/png,image/gif,image/webp" class="form-control" required>
                                <small class="text-muted">Allowed: JPG, PNG, GIF, WEBP</small>
                            </div>
                            <button type="submit" class="btn btn-primary">Test Upload</button>
                            <a href="products.php" class="btn btn-secondary">Back to Products</a>
                        </form>

                        <!-- Existing Files -->
                        <?php if (!empty($existing_files)): ?>
                        <h5 class="mt-4 mb-3">Existing Uploaded Images (<?= count($existing_files) ?>)</h5>
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm">
                                <thead>
                                    <tr>
                                        <th>Preview</th>
                                        <th>Filename</th>
                                        <th>Size</th>
                                        <th>Modified</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($existing_files as $file): ?>
                                    <tr>
                                        <td>
                                            <img src="<?= htmlspecialchars($file['url']) ?>" 
                                                 style="width:50px;height:50px;object-fit:cover;" 
                                                 onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2250%22 height=%2250%22%3E%3Crect fill=%22%23ccc%22 width=%2250%22 height=%2250%22/%3E%3C/svg%3E'">
                                        </td>
                                        <td><small><?= htmlspecialchars($file['name']) ?></small></td>
                                        <td><?= number_format($file['size'] / 1024, 1) ?> KB</td>
                                        <td><small><?= htmlspecialchars($file['modified']) ?></small></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php endif; ?>

                        <!-- Troubleshooting Tips -->
                        <div class="alert alert-info mt-4">
                            <h6>Troubleshooting Tips:</h6>
                            <ul class="mb-0">
                                <li>Ensure <code>uploads/</code> folder exists and is writable</li>
                                <li>Check PHP error log: <code>C:\xampp\php\logs\php_error_log</code></li>
                                <li>Verify <code>upload_max_filesize</code> and <code>post_max_size</code> in php.ini</li>
                                <li>Try uploading a small image (< 1 MB) first</li>
                                <li>Check Apache error log: <code>C:\xampp\apache\logs\error.log</code></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
