<?php
try {

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

    include_once dirname(__DIR__, 2) . "/config/dbcon.php";
    include_once dirname(__DIR__, 2) . "/helpers/api_helper.php";

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(405, "Method Not Allowed");
    }

    $categoryName  = $_POST['category_name'] ?? null;
    $categoryImage = $_FILES['category_image'] ?? null;

    
    if (!$categoryName) {
        sendResponse(400, "Category Name is required");
    }

    $fileName = null;

   
    if ($categoryImage && $categoryImage['error'] === 0) {

        $allowedTypes = ['jpg', 'jpeg', 'png', 'webp'];
        $ext = strtolower(pathinfo($categoryImage['name'], PATHINFO_EXTENSION));
        $maxSize = 2 * 1024 * 1024; // 2MB

        if (!in_array($ext, $allowedTypes)) {
            sendResponse(400, "Invalid image type");
        }

        if ($categoryImage['size'] > $maxSize) {
            sendResponse(400, "File size must be less than 2MB");
        }

        $upload_path = dirname(__DIR__, 2) . "/uploads/category_icon/";
        $fileName = time() . "_" . uniqid() . "." . $ext;

        if (!move_uploaded_file($categoryImage['tmp_name'], $upload_path . $fileName)) {
            sendResponse(400, "File uploading error");
        }
    }

    // INSERT (image can be NULL)
    $stmt = $conn->prepare(
        "INSERT INTO categories (category_name, category_image)
         VALUES (?, ?)"
    );
    $stmt->execute([$categoryName, $fileName]);

    sendResponse(200, "Category added successfully");

} catch (PDOException $e) {
    sendResponse(500, "Server Error");
}
