<?php
include 'db.php';

header('Content-Type: application/json');

$id = intval($_POST['id'] ?? 0);
$name = trim($_POST['name'] ?? '');
$sort_order = intval($_POST['sort_order'] ?? 1);
$status = $_POST['status'] ?? 'inactive';

if ($id <= 0 || $name == '') {
    echo json_encode(['status'=>'error','message'=>'Invalid data']);
    exit;
}

$slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));

$imageSQL = "";

/* GET OLD IMAGE */
$res = mysqli_query($conn,"SELECT image FROM categories WHERE id=$id");
$old = mysqli_fetch_assoc($res);

/* IMAGE UPLOAD */
if(!empty($_FILES['image']['name'])){

    $uploadDir = "../uploads/categories/";
    if(!is_dir($uploadDir)){
        mkdir($uploadDir,0777,true);
    }

    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg','jpeg','png','webp'];

    if(!in_array($ext,$allowed)){
        echo json_encode(['status'=>'error','message'=>'Invalid image type']);
        exit;
    }

    /* delete old image */
    if(!empty($old['image']) && file_exists($uploadDir.$old['image'])){
        unlink($uploadDir.$old['image']);
    }

    $imageName = time().rand(111,999).".".$ext;

    move_uploaded_file($_FILES['image']['tmp_name'],$uploadDir.$imageName);

    $imageSQL = ", image='$imageName'";
}

$sql = "
UPDATE categories
SET name='$name',
    slug='$slug',
    sort_order=$sort_order,
    status='$status'
    $imageSQL
WHERE id=$id
";

if(mysqli_query($conn,$sql)){
    echo json_encode(['status'=>'success','message'=>'Category updated']);
}else{
    echo json_encode(['status'=>'error','message'=>'Update failed']);
}