<?php
include("connection.php");
include("header.php");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Simple slug generator
function generateSlug($string)
{
    $slug = preg_replace('/[^A-Za-z0-9-]+/', '-', strtolower($string));
    return trim($slug, '-');
}

$error_message = '';
$valid = 1;

if (isset($_POST['submit'])) {

    // ---- Basic validation ----
    $top_category_id = isset($_POST['top_category_id']) ? (int)$_POST['top_category_id'] : 0;
    $product_name    = trim($_POST['product_name'] ?? '');
    $slug_input      = trim($_POST['slug'] ?? '');

    if ($top_category_id <= 0) {
        $valid = 0;
        $error_message .= "Please select a top category.<br>";
    }

    if ($product_name === '') {
        $valid = 0;
        $error_message .= "Product name cannot be empty.<br>";
    }

    if ($valid == 1) {

        // ---- Slug ----
        $slugBase = $slug_input !== '' ? $slug_input : $product_name;
        $slug     = generateSlug($slugBase);
        $slug     = mysqli_real_escape_string($con, $slug);

        // Ensure slug is unique
        $checkSlug = mysqli_query($con, "SELECT COUNT(*) AS total FROM products WHERE slug = '$slug'");
        $rowSlug   = mysqli_fetch_assoc($checkSlug);
        if ($rowSlug && $rowSlug['total'] > 0) {
            $slug .= '-' . time();
        }

        // ---- Other fields ----
        $product_name        = mysqli_real_escape_string($con, $product_name);
        $product_short_desc  = mysqli_real_escape_string($con, $_POST['product_short_desc'] ?? '');
        $product_line_code   = mysqli_real_escape_string($con, $_POST['product_line_code'] ?? '');
        $description         = mysqli_real_escape_string($con, $_POST['description'] ?? '');
        $technical_spec      = mysqli_real_escape_string($con, $_POST['technical_specification'] ?? '');

        // ---- Image upload paths ----
        $uploadDir = "./assets/images/products/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        // ---- Main image ----
        $mainImageName = null;
        if (isset($_FILES['product_main_image']) && $_FILES['product_main_image']['error'] === UPLOAD_ERR_OK) {
            $originalName   = $_FILES['product_main_image']['name'];
            $tmpName        = $_FILES['product_main_image']['tmp_name'];
            $extension      = pathinfo($originalName, PATHINFO_EXTENSION);
            $mainImageName  = time() . '_' . uniqid('main_') . '.' . $extension;
            $targetMainPath = $uploadDir . $mainImageName;

            if (!move_uploaded_file($tmpName, $targetMainPath)) {
                $mainImageName = null;
            }
        }

        // ---- Gallery images (JSON) ----
        $galleryFiles = [];
        if (!empty($_FILES['product_images']['name'][0])) {
            foreach ($_FILES['product_images']['name'] as $index => $filename) {
                if ($_FILES['product_images']['error'][$index] === UPLOAD_ERR_OK) {
                    $tmpName   = $_FILES['product_images']['tmp_name'][$index];
                    $ext       = pathinfo($filename, PATHINFO_EXTENSION);
                    $unique    = time() . '_' . uniqid('g_') . '.' . $ext;
                    $destPath  = $uploadDir . $unique;

                    if (move_uploaded_file($tmpName, $destPath)) {
                        $galleryFiles[] = $unique;
                    }
                }
            }
        }
        $productImagesJson = !empty($galleryFiles)
            ? mysqli_real_escape_string($con, json_encode($galleryFiles))
            : null;

        // ---- Build SQL (no product_quality column) ----
        $mainImageSql   = $mainImageName      ? "'" . mysqli_real_escape_string($con, $mainImageName) . "'" : "NULL";
        $imagesJsonSql  = $productImagesJson  ? "'" . $productImagesJson . "'" : "NULL";
        $shortDescSql   = $product_short_desc !== '' ? "'$product_short_desc'" : "NULL";
        $lineCodeSql    = $product_line_code  !== '' ? "'$product_line_code'"  : "NULL";
        $descriptionSql = $description        !== '' ? "'$description'" : "NULL";
        $techSpecSql    = $technical_spec     !== '' ? "'$technical_spec'" : "NULL";

        $sql = "INSERT INTO products 
                (top_category_id, product_name, slug, 
                 product_main_image, product_images, 
                 product_short_desc, product_line_code,
                 description, technical_specification)
                VALUES
                ($top_category_id, '$product_name', '$slug',
                 $mainImageSql, $imagesJsonSql,
                 $shortDescSql, $lineCodeSql,
                 $descriptionSql, $techSpecSql)";

        if (mysqli_query($con, $sql)) {
            header("Location: view_product.php");
            exit();
        } else {
            $error_message .= "Database Error: " . mysqli_error($con);
        }
    }
}
?>

<div class="main-content">
    <div class="page-content">
        <div class="container-fluid">

            <!-- start page title -->
            <div class="row">
                <div class="col-12">
                    <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                        <h4 class="mb-sm-0 font-size-18">Add Product</h4>
                    </div>
                </div>
            </div>
            <!-- end page title -->

            <?php if ($error_message != ''): ?>
            <div class="alert alert-danger">
                <?php echo $error_message; ?>
            </div>
            <?php endif; ?>

            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">

                            <form action="" method="POST" enctype="multipart/form-data">

                                <!-- Category + Name + Slug -->
                                <div class="row mb-3">
                                    <div class="col-lg-4">
                                        <label class="form-label">Top Category</label>
                                        <select class="form-select" name="top_category_id" required>
                                            <option value="">Select Top Category</option>
                                            <?php
                                            // order by id so it matches your table order
                                            $catQuery = mysqli_query($con, "SELECT id, name FROM top_categories ORDER BY id ASC");
                                            while ($cat = mysqli_fetch_assoc($catQuery)) {
                                                echo '<option value="' . (int)$cat['id'] . '">'
                                                     . htmlspecialchars($cat['name']) . '</option>';
                                            }
                                            ?>
                                        </select>
                                    </div>

                                    <div class="col-lg-4">
                                        <label class="form-label">Product Name</label>
                                        <input type="text" class="form-control" name="product_name" id="product_name"
                                            placeholder="Enter product name" onkeyup="generateSlug()" required>
                                    </div>

                                    <div class="col-lg-4">
                                        <label class="form-label">Slug</label>
                                        <input type="text" class="form-control" name="slug" id="slug"
                                            placeholder="Auto-generated from name (can edit)">
                                    </div>
                                </div>

                                <!-- Images -->
                                <div class="row mb-3">

                                    <div class="col-lg-3">
                                        <label class="form-label">Product Line Code</label>
                                        <input type="text" class="form-control" name="product_line_code"
                                            placeholder="e.g. AME-001">
                                    </div>
                                    <div class="col-lg-4">
                                        <label class="form-label">Main Product Image</label>
                                        <input type="file" class="form-control" name="product_main_image"
                                            id="product_main_image" accept="image/*">
                                        <small class="text-muted">Recommended: clear front view.</small>
                                        <img id="mainImagePreview" src="#" alt="Main Image Preview"
                                            class="img-thumbnail mt-2" style="max-height:150px; display:none;">
                                    </div>

                                    <div class="col-lg-5">
                                        <label class="form-label">Gallery Images</label>
                                        <input type="file" class="form-control" id="product_images"
                                            name="product_images[]" multiple accept="image/*">
                                        <small class="text-muted">Images will preview automatically. You can remove
                                            before submit.</small>

                                        <!-- Gallery Preview -->
                                        <div id="galleryPreview" class="gallery-preview mt-2"></div>
                                    </div>


                                </div>

                                <!--short desc (CKEditor) -->
                                <div class="mb-3">
                                    <label class="form-label">Short Description</label>
                                    <textarea name="product_short_desc" id="short_desc" rows="6"
                                        class="form-control"></textarea>

                                </div>

                                <!-- CKEditor fields -->
                                <div class="mb-3">
                                    <label class="form-label">Description</label>
                                    <textarea name="description" id="description" rows="6"
                                        class="form-control"></textarea>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Additional Info / Technical Specification</label>
                                    <textarea name="technical_specification" id="technical_specification" rows="6"
                                        class="form-control"></textarea>
                                </div>

                                <div class="text-center mt-4">
                                    <button type="submit" name="submit" class="btn btn-primary">
                                        Submit
                                    </button>
                                    <a href="view_product.php" class="btn btn-danger">
                                        Back to List
                                    </a>
                                </div>

                            </form>

                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <style>
    /* ===== Gallery Preview ===== */
    .gallery-preview {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
    }

    .gallery-item {
        position: relative;
        width: 90px;
        height: 90px;
        border-radius: 6px;
        border: 1px solid #ddd;
        overflow: hidden;
        background: #f8f9fa;
    }

    .gallery-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .gallery-item button {
        position: absolute;
        top: 3px;
        right: 3px;
        background: #dc3545;
        color: #fff;
        border: none;
        width: 22px;
        height: 22px;
        border-radius: 50%;
        font-size: 14px;
        cursor: pointer;
    }
    </style>

    <?php include("footer.php"); ?>
</div>

<!-- CKEditor -->
<script src="./ck editor/ckeditor.js"></script>
<script>
CKEDITOR.replace('short_desc');
CKEDITOR.replace('description');
CKEDITOR.replace('technical_specification');

// Auto slug from product name
function generateSlug() {
    let title = document.getElementById("product_name").value;
    let slug = title.toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '') // remove invalid chars
        .replace(/\s+/g, '-') // spaces to dash
        .replace(/-+/g, '-') // collapse dashes
        .replace(/^-+|-+$/g, ''); // trim dashes
    document.getElementById("slug").value = slug;
}

// Main image preview
const mainInput = document.getElementById('product_main_image');
const mainPreview = document.getElementById('mainImagePreview');

if (mainInput) {
    mainInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) {
            mainPreview.style.display = 'none';
            mainPreview.src = '#';
            return;
        }
        const reader = new FileReader();
        reader.onload = function(event) {
            mainPreview.src = event.target.result;
            mainPreview.style.display = 'block';
        };
        reader.readAsDataURL(file);
    });
}
</script>
<script>
// ===== GALLERY IMAGE PREVIEW & REMOVE =====
const galleryInput = document.getElementById('product_images');
const previewContainer = document.getElementById('galleryPreview');

let selectedGalleryFiles = [];

galleryInput.addEventListener('change', function() {
    for (let file of this.files) {
        selectedGalleryFiles.push(file);
    }
    renderGalleryPreview();
    this.value = ""; // reset input
});

function renderGalleryPreview() {
    previewContainer.innerHTML = "";

    selectedGalleryFiles.forEach((file, index) => {
        const reader = new FileReader();
        reader.onload = function(e) {
            const div = document.createElement("div");
            div.className = "gallery-item";
            div.innerHTML = `
                <img src="${e.target.result}">
                <button type="button" onclick="removeGalleryImage(${index})">&times;</button>
            `;
            previewContainer.appendChild(div);
        };
        reader.readAsDataURL(file);
    });
}

function removeGalleryImage(index) {
    selectedGalleryFiles.splice(index, 1);
    renderGalleryPreview();
}

// Attach filtered images before submit
document.querySelector("form").addEventListener("submit", function() {
    const dataTransfer = new DataTransfer();
    selectedGalleryFiles.forEach(file => dataTransfer.items.add(file));
    galleryInput.files = dataTransfer.files;
});
</script>