<?php
include "db.php";
$type = "brand";
$uploadDir = "../uploads/";

function uploadBrandImage($file, $uploadDir) {
    $tmp = $file['tmp_name'];

    $info = getimagesize($tmp);
    if ($info === false) {
        die("Invalid image file");
    }

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

    $ext = image_type_to_extension($type, false); // jpg, png, gif, webp, etc.
    $name = time() . "_brand_" . pathinfo($file['name'], PATHINFO_FILENAME) . "." . $ext;
    $path = $uploadDir . $name;

    switch ($type) {
        case IMAGETYPE_JPEG:
            $src = imagecreatefromjpeg($tmp);
            imagejpeg($src, $path, 70);
            break;

        case IMAGETYPE_PNG:
            $src = imagecreatefrompng($tmp);
            imagealphablending($src, false);
            imagesavealpha($src, true);
            imagepng($src, $path, 6); // compression level 0–9
            break;

        case IMAGETYPE_GIF:
            $src = imagecreatefromgif($tmp);
            imagegif($src, $path);
            break;

        case IMAGETYPE_WEBP:
            $src = imagecreatefromwebp($tmp);
            imagewebp($src, $path, 70);
            break;

        case IMAGETYPE_BMP:
            $src = imagecreatefrombmp($tmp);
            imagebmp($src, $path);
            break;

        default:
            die("Unsupported image format");
    }

    imagedestroy($src);
    return $name;
}


/* ADD */
if(isset($_POST['add'])){
   $name = mysqli_real_escape_string($conn,$_POST['name']);
$image = uploadBrandImage($_FILES['image'],$uploadDir);

mysqli_query($conn,"INSERT INTO masters(type,name,image,position,status)
VALUES('$type','$name','$image',0,1)");

    header("Location: admin-brands.php");
    exit;
}

/* UPDATE */
if(isset($_POST['update'])){
    $id = $_POST['id'];
    $name = mysqli_real_escape_string($conn,$_POST['name']);

$old = mysqli_fetch_assoc(mysqli_query($conn,"SELECT image FROM masters WHERE id='$id'"));
$image = $old['image'];

if(!empty($_FILES['image']['name'])){
    if(file_exists($uploadDir.$old['image'])){
        unlink($uploadDir.$old['image']);
    }
    $image = uploadBrandImage($_FILES['image'],$uploadDir);
}

mysqli_query($conn,"UPDATE masters SET name='$name', image='$image' WHERE id='$id'");

    header("Location: admin-brands.php");
    exit;
}

/* DELETE */
if(isset($_GET['del'])){
   $old = mysqli_fetch_assoc(mysqli_query($conn,"SELECT image FROM masters WHERE id=".$_GET['del']));
if(file_exists($uploadDir.$old['image'])){
    unlink($uploadDir.$old['image']);
}
mysqli_query($conn,"DELETE FROM masters WHERE id=".$_GET['del']);

    header("Location: admin-brands.php");
    exit;
}

/* STATUS TOGGLE */
if(isset($_GET['status'])){
    $id = $_GET['id'];
    $st = $_GET['status']==1 ? 0 : 1;
    mysqli_query($conn,"UPDATE masters SET status='$st' WHERE id='$id'");
    header("Location: admin-brands.php");
    exit;
}

/* EDIT FETCH */
$editData = null;
if(isset($_GET['edit'])){
    $editData = mysqli_fetch_assoc(
        mysqli_query($conn,"SELECT * FROM masters WHERE id=".$_GET['edit'])
    );
}

/* FETCH */
$data = mysqli_query($conn,"SELECT * FROM masters WHERE type='$type' ORDER BY position ASC");
?>
<!doctype html>
<html>
<head>
<title>Brands</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<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>

<?php include "sidebar.php"; ?>

<div class="container mt-4">

<h3>Brands (Drag to Sort)</h3>

<!-- ADD / EDIT FORM -->
<form method="post" enctype="multipart/form-data" class="row g-2 mb-3">

    <input type="hidden" name="id" value="<?= $editData['id'] ?? '' ?>">

    <div class="col-md-4">
    <input name="name" class="form-control" placeholder="Brand name"
           value="<?= $editData['name'] ?? '' ?>" required>
</div>

<div class="col-md-4">
    <input type="file" name="image" class="form-control" <?= isset($editData)?'':'required' ?>>
    <?php if(!empty($editData['image'])){ ?>
        <img src="../uploads/<?= $editData['image'] ?>" width="80" class="mt-2">
    <?php } ?>
</div>


    <div class="col-md-2">
        <?php if(isset($editData)){ ?>
            <button name="update" class="btn btn-warning w-100">Update</button>
            <a href="admin-brands.php" class="btn btn-secondary w-100 mt-1">Cancel</a>
        <?php } else { ?>
            <button name="add" class="btn btn-primary w-100">Add</button>
        <?php } ?>
    </div>
</form>

<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Image</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>

<tbody class="sortable">
<?php while($r=mysqli_fetch_assoc($data)){ ?>
<tr id="row_<?= $r['id'] ?>">
<td><?= $r['id'] ?></td>
<td><?= $r['name'] ?></td>
<td><img src="../uploads/<?= $r['image'] ?>" width="60"></td>

<td>
<a href="?status=<?= $r['status'] ?>&id=<?= $r['id'] ?>"
   class="btn btn-sm <?= $r['status']?'btn-success':'btn-secondary' ?>">
   <?= $r['status']?'Active':'Inactive' ?>
</a>
</td>

<td>
<a href="?edit=<?= $r['id'] ?>" class="btn btn-warning btn-sm">Edit</a>
<a href="?del=<?= $r['id'] ?>" class="btn btn-danger btn-sm"
   onclick="return confirm('Delete this brand?')">Delete</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>

</div>

<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:"masters"
        });
    }
});
</script>

</body>
</html>
