<?php
require 'db.php';

$id = (int)($_POST['id'] ?? 0);
$category_id = (int)($_POST['category_id'] ?? 0);
$name = trim($_POST['name'] ?? '');
$sort = (int)($_POST['sort_order'] ?? 1);
$status = $_POST['status'] ?? 'active';

if(!$id){
    echo json_encode(['status'=>'error','message'=>'Invalid ID']);
    exit;
}

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

$imageSQL = '';

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

    $uploadDir = "../uploads/subcategories/";

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

    $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    $imageName = time().rand(111,999).".".$ext;

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

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

$update = mysqli_query($conn,"
UPDATE subcategories
SET category_id=$category_id,
    name='$name',
    slug='$slug',
    sort_order=$sort,
    status='$status'
    $imageSQL
WHERE id=$id
");

if($update){
    echo json_encode(['status'=>'success','message'=>'Subcategory updated']);
}else{
    echo json_encode(['status'=>'error','message'=>'Update failed']);
}