<?php
/**
 * ================================================================
 * VENDOR ITEM FORM - COMPLETE REWRITE
 * ================================================================
 * File: vendor/item-form.php
 * Add or edit rental items
 * ================================================================
 */

require_once '../app/Core/init.php';
require_once '../app/Core/Mailer.php';

// Require vendor authentication
Auth::requireVendor();

// Initialize models
$vendor = new Vendor();
$item   = new Item();
$category = new Category();

// Get vendor details
$vendor_id   = Auth::id();
$vendor_data = $vendor->getByUserId($vendor_id);

if (!$vendor_data) {
    flash('error', 'Please complete your profile first.', 'danger');
    redirect('profile.php');
}

// Check if editing
$item_id    = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$is_editing = $item_id > 0;
$item_data  = null;

if ($is_editing) {
    $item_data = $item->find($item_id);

    // Verify ownership
    if (!$item_data || $item_data['vendor_id'] != $vendor_data['id']) {
        flash('error', 'Item not found or access denied.', 'danger');
        redirect('items.php');
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Validate CSRF token
    if (!Security::validateToken($_POST['csrf_token'] ?? '')) {
        flash('error', 'Invalid security token. Please try again.', 'danger');
        redirect($_SERVER['PHP_SELF'] . ($is_editing ? '?id=' . $item_id : ''));
    }

    // Collect and clean input data
    $data = [
        'vendor_id'          => $vendor_data['id'],
        'category_id'        => (int)($_POST['category_id'] ?? 0),
        'title'              => Security::clean($_POST['title'] ?? ''),
        'description'        => Security::clean($_POST['description'] ?? ''),
        'price_per_day'      => (float)($_POST['price_per_day'] ?? 0),
        'security_deposit'   => (float)($_POST['security_deposit'] ?? 0),
        'quantity'           => (int)($_POST['quantity'] ?? 1),
        'available_quantity' => (int)($_POST['quantity'] ?? 1),
        'condition_status'   => Security::clean($_POST['condition_status'] ?? 'good'),
        'location'           => Security::clean($_POST['location'] ?? ''),
        'city'               => Security::clean($_POST['city'] ?? ''),
        'state'              => Security::clean($_POST['state'] ?? ''),
        'features'           => Security::clean($_POST['features'] ?? ''),
        'terms_and_conditions' => Security::clean($_POST['terms_and_conditions'] ?? ''),
    ];

    // Generate slug from title
    $data['slug'] = generate_slug($data['title']);

    // Validation
    $errors = [];

    if (empty($data['title'])) {
        $errors[] = 'Item title is required';
    }

    if ($data['category_id'] <= 0) {
        $errors[] = 'Please select a category';
    }

    if (empty($data['description'])) {
        $errors[] = 'Item description is required';
    } elseif (strlen($data['description']) < 50) {
        $errors[] = 'Description must be at least 50 characters';
    }

    if ($data['price_per_day'] <= 0) {
        $errors[] = 'Price per day must be greater than 0';
    }

    if ($data['quantity'] <= 0) {
        $errors[] = 'Quantity must be at least 1';
    }

    if (empty($data['city'])) {
        $errors[] = 'City is required';
    }

    if (empty($data['state'])) {
        $errors[] = 'State is required';
    }

    // ================================================================
    // HANDLE MAIN IMAGE UPLOAD
    // ================================================================
    $main_image_uploaded    = false;
    $uploaded_main_filename = '';

    if (isset($_FILES['main_image']) && $_FILES['main_image']['error'] === UPLOAD_ERR_OK) {
        $image_validation = Security::validateFile($_FILES['main_image'], ALLOWED_IMAGE_TYPES, MAX_FILE_SIZE);

        if ($image_validation['success']) {
            $image_result = Upload::uploadImage($_FILES['main_image'], 'items');

            if ($image_result['success'] && !empty($image_result['filename'])) {
                $uploaded_main_filename = $image_result['filename'];
                $main_image_uploaded    = true;

                error_log("✓ Main image uploaded: {$uploaded_main_filename} for vendor {$vendor_data['id']}");

                // Delete old image if editing
                if ($is_editing && !empty($item_data['main_image'])) {
                    Upload::deleteFile('items/' . $item_data['main_image']);
                    error_log("✓ Deleted old main image: {$item_data['main_image']}");
                }
            } else {
                $errors[] = $image_result['message'] ?? 'Failed to upload main image';
                error_log("✗ Main image upload failed: " . ($image_result['message'] ?? 'Unknown'));
            }
        } else {
            $errors[] = $image_validation['message'];
            error_log("✗ Main image validation failed: {$image_validation['message']}");
        }
    } elseif (!$is_editing) {
        // Main image required for new items only
        $errors[] = 'Main image is required';
    }

    // Add main_image to data if uploaded
    if ($main_image_uploaded) {
        $data['main_image'] = $uploaded_main_filename;
    }

    // ================================================================
    // PROCESS IF NO ERRORS
    // ================================================================
    if (empty($errors)) {
        $result          = false;
        $success_message = '';

        if ($is_editing) {
            // ============================================================
            // EDITING EXISTING ITEM
            // ============================================================
            $old_data = $item_data;
            $changes  = [];

            // Compare tracked fields — store BOTH old and new values
            $tracked_fields = [
                'title', 'description', 'price_per_day', 'security_deposit',
                'quantity', 'condition_status', 'location', 'city', 'state',
                'features', 'terms_and_conditions',
            ];

            foreach ($tracked_fields as $field) {
                $old_value = $old_data[$field] ?? null;
                $new_value = $data[$field]     ?? null;

                if (is_numeric($old_value)) $old_value = (float)$old_value;
                if (is_numeric($new_value)) $new_value = (float)$new_value;

                if ($old_value != $new_value) {
                    // Store both old and new so the review page can compare correctly
                    $changes[$field] = [
                        'old' => $old_value,
                        'new' => $new_value,
                    ];
                }
            }

            // Prepare update data
            $update_data = [];
            foreach ($data as $key => $value) {
                if ($key !== 'vendor_id') {
                    $update_data[$key] = $value;
                }
            }

            // Only include main_image if it was uploaded
            if (!$main_image_uploaded) {
                unset($update_data['main_image']);
            }

            // Track significant field changes
            if (!empty($changes)) {
                $update_reason = Security::clean($_POST['update_reason'] ?? '');
                $item->trackUpdate($item_id, $vendor_data['id'], $changes, $update_reason);
                $item->update($item_id, ['updates_pending' => 1]);
                $success_message = 'Item updated! Changes submitted for admin approval.';

                // ── Notify admin about the update ──────────────────────
                try {
                    $db            = Database::getInstance();
                    $category_row  = $db->fetch("SELECT name FROM categories WHERE id = ?", [$item_data['category_id']]);
                    $mailer        = new Mailer();
                    $mailer->sendNewItemNotification(
                        $item_id,
                        $data['title'],
                        $category_row['name'] ?? 'N/A',
                        $data['price_per_day'],
                        $vendor_data['business_name'],
                        $vendor_data['email'] ?? '',
                        date('Y-m-d H:i:s')
                    );
                } catch (Exception $mail_e) {
                    error_log("Admin notification email failed (item update): " . $mail_e->getMessage());
                }
                // ──────────────────────────────────────────────────────

            } elseif ($main_image_uploaded) {
                $success_message = 'Item image updated successfully!';
            } else {
                $success_message = 'No changes detected.';
            }

            // Perform the update
            $result = $item->update($item_id, $update_data);

            // Reset rejected status
            if ($item_data['approval_status'] === 'rejected') {
                $item->update($item_id, ['approval_status' => 'pending']);
                $success_message .= ' Re-submitted for approval.';
            }

            error_log("✓ Item {$item_id} updated" . ($main_image_uploaded ? " with new image: {$uploaded_main_filename}" : ""));

        } else {
            // ============================================================
            // CREATING NEW ITEM
            // ============================================================
            $data['approval_status'] = 'pending';
            $data['status']          = 'pending';

            $result = $item->create($data);

            if ($result) {
                $item_id         = $result; // new item ID
                $success_message = 'Item created and submitted for approval!';
                error_log("✓ New item created: ID {$item_id}, main_image: {$uploaded_main_filename}");

                // ── Notify admin about the new item ────────────────────
                try {
                    $db           = Database::getInstance();
                    $category_row = $db->fetch("SELECT name FROM categories WHERE id = ?", [$data['category_id']]);
                    $mailer       = new Mailer();
                    $mailer->sendNewItemNotification(
                        $item_id,
                        $data['title'],
                        $category_row['name'] ?? 'N/A',
                        $data['price_per_day'],
                        $vendor_data['business_name'],
                        $vendor_data['email'] ?? '',
                        date('Y-m-d H:i:s')
                    );
                } catch (Exception $mail_e) {
                    error_log("Admin notification email failed (new item): " . $mail_e->getMessage());
                }
                // ──────────────────────────────────────────────────────

            } else {
                $errors[] = 'Failed to create item in database';
                error_log("✗ Item creation failed for vendor {$vendor_data['id']}");
            }
        }

        // ================================================================
        // HANDLE ADDITIONAL IMAGES (for both create and edit)
        // ================================================================
        if ($result && isset($_FILES['additional_images']) && !empty($_FILES['additional_images']['name'][0])) {
            $uploaded_count = 0;
            $failed_count   = 0;
            $max_additional = 5;
            $db             = Database::getInstance();

            foreach ($_FILES['additional_images']['tmp_name'] as $key => $tmp_name) {
                if ($uploaded_count >= $max_additional) break;

                if ($_FILES['additional_images']['error'][$key] === UPLOAD_ERR_OK) {
                    $file = [
                        'name'     => $_FILES['additional_images']['name'][$key],
                        'type'     => $_FILES['additional_images']['type'][$key],
                        'tmp_name' => $tmp_name,
                        'error'    => $_FILES['additional_images']['error'][$key],
                        'size'     => $_FILES['additional_images']['size'][$key],
                    ];

                    $validation = Security::validateFile($file, ALLOWED_IMAGE_TYPES, MAX_FILE_SIZE);
                    if (!$validation['success']) {
                        error_log("✗ Additional image validation failed: {$validation['message']}");
                        $failed_count++;
                        continue;
                    }

                    $img_result = Upload::uploadImage($file, 'items');

                    if ($img_result['success'] && !empty($img_result['filename'])) {
                        try {
                            $img_sql   = "INSERT INTO item_images (item_id, image_path, display_order, created_at) VALUES (?, ?, ?, NOW())";
                            $db_result = $db->execute($img_sql, [$item_id, $img_result['filename'], $uploaded_count]);

                            if ($db_result) {
                                $uploaded_count++;
                                error_log("✓ Additional image saved: {$img_result['filename']} for item {$item_id}");
                            } else {
                                error_log("✗ DB insert failed for: {$img_result['filename']}");
                                Upload::deleteFile('items/' . $img_result['filename']);
                                $failed_count++;
                            }
                        } catch (Exception $e) {
                            error_log("✗ Exception saving image: " . $e->getMessage());
                            Upload::deleteFile('items/' . $img_result['filename']);
                            $failed_count++;
                        }
                    } else {
                        error_log("✗ Additional image upload failed: " . ($img_result['message'] ?? 'Unknown'));
                        $failed_count++;
                    }
                }
            }

            if ($uploaded_count > 0) {
                $success_message .= " ({$uploaded_count} additional image" . ($uploaded_count > 1 ? 's' : '') . " uploaded)";
            }
            if ($failed_count > 0) {
                $success_message .= " ({$failed_count} failed)";
            }
        }

        // ================================================================
        // SUCCESS - REDIRECT
        // ================================================================
        if ($result) {
            flash('success', $success_message, 'success');
            redirect('items.php');
        } else {
            flash('error', 'Operation failed. Please try again.', 'danger');
        }

    } else {
        // ================================================================
        // VALIDATION ERRORS
        // ================================================================
        foreach ($errors as $error) {
            flash('error', $error, 'danger');
        }
        $_SESSION['old'] = $data;
    }
}

// ================================================================
// GET DATA FOR FORM DISPLAY
// ================================================================
$categories = $category->getActive();

$nigerian_states = [
    'Abia', 'Adamawa', 'Akwa Ibom', 'Anambra', 'Bauchi', 'Bayelsa', 'Benue', 'Borno', 'Cross River',
    'Delta', 'Ebonyi', 'Edo', 'Ekiti', 'Enugu', 'FCT', 'Gombe', 'Imo', 'Jigawa', 'Kaduna', 'Kano',
    'Katsina', 'Kebbi', 'Kogi', 'Kwara', 'Lagos', 'Nasarawa', 'Niger', 'Ogun', 'Ondo', 'Osun',
    'Oyo', 'Plateau', 'Rivers', 'Sokoto', 'Taraba', 'Yobe', 'Zamfara',
];

// Get existing additional images if editing
$additional_images = [];
if ($is_editing) {
    $db        = Database::getInstance();
    $img_sql   = "SELECT * FROM item_images WHERE item_id = ? ORDER BY display_order";
    $additional_images = $db->fetchAll($img_sql, [$item_id]);
}

$page_title  = $is_editing ? 'Edit Item' : 'Add New Item';
$active_menu = 'items';

include '../templates/layouts/vendor/header.php';
?>

<!-- AJAX IMAGE DELETION -->
<style>
.delete-image-btn {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    font-size: 12px;
    opacity: 0.8;
    transition: all 0.3s ease;
    border: 2px solid #fff;
    background: #dc3545;
}
.delete-image-btn:hover {
    opacity: 1;
    transform: scale(1.1);
    background: #c82333;
}
.additional-image-item {
    transition: opacity 0.3s ease;
    position: relative;
}
.additional-image-item img {
    object-fit: cover;
    height: 120px;
    width: 100%;
    border: 2px solid #dee2e6;
}
.additional-image-item:hover img { border-color: #007bff; }
.spinner-border { z-index: 10; }
</style>

<div class="main-content">
    <div class="page-header">
        <div class="header-left">
            <a href="items.php" class="btn btn-secondary me-3">
                <i class="fas fa-arrow-left"></i> Back
            </a>
            <div>
                <h1><i class="fas fa-<?= $is_editing ? 'edit' : 'plus' ?>"></i> <?= $page_title ?></h1>
                <p class="text-muted">Fill in the details about your rental item</p>
            </div>
        </div>
    </div>

    <?php if ($is_editing && $item_data['approval_status'] === 'rejected'): ?>
        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle"></i>
            <strong>This item was rejected:</strong>
            <?php if ($item_data['rejection_reason'] != '') echo htmlspecialchars($item_data['rejection_reason']); ?>
            <br><small>Make the necessary changes and submit for re-approval.</small>
        </div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">

        <div class="row">
            <!-- Main Form -->
            <div class="col-lg-8">
                <!-- Basic Information -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-info-circle"></i> Basic Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Item Title <span class="text-danger">*</span></label>
                            <input type="text" name="title" class="form-control"
                                   value="<?= esc($item_data['title'] ?? old('title')) ?>"
                                   placeholder="e.g., Professional DSLR Camera with Lens"
                                   required>
                            <small class="text-muted">Be specific and descriptive</small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Category <span class="text-danger">*</span></label>
                            <select name="category_id" class="form-control" required>
                                <option value="">Select category</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?= $cat['id'] ?>"
                                            <?= ($item_data['category_id'] ?? old('category_id')) == $cat['id'] ? 'selected' : '' ?>>
                                        <?= esc($cat['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Description <span class="text-danger">*</span></label>
                            <textarea name="description" class="form-control" rows="6" required
                                      placeholder="Describe your item in detail..."><?= esc($item_data['description'] ?? old('description')) ?></textarea>
                            <small class="text-muted">Minimum 50 characters. Be detailed to attract more customers.</small>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Condition <span class="text-danger">*</span></label>
                                <select name="condition_status" class="form-control" required>
                                    <option value="new"      <?= ($item_data['condition_status'] ?? 'good') === 'new'      ? 'selected' : '' ?>>Brand New</option>
                                    <option value="like_new" <?= ($item_data['condition_status'] ?? 'good') === 'like_new' ? 'selected' : '' ?>>Like New</option>
                                    <option value="good"     <?= ($item_data['condition_status'] ?? 'good') === 'good'     ? 'selected' : '' ?>>Good</option>
                                    <option value="fair"     <?= ($item_data['condition_status'] ?? 'good') === 'fair'     ? 'selected' : '' ?>>Fair</option>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Quantity Available <span class="text-danger">*</span></label>
                                <input type="number" name="quantity" class="form-control"
                                       value="<?= esc($item_data['quantity'] ?? old('quantity', 1)) ?>"
                                       min="1" required>
                                <small class="text-muted">How many units do you have?</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Pricing -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-tag"></i> Pricing</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Price per Day (₦) <span class="text-danger">*</span></label>
                                <input type="number" name="price_per_day" class="form-control"
                                       value="<?= esc($item_data['price_per_day'] ?? old('price_per_day')) ?>"
                                       min="1" step="0.01" required>
                                <small class="text-muted">Daily rental rate</small>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Security Deposit (₦)</label>
                                <input type="number" name="security_deposit" class="form-control"
                                       value="<?= esc($item_data['security_deposit'] ?? old('security_deposit', 0)) ?>"
                                       min="0" step="0.01">
                                <small class="text-muted">Refundable deposit (optional)</small>
                            </div>
                        </div>

                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            Platform commission: <strong><?= PLATFORM_COMMISSION ?>%</strong> will be deducted from your earnings.
                        </div>
                    </div>
                </div>

                <!-- Location -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-map-marker-alt"></i> Location</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Specific Location/Address</label>
                            <input type="text" name="location" class="form-control"
                                   value="<?= esc($item_data['location'] ?? old('location')) ?>"
                                   placeholder="e.g., Shop 5, Plaza Building">
                            <small class="text-muted">Optional: Specific pickup location</small>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">City <span class="text-danger">*</span></label>
                                <input type="text" name="city" class="form-control"
                                       value="<?= esc($item_data['city'] ?? old('city', $vendor_data['city'])) ?>"
                                       required>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">State <span class="text-danger">*</span></label>
                                <select name="state" class="form-control" required>
                                    <option value="">Select state</option>
                                    <?php foreach ($nigerian_states as $state): ?>
                                        <option value="<?= $state ?>"
                                                <?= ($item_data['state'] ?? old('state', $vendor_data['state'])) === $state ? 'selected' : '' ?>>
                                            <?= $state ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Additional Details -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-list"></i> Additional Details</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Features &amp; Specifications</label>
                            <textarea name="features" class="form-control" rows="4"
                                      placeholder="List key features, specifications, included accessories, etc."><?= esc($item_data['features'] ?? old('features')) ?></textarea>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Terms &amp; Conditions</label>
                            <textarea name="terms_and_conditions" class="form-control" rows="4"
                                      placeholder="Rental terms, usage rules, damage policy, etc."><?= esc($item_data['terms_and_conditions'] ?? old('terms_and_conditions')) ?></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="col-lg-4">
                <!-- Main Image -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-image"></i> Main Image <span class="text-danger">*</span></h5>
                    </div>
                    <div class="card-body">
                        <?php if ($is_editing && !empty($item_data['main_image'])): ?>
                            <img src="<?= upload('items/' . $item_data['main_image']) ?>"
                                 alt="Current image"
                                 class="img-fluid rounded mb-3"
                                 id="currentMainImage">
                        <?php endif; ?>

                        <input type="file" name="main_image" class="form-control"
                               accept="image/*"
                               <?= !$is_editing ? 'required' : '' ?>
                               onchange="previewMainImage(this)">
                        <small class="text-muted">High-quality image. JPG, PNG. Max 5MB</small>

                        <img id="mainImagePreview" class="img-fluid rounded mt-3" style="display: none;">
                    </div>
                </div>

                <!-- Additional Images -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-images"></i> Additional Images</h5>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($additional_images)): ?>
                            <div class="mb-3">
                                <label class="form-label">Current Images:</label>
                                <div class="row g-2" id="additionalImagesContainer">
                                    <?php foreach ($additional_images as $img): ?>
                                        <div class="col-6 col-md-4 position-relative additional-image-item" data-image-id="<?= $img['id'] ?>">
                                            <img src="<?= upload('items/' . $img['image_path']) ?>"
                                                 class="img-fluid rounded"
                                                 alt="Additional image">
                                            <button type="button"
                                                    class="btn btn-danger btn-sm position-absolute top-0 end-0 m-1 delete-image-btn"
                                                    data-image-id="<?= $img['id'] ?>"
                                                    data-image-path="<?= $img['image_path'] ?>"
                                                    title="Delete this image">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            <div class="position-absolute top-50 start-50 translate-middle spinner-border text-primary d-none"
                                                 role="status" style="width:2rem;height:2rem;">
                                                <span class="visually-hidden">Loading...</span>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <input type="file" name="additional_images[]" class="form-control"
                               accept="image/*" multiple>
                        <small class="text-muted">Upload up to 5 additional images. Hold Ctrl/Cmd to select multiple.</small>
                    </div>
                </div>

                <!-- Submit Button -->
                <div class="card">
                    <div class="card-body">
                        <button type="submit" class="btn btn-primary btn-lg w-100 mb-2">
                            <i class="fas fa-<?= $is_editing ? 'save' : 'plus' ?>"></i>
                            <?= $is_editing ? 'Update Item' : 'Add Item' ?>
                        </button>

                        <a href="items.php" class="btn btn-outline-secondary w-100">
                            <i class="fas fa-times"></i> Cancel
                        </a>

                        <?php if (!$is_editing): ?>
                            <div class="alert alert-info mt-3 mb-0">
                                <small>
                                    <i class="fas fa-info-circle"></i>
                                    Your item will be submitted for admin approval before going live.
                                </small>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
function previewMainImage(input) {
    const preview = document.getElementById('mainImagePreview');
    const current = document.getElementById('currentMainImage');
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
            if (current) current.style.display = 'none';
        };
        reader.readAsDataURL(input.files[0]);
    }
}

document.addEventListener('DOMContentLoaded', function () {
    document.addEventListener('click', function (e) {
        if (e.target.closest('.delete-image-btn')) {
            const button    = e.target.closest('.delete-image-btn');
            const imageId   = button.getAttribute('data-image-id');
            const imagePath = button.getAttribute('data-image-path');
            const imageItem = button.closest('.additional-image-item');
            deleteImage(imageId, imagePath, imageItem, button);
        }
    });
});

function deleteImage(imageId, imagePath, imageItem, button) {
    const spinner   = imageItem.querySelector('.spinner-border');
    button.classList.add('d-none');
    spinner.classList.remove('d-none');
    button.disabled = true;

    const csrfToken = document.querySelector('input[name="csrf_token"]').value;

    fetch('ajax_delete_item_image.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ image_id: imageId, image_path: imagePath, csrf_token: csrfToken })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            imageItem.style.opacity    = '0';
            imageItem.style.transition = 'opacity 0.3s ease';
            setTimeout(() => {
                imageItem.remove();
                const container = document.getElementById('additionalImagesContainer');
                if (container && container.children.length === 0) {
                    container.innerHTML = '<div class="col-12"><p class="text-muted">No additional images</p></div>';
                }
                showFlashMessage('Image deleted successfully!', 'success');
            }, 300);
        } else {
            showFlashMessage(data.message || 'Failed to delete image', 'danger');
            button.classList.remove('d-none');
            spinner.classList.add('d-none');
            button.disabled = false;
        }
    })
    .catch(() => {
        showFlashMessage('An error occurred while deleting the image', 'danger');
        button.classList.remove('d-none');
        spinner.classList.add('d-none');
        button.disabled = false;
    });
}

function showFlashMessage(message, type = 'info') {
    document.querySelectorAll('.custom-flash-message').forEach(a => a.remove());
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show custom-flash-message`;
    alertDiv.innerHTML = `${message}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
    const form = document.querySelector('form');
    form.insertBefore(alertDiv, form.firstChild);
    setTimeout(() => { if (alertDiv.parentNode) alertDiv.remove(); }, 5000);
}
</script>

<?php
unset($_SESSION['old']);
// include '../templates/layouts/vendor/footer.php';
?>