<?php
require 'db.php';

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

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/categories/";
    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);
}

if($id){

    $sql = "
        UPDATE categories
        SET name='$name',
            slug='$slug',
            sort_order=$sort,
            status='$status'
    ";

    if($imageName){
        $sql .= ", image='$imageName'";
    }

    $sql .= " WHERE id=".(int)$id;

    mysqli_query($conn,$sql);

    echo json_encode(['status'=>'success','message'=>'Category updated']);

}else{

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

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