<?php
require 'db.php';

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

if(!$category_id){
    echo json_encode(['status'=>'error','message'=>'Select category']);
    exit;
}

if(!$name){
    echo json_encode(['status'=>'error','message'=>'Name required']);
    exit;
}

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

$imageName = '';

/* IMAGE UPLOAD */
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);
}

mysqli_query($conn,"
INSERT INTO subcategories(category_id,name,slug,image,sort_order,status)
VALUES($category_id,'$name','$slug','$imageName',$sort,'$status')
");

echo json_encode(['status'=>'success','message'=>'Subcategory added']);