<?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");
        exit;
    }

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


    if (!$id) {
        sendResponse(400, "id is required");
        exit;
    }

    if (!$categoryName && !$categoryImage) {
        sendResponse(400, "name or icon is required");
        exit;
    }



    $stmt = $conn->prepare(
        "SELECT category_image FROM categories WHERE id = ?"
    );
    $stmt->execute([$id]);
    $category = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$category) {
        sendResponse(404, "Category not found");
        exit;
    }


    $fileName = $category['category_image'];


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

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

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

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

        $upload_path = dirname(__DIR__, 2) . "/uploads/category_icon/";


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

        $newFileName = time() . "_" . uniqid() . "." . $ext;

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

        // delete old icon
        if ($fileName && file_exists($upload_path . $fileName)) {
            unlink($upload_path . $fileName);
        }

        $fileName = $newFileName;
    }

    if ($categoryName !== null) {

        $stmt = $conn->prepare(
            "UPDATE categories SET category_name = ?, category_image = ? WHERE id = ?"
        );
        $stmt->execute([$categoryName, $fileName, $id]);
    } else {
        $stmt = $conn->prepare(
            "UPDATE categories SET category_image = ? WHERE id = ?"
        );
        $stmt->execute([$fileName, $id]);
    }
    sendResponse(200, "Category updated successfully");
    exit;

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