<!doctype html> 
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Admin - Products</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <script src="https://cdn.ckeditor.com/ckeditor5/38.1.0/classic/ckeditor.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

<style>
.sortable tr{ cursor:move; }
</style>

</head>
<body>
<body>
<?php 
include "sidebar.php"; 
include "db.php";


function resizeCompress500($src, $dest, $quality = 70) {

    if (!extension_loaded('gd')) {
        move_uploaded_file($src, $dest);
        return;
    }

    $info = getimagesize($src);
    if ($info === false) {
        move_uploaded_file($src, $dest);
        return;
    }

    [$w, $h, $type] = $info;

    $newW = 500;
    $newH = 500;

    $dst = imagecreatetruecolor($newW, $newH);

    switch ($type) {

        case IMAGETYPE_JPEG:
            $srcImg = imagecreatefromjpeg($src);
            imagecopyresampled($dst, $srcImg, 0, 0, 0, 0, $newW, $newH, $w, $h);
            imagejpeg($dst, $dest, $quality);
            break;

        case IMAGETYPE_PNG:
            $srcImg = imagecreatefrompng($src);
            imagealphablending($dst, false);
            imagesavealpha($dst, true);
            imagecopyresampled($dst, $srcImg, 0, 0, 0, 0, $newW, $newH, $w, $h);
            imagepng($dst, $dest, 6);
            break;

        case IMAGETYPE_GIF:
            $srcImg = imagecreatefromgif($src);
            imagecopyresampled($dst, $srcImg, 0, 0, 0, 0, $newW, $newH, $w, $h);
            imagegif($dst, $dest);
            break;

        case IMAGETYPE_WEBP:
            $srcImg = imagecreatefromwebp($src);
            imagecopyresampled($dst, $srcImg, 0, 0, 0, 0, $newW, $newH, $w, $h);
            imagewebp($dst, $dest, $quality);
            break;

        case IMAGETYPE_BMP:
            $srcImg = imagecreatefrombmp($src);
            imagecopyresampled($dst, $srcImg, 0, 0, 0, 0, $newW, $newH, $w, $h);
            imagebmp($dst, $dest);
            break;

        default:
            move_uploaded_file($src, $dest);
            return;
    }

    imagedestroy($srcImg);
    imagedestroy($dst);
}


/* TAGS */
$allTags = ['New Arrival','Best Seller','Deals'];

/* FETCH OPTIONS FOR SELECTS */
$brands = mysqli_query($conn,"SELECT * FROM masters WHERE type='brand' ORDER BY name");
$categories = mysqli_query($conn,"SELECT * FROM masters WHERE type='category' ORDER BY name");
$detection_systems = mysqli_query($conn,"SELECT * FROM masters WHERE type='detection' ORDER BY name");


/* UPLOAD DIRECTORIES */
$uploadDir = __DIR__ . '/../uploads/products/';
$pdfDir    = __DIR__ . '/../uploads/pdfs/';

if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
if (!is_dir($pdfDir)) mkdir($pdfDir, 0777, true);

/* HANDLE DELETE */
if(isset($_GET['delete'])){
    $del_id = $_GET['delete'];
    $row = mysqli_fetch_assoc(mysqli_query($conn,"SELECT main_image,gallery_images,pdf_files FROM products WHERE id='$del_id'"));
    if($row){
        if(!empty($row['main_image']) && file_exists($uploadDir.$row['main_image'])) unlink($uploadDir.$row['main_image']);
        if(!empty($row['gallery_images'])){
            foreach(explode('|',$row['gallery_images']) as $img){
                if(file_exists($uploadDir.$img)) unlink($uploadDir.$img);
            }
        }
        if(!empty($row['pdf_files'])){
            foreach(explode('|',$row['pdf_files']) as $pdf){
                if(file_exists($pdfDir.$pdf)) unlink($pdfDir.$pdf);
            }
        }
    }
    mysqli_query($conn,"DELETE FROM products WHERE id='$del_id'");
    echo "<script>window.location='admin-products.php';</script>";
}

/* HANDLE ADD/EDIT */
$edit_id = $_GET['edit'] ?? null;
$productData = [];
if($edit_id){
    $productData = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM products WHERE id='$edit_id'"));
}

if(isset($_POST['submit'])){
    // Escape all text inputs to avoid SQL errors
    $name = mysqli_real_escape_string($conn, $_POST['product_name']);
    $brand = mysqli_real_escape_string($conn, $_POST['brand']);
    $categories_arr = $_POST['categories'] ?? [];
    $detection_arr = $_POST['detection_systems'] ?? [];
    $short_desc = mysqli_real_escape_string($conn, $_POST['short_desc'] ?? '');
    $description = mysqli_real_escape_string($conn, $_POST['description'] ?? '');
    $features = mysqli_real_escape_string($conn, $_POST['features'] ?? '');
    $specifications = mysqli_real_escape_string($conn, $_POST['specifications'] ?? '');
    $package_content = mysqli_real_escape_string($conn, $_POST['package_content'] ?? '');
    $informations = mysqli_real_escape_string($conn, $_POST['informations'] ?? '');
    $faq = mysqli_real_escape_string($conn, $_POST['faq'] ?? '');
    $youtube = mysqli_real_escape_string($conn, $_POST['youtube_video'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $tags_arr = $_POST['tags'] ?? [];

    $categories_str = mysqli_real_escape_string($conn, implode('|',$categories_arr));
    $detection_str = mysqli_real_escape_string($conn, implode('|',$detection_arr));
    $tags_str = mysqli_real_escape_string($conn, implode('|',$tags_arr));

    /* MAIN IMAGE */
 /* MAIN IMAGE */
$main_img = $productData['main_image'] ?? '';

if(!empty($_FILES['main_image']['name'])){

    // Delete old image while editing
    if($edit_id && !empty($productData['main_image'])){
        $old = $uploadDir.$productData['main_image'];
        if(file_exists($old)) unlink($old);
    }

    $main_img = time().'_'.$_FILES['main_image']['name'];
   resizeCompress500($_FILES['main_image']['tmp_name'], $uploadDir.$main_img);

}


    /* GALLERY IMAGES */
   /* GALLERY IMAGES */
$gallery_imgs = [];

if($edit_id && !empty($productData['gallery_images'])){
    $gallery_imgs = explode('|', $productData['gallery_images']);
}

if(!empty($_FILES['gallery_images']['name'][0])){

    // Delete old gallery images
    if($edit_id){
        foreach($gallery_imgs as $img){
            $old = $uploadDir.$img;
            if(file_exists($old)) unlink($old);
        }
    }

    $gallery_imgs = [];

    foreach($_FILES['gallery_images']['tmp_name'] as $k=>$tmp){
        $filename = time().'_'.$k.'_'.$_FILES['gallery_images']['name'][$k];
       resizeCompress500($tmp, $uploadDir.$filename);

        $gallery_imgs[] = $filename;
    }
}

$gallery_str = !empty($gallery_imgs) ? implode('|',$gallery_imgs) : NULL;


    /* PDF FILES */
  /* PDF FILES */
$pdf_files = [];

if($edit_id && !empty($productData['pdf_files'])){
    $pdf_files = explode('|', $productData['pdf_files']);
}

if(!empty($_FILES['pdf_files']['name'][0])){

    if($edit_id){
        foreach($pdf_files as $pdf){
            $old = $pdfDir.$pdf;
            if(file_exists($old)) unlink($old);
        }
    }

    $pdf_files = [];

    foreach($_FILES['pdf_files']['tmp_name'] as $k=>$tmp){
        $filename = time().'_'.$k.'_'.$_FILES['pdf_files']['name'][$k];
        move_uploaded_file($tmp, $pdfDir.$filename);
        $pdf_files[] = $filename;
    }
}

$pdf_str = !empty($pdf_files) ? implode('|',$pdf_files) : NULL;


    if($edit_id){
$sql = "UPDATE products SET
product_name='$name',
brand='$brand',
categories='".implode('|',$categories_arr)."',
detection_systems='".implode('|',$detection_arr)."',
main_image='$main_img',
gallery_images='$gallery_str',
short_desc='$short_desc',
description='$description',
features='$features',
specifications='$specifications',
package_content='$package_content',
informations='$informations',
faq='$faq',
youtube_video='$youtube',
pdf_files='$pdf_str',
price='$price',
tags='".implode('|',$tags_arr)."',
type='product'
WHERE id='$edit_id'";

        mysqli_query($conn,$sql);
        echo "<div class='alert alert-success mt-2'>Product updated successfully!</div>";
    } else {
       $sql = "INSERT INTO products
(
product_name,
brand,
categories,
detection_systems,
main_image,
gallery_images,
short_desc,
description,
features,
specifications,
package_content,
informations,
faq,
youtube_video,
pdf_files,
price,
tags,
position,
type,
extra_data
)
VALUES
(
'$name',
'$brand',
'".implode('|',$categories_arr)."',
'".implode('|',$detection_arr)."',
'$main_img',
'$gallery_str',
'$short_desc',
'$description',
'$features',
'$specifications',
'$package_content',
'$informations',
'$faq',
'$youtube',
'$pdf_str',
'$price',
'".implode('|',$tags_arr)."',
0,
'product',
NULL
)";

       if(mysqli_query($conn, $sql)){
    echo "<div class='alert alert-success mt-2'>Product added successfully!</div>";
} else {
    echo "<div class='alert alert-danger mt-2'>Database Error: " . mysqli_error($conn) . "</div>";
}

    }
}

/* FETCH EXISTING PRODUCTS */
$where = "WHERE 1";

if(!empty($_GET['search'])){
    $s = mysqli_real_escape_string($conn,$_GET['search']);
    $where .= " AND product_name LIKE '%$s%'";
}

if(!empty($_GET['filter_brand'])){
    $b = mysqli_real_escape_string($conn,$_GET['filter_brand']);
    $where .= " AND brand='$b'";
}

if(!empty($_GET['filter_category'])){
    $c = mysqli_real_escape_string($conn,$_GET['filter_category']);
    $where .= " AND categories LIKE '%$c%'";
}

$products = mysqli_query($conn,"SELECT * FROM products $where ORDER BY position ASC");

?>

<div class="container mt-4">
    <h2>Admin - Products</h2>

    <!-- ADD/EDIT PRODUCT FORM -->
    <form method="POST" enctype="multipart/form-data" class="mb-5">
        <!-- PRODUCT NAME, BRAND, CATEGORY, DETECTION SYSTEMS -->
       <div class="row">
    <div class="col-md-4 mb-3">
        <label>Product Name</label>
        <input type="text" name="product_name" class="form-control" required
               value="<?= $productData['product_name'] ?? '' ?>">
    </div>

    <div class="col-md-4 mb-3">
        <label>Brand</label>
        <div class="d-flex gap-2">
            <select name="brand" class="form-control" required>
                <option value="">-- Select Brand --</option>
                <?php while($b=mysqli_fetch_assoc($brands)){ ?>
                    <option value="<?= $b['name'] ?>"
                        <?= (!empty($productData['brand']) && $productData['brand']==$b['name'])?'selected':'' ?>>
                        <?= $b['name'] ?>
                    </option>
                <?php } ?>
            </select>
           
        </div>
    </div>

    <div class="col-md-4 mb-3">
        <label>Categories</label>
        <select name="categories[]" class="form-control" multiple required>
<?php
$selectedCats = !empty($productData['categories']) ? explode('|',$productData['categories']) : [];
while($c=mysqli_fetch_assoc($categories)){ ?>
    <option value="<?= $c['name'] ?>"
        <?= in_array($c['name'],$selectedCats)?'selected':'' ?>>
        <?= $c['name'] ?>
    </option>
<?php } ?>
</select>

       
    </div>
</div>


        <!-- DETECTION SYSTEMS, MAIN IMAGE, GALLERY IMAGES -->
<div class="row">
    <div class="col-md-4 mb-3">
        <label>Detection Systems</label>
       <select name="detection_systems[]" class="form-control" multiple required>
<?php
$selectedDet = !empty($productData['detection_systems']) ? explode('|',$productData['detection_systems']) : [];
while($d=mysqli_fetch_assoc($detection_systems)){ ?>
    <option value="<?= $d['name'] ?>"
        <?= in_array($d['name'],$selectedDet)?'selected':'' ?>>
        <?= $d['name'] ?>
    </option>
<?php } ?>
</select>

      
    </div>

    <div class="col-md-4 mb-3">
        <label>Main Image</label>
        <input type="file" name="main_image" class="form-control">
        <?php if(!empty($productData['main_image'])){ ?>
            <img src="../uploads/products/<?= $productData['main_image'] ?>" class="img-thumbnail mt-2" width="100">


        <?php } ?>
    </div>

    <div class="col-md-4 mb-3">
        <label>Gallery Images</label>
        <input type="file" name="gallery_images[]" class="form-control" multiple>
        <div class="mt-2">
            <?php if(!empty($productData['gallery_images'])){
                foreach(explode('|',$productData['gallery_images']) as $g){ ?>
                 <img src="../uploads/products/<?= $g ?>" class="img-thumbnail me-1 mb-1" width="60">

            <?php }} ?>
        </div>
    </div>
</div>

        <!-- PDF FILES, YOUTUBE, PRICE -->
<div class="row">
    <div class="col-md-4 mb-3">
        <label>PDF Files</label>
        <input type="file" name="pdf_files[]" class="form-control" multiple>
    </div>

    <div class="col-md-4 mb-3">
        <label>YouTube Video ID</label>
        <input type="text" name="youtube_video" class="form-control"
               value="<?= $productData['youtube_video'] ?? '' ?>">
    </div>

    <div class="col-md-4 mb-3">
        <label>Price</label>
        <input type="number" step="0.01" name="price" class="form-control" required
               value="<?= $productData['price'] ?? '' ?>">
    </div>
</div>


        <!-- TAGS -->
        <div class="mb-3">
            <label>Tags</label><br>
            <?php 
            $selectedTags = !empty($productData['tags']) ? explode('|',$productData['tags']) : [];
            foreach($allTags as $tag){ ?>
                <input type="checkbox" name="tags[]" value="<?= $tag ?>" <?= in_array($tag,$selectedTags)?'checked':'' ?>> <?= $tag ?>&nbsp;
            <?php } ?>
        </div>

        <!-- TEXTAREAS WITH CKEDITOR -->
        <?php 
        $fields = ['short_desc'=>'Short Description','description'=>'Description','features'=>'Features','specifications'=>'Specifications','package_content'=>'Package Content','informations'=>'Informations','faq'=>'FAQ'];
        foreach($fields as $id=>$label){ ?>
        <div class="mb-3">
            <label><?= $label ?></label>
            <textarea name="<?= $id ?>" id="<?= $id ?>" class="form-control"><?= $productData[$id] ?? '' ?></textarea>
        </div>
        <?php } ?>

       <button type="submit" name="submit" class="btn btn-primary mt-3">
    <?= isset($_GET['edit']) ? 'Update Product' : 'Add Product' ?>
</button>

    </form>

    <!-- EXISTING PRODUCTS TABLE -->
    <h3>Existing Products</h3>
<a href="admin-products.php" class="btn btn-success mb-3">
    + Add New Product
</a>

<form method="get" class="row g-2 mb-3">
<div class="col-md-3">
   <input type="text" id="searchInput" class="form-control"
          placeholder="Search product">
</div>

<div class="col-md-3">
    <select id="brandFilter" class="form-control">
        <option value="">-- All Brands --</option>
        <?php
        $bq = mysqli_query($conn,"SELECT * FROM masters WHERE type='brand' ORDER BY name");
        while($b=mysqli_fetch_assoc($bq)){
            echo "<option value='{$b['name']}'>{$b['name']}</option>";
        }
        ?>
    </select>
</div>

<div class="col-md-3">
    <select id="categoryFilter" class="form-control">
        <option value="">-- All Categories --</option>
        <?php
        $cq = mysqli_query($conn,"SELECT * FROM masters WHERE type='category' ORDER BY name");
        while($c=mysqli_fetch_assoc($cq)){
            echo "<option value='{$c['name']}'>{$c['name']}</option>";
        }
        ?>
    </select>
</div>


    <div class="col-md-3">
      
        <a href="admin-products.php" class="btn btn-secondary">Reset</a>
    </div>
</form>

    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Brand</th>
                <th>Categories</th>
                <th>Detection Systems</th>
                <th>Tags</th>
                <th>Price</th>
                <th>Actions</th>
            </tr>
        </thead>
       <tbody class="sortable">

            <?php while($p=mysqli_fetch_assoc($products)){ ?>
            
          <tr id="row_<?= $p['id'] ?>">
    <td><?= $p['id'] ?></td>
    <td><?= $p['product_name'] ?></td>
    <td><?= $p['brand'] ?></td>
    <td><?= str_replace('|',' | ',$p['categories']) ?></td>
    <td><?= str_replace('|',' | ',$p['detection_systems']) ?></td>
    <td><?= str_replace('|',' | ',$p['tags']) ?></td>
    <td>₹ <?= $p['price'] ?></td>
    <td>
        <a href="?edit=<?= $p['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
        <a href="?delete=<?= $p['id'] ?>" class="btn btn-sm btn-danger"
           onclick="return confirm('Delete this product?')">Delete</a>
    </td>
</tr>

            <?php } ?>
        </tbody>
    </table>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const ckFields = ['short_desc','description','features','specifications','package_content','informations','faq'];

    ckFields.forEach(id => {
        const el = document.querySelector('#' + id);
        if(el){
         ClassicEditor.create(el, {
    toolbar: [
        'heading', '|', 'bold', 'italic', 'link',
        'bulletedList', 'numberedList',
        '|', 'insertTable', 'blockQuote', 'undo', 'redo', 'imageUpload'
    ],
    ckfinder: {
        uploadUrl: 'upload-ck.php' // relative path is correct
    }
})
.catch(error => console.error(error));

        }
    });
});



</script>


<script>
$(".sortable").sortable({
    update:function(){
        let ids=[];
        $(".sortable tr").each(function(){
            ids.push($(this).attr("id").replace("row_",""));
        });

        $.post("update-position.php",{
            ids:ids,
            table:"products"
        });
    }
});
</script>

<script>
function loadProducts(){
    let search   = $("#searchInput").val();
    let brand    = $("#brandFilter").val();
    let category = $("#categoryFilter").val();

    $.get("ajax-search-products.php",{
        search: search,
        brand: brand,
        category: category
    }, function(data){
        $(".sortable").html(data);

        $(".sortable").sortable({
            update:function(){
                let ids=[];
                $(".sortable tr").each(function(){
                    ids.push($(this).attr("id").replace("row_",""));
                });

                $.post("update-position.php",{
                    ids:ids,
                    table:"products"
                });
            }
        });
    });
}

let typingTimer;
const delay = 400;

$("#searchInput").on("keyup", function(){
    clearTimeout(typingTimer);
    typingTimer = setTimeout(loadProducts, delay);
});

$("#brandFilter, #categoryFilter").on("change", function(){
    loadProducts();
});
</script>

