<?php
@ini_set('upload_max_filesize', '5000M');
@ini_set('post_max_size', '5000M');
@ini_set('max_execution_time', '0');
@ini_set('max_input_time', '0');
@ini_set('memory_limit', '-1');

require_once 'header.php';

$success = ''; 
$error = '';
$is_ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST) && empty($_FILES) && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 0) {
    $error = "The uploaded file exceeds the maximum allowed size configured on your server's php.ini file.";
    if($is_ajax) {
        if(ob_get_length()) ob_clean();
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => $error]);
        exit;
    }
}

$prod_dir = '../uploads/products/images/';
$file_dir = '../uploads/products/files/';
$screens_dir = '../uploads/products/screenshots/';

if (!is_dir($prod_dir)) mkdir($prod_dir, 0777, true);
if (!is_dir($file_dir)) mkdir($file_dir, 0777, true);
if (!is_dir($screens_dir)) mkdir($screens_dir, 0777, true);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_product'])) {
    $title           = trim($_POST['title']);
    $category_id     = (int)$_POST['category_id'];
    $price           = filter_var($_POST['price'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
    $old_price       = filter_var($_POST['old_price'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
    $setup_video     = trim($_POST['setup_video_url']);
    $description     = trim($_POST['description']);
    $meta_title      = trim($_POST['meta_title']);
    $meta_desc       = trim($_POST['meta_description']);
    $meta_keywords   = trim($_POST['meta_keywords']);
    
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));

    if (empty($title) || empty($category_id)) {
        $error = "Title and Category are required.";
    } elseif (!empty($_FILES['main_image']['name'])) {
        
        $img_ext = strtolower(pathinfo($_FILES['main_image']['name'], PATHINFO_EXTENSION));
        
        $file_name = null;
        $file_upload_success = true;
        
        if(isset($_FILES['download_file']) && !empty($_FILES['download_file']['name'])) {
            $file_ext = strtolower(pathinfo($_FILES['download_file']['name'], PATHINFO_EXTENSION));
            if (in_array($file_ext, ['zip', 'rar'])) {
                $file_name = 'source_' . time() . '.' . $file_ext;
                if (!move_uploaded_file($_FILES['download_file']['tmp_name'], $file_dir . $file_name)) {
                    $file_upload_success = false;
                    $error = "Failed to upload ZIP/RAR file.";
                }
            } else {
                $file_upload_success = false;
                $error = "Source file must be ZIP/RAR.";
            }
        }
        
        if (in_array($img_ext, ['jpg', 'jpeg', 'png', 'webp']) && $file_upload_success) {
            
            $img_name = 'img_' . time() . '.' . $img_ext;

            if (move_uploaded_file($_FILES['main_image']['tmp_name'], $prod_dir . $img_name)) {
                
                try {
                    $pdo->beginTransaction();
                    
                    $stmt = $pdo->prepare("INSERT INTO products (category_id, title, slug, old_price, price, main_image, download_file, setup_video_url, description, meta_title, meta_description, meta_keywords, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')");
                    $stmt->execute([$category_id, $title, $slug, $old_price, $price, $img_name, $file_name, $setup_video, $description, $meta_title, $meta_desc, $meta_keywords]);
                    $product_id = $pdo->lastInsertId();

                    if (!empty($_FILES['screenshots']['name'][0])) {
                        $files = $_FILES['screenshots'];
                        $count = count($files['name']);
                        if($count > 10) $count = 10;

                        $stmt_sc = $pdo->prepare("INSERT INTO product_screenshots (product_id, image) VALUES (?, ?)");

                        for ($i = 0; $i < $count; $i++) {
                            if ($files['error'][$i] === 0) {
                                $sc_ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
                                if (in_array($sc_ext, ['jpg', 'jpeg', 'png', 'webp'])) {
                                    $sc_name = 'sc_' . time() . '_' . $i . '.' . $sc_ext;
                                    if (move_uploaded_file($files['tmp_name'][$i], $screens_dir . $sc_name)) {
                                        $stmt_sc->execute([$product_id, $sc_name]);
                                    }
                                }
                            }
                        }
                    }

                    $pdo->commit();
                    
                    if($is_ajax) {
                         if(ob_get_length()) ob_clean();
                         header('Content-Type: application/json');
                         echo json_encode(['status' => 'success', 'message' => 'Product Published Successfully!']);
                         exit;
                    }

                    $success = "Product Published Successfully!";
                } catch (PDOException $e) {
                    $pdo->rollBack();
                    if($is_ajax) {
                         if(ob_get_length()) ob_clean();
                         header('Content-Type: application/json');
                         echo json_encode(['status' => 'error', 'message' => "Database Error: " . $e->getMessage()]);
                         exit;
                    }
                    $error = "Database Error: " . $e->getMessage();
                }
            } else {
                if(!$error) $error = "Failed to upload main image.";
            }
        } else {
            if(!$error) $error = "Main Image must be JPG/PNG/WEBP.";
        }
    } else {
        $error = "Please upload a Main Image.";
    }
    
    if($is_ajax && $error) {
        if(ob_get_length()) ob_clean();
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => $error]);
        exit;
    }
}

$categories = $pdo->query("SELECT * FROM categories ORDER BY name ASC")->fetchAll();
?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
<script>
    $(document).ready(function() {
        $('#description').summernote({
            placeholder: 'Write product description here... You can use bold, colors, highlights, and formatting.',
            tabsize: 2,
            height: 350,
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline', 'clear']],
                ['color', ['color']], /* Highlight & Text Color Tool */
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture', 'video']],
                ['view', ['fullscreen', 'codeview', 'help']]
            ]
        });
    });
</script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<style>
    :root {
        --primary: #84cc16; 
        --primary-hover: #65a30d;
        --bg-light: #f8fafc;
        --card-bg: #ffffff;
        --border: #e2e8f0;
        --text-main: #1e293b;
        --text-muted: #64748b;
    }

    body { background: var(--bg-light); color: var(--text-main); font-family: 'Inter', sans-serif; margin: 0;}
    
    .settings-container { max-width: 900px; margin: 0 auto; padding: 20px; }

    .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; flex-wrap: wrap; gap: 15px; }
    .page-title { font-size: 1.5rem; font-weight: 800; color: var(--text-main); margin: 0; }
    
    .btn-back { 
        background: #f1f5f9; color: var(--text-main); padding: 8px 15px; border-radius: 6px; 
        text-decoration: none; font-size: 0.9rem; font-weight: 600; border: 1px solid var(--border); 
        display: inline-flex; align-items: center; gap: 6px; transition: 0.2s; 
    }
    .btn-back:hover { background: #e2e8f0; }

    .admin-card { 
        background: var(--card-bg); border-radius: 12px; padding: 25px; 
        border: 1px solid var(--border); margin-bottom: 20px; box-shadow: none; 
    }

    .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 5px; }
    .form-group { margin-bottom: 20px; }
    .form-label { display: block; font-size: 0.9rem; font-weight: 700; margin-bottom: 8px; color: var(--text-main); }
    
    .form-control { 
        width: 100%; padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; 
        font-size: 0.95rem; transition: 0.2s; box-sizing: border-box; background: transparent;
    }
    .form-control:focus { border-color: var(--primary); outline: none; }
    
    .file-upload-box {
        border: 2px dashed var(--border); padding: 20px 15px; border-radius: 8px;
        text-align: center; background: #fafafa; cursor: pointer; position: relative; transition: 0.3s ease;
    }
    .file-upload-box:hover { border-color: var(--primary); background: #f4fce3; }
    .file-upload-box input[type="file"] {
        position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer;
    }
    .file-icon { color: var(--text-muted); margin-bottom: 10px; transition: 0.3s; }
    .file-upload-box:hover .file-icon { color: var(--primary); }

    .new-preview-img { max-width: 120px; max-height: 100px; object-fit: contain; border-radius: 6px; border: 2px solid var(--primary); display: block; background: #fff; margin-top: 10px;}
    .new-file-badge { font-size: 0.85rem; color: #3b82f6; font-weight: 700; display: inline-block; padding: 6px 12px; background: #eff6ff; border-radius: 6px; margin-top: 10px; border: 1px solid #bfdbfe;}

    .sc-grid { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px; }
    .sc-item { position: relative; border: 1px solid var(--border); border-radius: 6px; padding: 4px; background: #fff; border-color: var(--primary); }
    .sc-item img { width: 70px; height: 70px; object-fit: cover; display: block; border-radius: 4px; }

    .btn-submit { 
        background: var(--primary); color: white; padding: 14px 28px; border: none; 
        border-radius: 8px; font-weight: 700; font-size: 1rem; cursor: pointer; 
        display: flex; align-items: center; justify-content: center; gap: 8px; 
        transition: 0.3s; width: 100%; margin-top: 10px; box-shadow: none;
    }
    .btn-submit:hover { background: var(--primary-hover); transform: none; }
    .btn-submit:disabled { background: #94a3b8; cursor: not-allowed; }

    .progress-wrapper {
        display: none;
        margin-top: 25px;
        margin-bottom: 15px;
        background: #f1f5f9;
        border-radius: 10px;
        overflow: hidden;
        border: 1px solid var(--border);
        height: 35px;
        position: relative;
        box-shadow: inset 0 2px 4px rgba(0,0,0,0.05);
    }
    .progress-bar {
        height: 100%;
        background: var(--primary);
        width: 0%;
        transition: width 0.3s ease;
        position: absolute;
        top: 0; left: 0;
        background-image: linear-gradient(45deg, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent);
        background-size: 1rem 1rem;
        animation: progress-animation 1s linear infinite;
    }
    @keyframes progress-animation {
        from { background-position: 1rem 0; }
        to { background-position: 0 0; }
    }
    .progress-percentage {
        position: absolute;
        width: 100%;
        text-align: center;
        line-height: 35px;
        color: #1e293b;
        font-weight: 800;
        font-size: 0.95rem;
        z-index: 2;
        mix-blend-mode: difference;
        color: white;
    }
    .progress-text {
        text-align: center;
        font-size: 0.85rem;
        color: var(--text-main);
        margin-top: 8px;
        font-weight: 700;
    }

    .section-title {
        font-size: 1.1rem;
        font-weight: 700;
        color: #0f172a;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e2e8f0;
    }

    @media (max-width: 768px) {
        .form-grid { grid-template-columns: 1fr; gap: 0; }
        .page-header { flex-direction: column; align-items: flex-start; }
        .admin-card { padding: 20px 15px; }
        .settings-container { padding: 15px; }
    }
</style>

<div class="settings-container">
    <div class="page-header">
        <h1 class="page-title">Upload New Product</h1>
        <a href="manage-products.php" class="btn-back">
            <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
            Back to List
        </a> 
    </div>

    <div class="admin-card">
        <form id="addProductForm" action="" method="POST" enctype="multipart/form-data" accept-charset="UTF-8">
            <input type="hidden" name="add_product" value="1">
            
            <div class="section-title">Basic Information</div>
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Product Title *</label>
                    <input type="text" name="title" class="form-control" placeholder="e.g. Premium App Source Code" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Category *</label>
                    <select name="category_id" class="form-control" required>
                        <option value="">Select Category</option>
                        <?php foreach($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Old Price</label>
                    <input type="number" step="0.01" name="old_price" class="form-control" placeholder="0.00">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Sale Price *</label>
                    <input type="number" step="0.01" name="price" class="form-control" placeholder="0.00" required>
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">Setup / Tutorial Video URL (Optional)</label>
                <input type="url" name="setup_video_url" class="form-control" placeholder="https://youtu.be/xxxxxx">
            </div>

            <div class="form-group">
                <label class="form-label">Product Description</label>
                <textarea id="description" name="description" class="form-control" placeholder="Write details about the script, features, installation guide etc."></textarea>
            </div>

            <div class="section-title" style="margin-top: 30px;">Media & Files</div>
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Main Thumbnail (JPG/PNG/WEBP) *</label>
                    <div class="file-upload-box">
                        <svg class="file-icon" width="30" height="30" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                        <div style="font-weight: 600; font-size: 0.9rem; color: var(--text-main);">Click to Upload Main Image</div>
                        <input type="file" id="main_image_input" name="main_image" accept="image/*" required>
                    </div>
                    <div id="main_image_preview"></div>
                </div>

                <div class="form-group">
                    <label class="form-label">Source Code (ZIP/RAR) (Optional)</label>
                    <div class="file-upload-box">
                        <svg class="file-icon" width="30" height="30" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                        <div style="font-weight: 600; font-size: 0.9rem; color: var(--text-main);">Click to Upload ZIP/RAR</div>
                        <input type="file" id="zip_file" name="download_file" accept=".zip,.rar">
                    </div>
                    <div id="zip_file_preview"></div>
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">Product Screenshots (Optional, Max 10)</label>
                <div class="file-upload-box" style="padding: 15px;">
                    <svg class="file-icon" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" style="margin-bottom: 5px;"><path stroke-linecap="round" stroke-linejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
                    <div style="font-weight: 600; font-size: 0.85rem; color: var(--text-main);">Select multiple images</div>
                    <input type="file" id="screenshots_input" name="screenshots[]" accept="image/*" multiple>
                </div>
                <div id="screenshots_preview" class="sc-grid"></div>
            </div>

            <div class="section-title" style="margin-top: 30px;">Professional SEO Settings</div>
            
            <div class="form-group">
                <label class="form-label">Meta Title (For Google & Facebook Share)</label>
                <input type="text" name="meta_title" class="form-control" placeholder="Leave empty to use Product Title">
                <small style="color: var(--text-muted); font-size: 0.8rem;">Optimal length: 50-60 characters</small>
            </div>

            <div class="form-group">
                <label class="form-label">Meta Description</label>
                <textarea name="meta_description" class="form-control" rows="3" placeholder="Brief, catchy description for search results and social media shares."></textarea>
                <small style="color: var(--text-muted); font-size: 0.8rem;">Optimal length: 150-160 characters</small>
            </div>
            
            <div class="form-group">
                <label class="form-label">Meta Keywords</label>
                <input type="text" name="meta_keywords" class="form-control" placeholder="e.g. app source code, buy script, android template">
                <small style="color: var(--text-muted); font-size: 0.8rem;">Separate with commas</small>
            </div>

            <div id="progressWrapper" class="progress-wrapper">
                <div id="progressBar" class="progress-bar"></div>
                <div id="progressPercentage" class="progress-percentage">0%</div>
            </div>
            <div id="progressText" class="progress-text"></div>

            <button type="submit" id="submitBtn" class="btn-submit">
                <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                Publish Product
            </button>

        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
<script>
    <?php if($success && !isset($_SERVER['HTTP_X_REQUESTED_WITH'])): ?>
    Toastify({
        text: "<?php echo addslashes($success); ?>",
        duration: 3000,
        gravity: "top", 
        position: "center",
        className: "toast-success",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>

    <?php if($error && !isset($_SERVER['HTTP_X_REQUESTED_WITH'])): ?>
    Toastify({
        text: "<?php echo addslashes($error); ?>",
        duration: 5000,
        gravity: "top", 
        position: "center",
        className: "toast-error",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>

    document.getElementById('main_image_input').addEventListener('change', function(e) {
        const preview = document.getElementById('main_image_preview');
        preview.innerHTML = '';
        if (this.files && this.files[0]) {
            const file = this.files[0];
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.className = 'new-preview-img';
                    preview.appendChild(img);
                }
                reader.readAsDataURL(file);
            }
        }
    });

    document.getElementById('zip_file').addEventListener('change', function(e) {
        const preview = document.getElementById('zip_file_preview');
        preview.innerHTML = '';
        if (this.files && this.files[0]) {
            const file = this.files[0];
            const sizeMB = (file.size / (1024 * 1024)).toFixed(2);
            preview.innerHTML = `<span class="new-file-badge">
                <svg style="width:14px; height:14px; display:inline-block; vertical-align:middle; margin-right:4px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
                Selected: ${file.name} (${sizeMB} MB)
            </span>`;
        }
    });

    document.getElementById('screenshots_input').addEventListener('change', function(e) {
        const preview = document.getElementById('screenshots_preview');
        preview.innerHTML = '';
        if (this.files) {
            Array.from(this.files).forEach(file => {
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const div = document.createElement('div');
                        div.className = 'sc-item';
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        div.appendChild(img);
                        preview.appendChild(div);
                    }
                    reader.readAsDataURL(file);
                }
            });
        }
    });

    document.getElementById('addProductForm').addEventListener('submit', function(e) {
        // Ensure Summernote value is copied to textarea
        if (typeof $ !== 'undefined' && $.fn.summernote) {
            $('#description').val($('#description').summernote('code'));
        }

        let fileInput = document.getElementById('zip_file');
        let imgInput = document.getElementById('main_image_input');
        
        let hasFiles = (fileInput.files.length > 0) || (imgInput.files.length > 0);

        if(hasFiles) {
            e.preventDefault();
            
            let formData = new FormData(this);
            let xhr = new XMLHttpRequest();
            
            let progressWrapper = document.getElementById('progressWrapper');
            let progressBar = document.getElementById('progressBar');
            let progressPercentage = document.getElementById('progressPercentage');
            let progressText = document.getElementById('progressText');
            let submitBtn = document.getElementById('submitBtn');

            progressWrapper.style.display = 'block';
            submitBtn.disabled = true;
            submitBtn.innerHTML = 'Uploading... Please wait';

            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    let percentComplete = Math.round((e.loaded / e.total) * 100);
                    progressBar.style.width = percentComplete + '%';
                    progressPercentage.innerHTML = percentComplete + '%';
                    
                    let loadedMB = (e.loaded / (1024 * 1024)).toFixed(2);
                    let totalMB = (e.total / (1024 * 1024)).toFixed(2);
                    progressText.innerHTML = `Uploading Files: ${loadedMB} MB / ${totalMB} MB (${percentComplete}%)`;
                }
            });

            xhr.addEventListener('load', function() {
                if (xhr.status == 200) {
                    try {
                        let response = JSON.parse(xhr.responseText);
                        if(response.status === 'success') {
                            progressBar.style.backgroundColor = '#10b981';
                            progressText.innerHTML = 'Upload complete! Redirecting...';
                            Toastify({text: response.message, duration: 2000, backgroundColor: "#10b981", gravity: "top", position: "center"}).showToast();
                            setTimeout(() => { window.location.href = 'manage-products.php'; }, 1500);
                        } else {
                            progressWrapper.style.display = 'none';
                            submitBtn.disabled = false;
                            submitBtn.innerHTML = '<svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg> Publish Product';
                            Toastify({text: response.message, duration: 5000, backgroundColor: "#ef4444", gravity: "top", position: "center"}).showToast();
                        }
                    } catch(e) {
                        window.location.href = 'manage-products.php';
                    }
                } else {
                    progressWrapper.style.display = 'none';
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg> Publish Product';
                    Toastify({text: "An error occurred during upload. The file may exceed server POST limits.", duration: 5000, backgroundColor: "#ef4444", gravity: "top", position: "center"}).showToast();
                }
            });

            xhr.addEventListener('error', function() {
                progressWrapper.style.display = 'none';
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg> Publish Product';
                Toastify({text: "Network error occurred during upload.", duration: 5000, backgroundColor: "#ef4444", gravity: "top", position: "center"}).showToast();
            });

            xhr.open('POST', window.location.href, true);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.send(formData);
        }
    });
</script>

<?php require_once 'footer.php'; ?>
