<?php
include "connection.php";
header("Content-Type: application/json");

$response = ["status" => false, "message" => ""];

try {
    $json = file_get_contents("php://input");
    $data = json_decode($json, true);

    $title = $data['title'] ?? null;
    $description = $data['description'] ?? null;
    $imageBase64 = $data['image'] ?? null;
    $status = $data['status'] ?? null;
    $category_id = $data["category_id"] ?? null;

    if (!$title) throw new Exception("Please enter category title.");
    if (!$description) throw new Exception("Please enter description.");
    if (!$status) throw new Exception("Please Select Status");

    $imgPath = null;

    // If image is provided, process and save it
    if (!empty($imageBase64)) {
        if (preg_match('/^data:image\/(\w+);base64,/', $imageBase64, $type)) {
            $imageBase64 = substr($imageBase64, strpos($imageBase64, ',') + 1);
            $type = strtolower($type[1]); // jpg, png, gif

            if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) throw new Exception("Invalid image type.");

            $imageBase64 = base64_decode($imageBase64);
            if ($imageBase64 === false) throw new Exception("Base64 decode failed.");

            $uploadDir = "../uploads/categories/";
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

            $fileName = time() . "." . $type;
            $filePath = $uploadDir . $fileName;
            file_put_contents($filePath, $imageBase64);

            $imgPath = "uploads/categories/" . $fileName;
        } else {
            throw new Exception("Invalid image format.");
        }
    }

    $rs = Database::search("SELECT * FROM `category` WHERE `id` = '" . $category_id . "' ");
    $rows = $rs->num_rows;

    if ($rows > 0) {
        // Update category (with or without image)
        if ($imgPath) {
            Database::iud("UPDATE `category` SET 
                `title` = '" . $title . "', 
                `description` = '" . $description . "', 
                `img_path` = '" . $imgPath . "' , `category_status_id` = '" . $status . "'
                WHERE `id` = '" . $category_id . "' ");
        } else {
            Database::iud("UPDATE `category` SET 
                `title` = '" . $title . "', 
                `description` = '" . $description . "' , `category_status_id` = '" . $status . "' 
                WHERE `id` = '" . $category_id . "' ");
        }

        $response["status"] = true;
        $response["message"] = "Category updated successfully!";
    } else {
        // Insert new category
        if (!$imgPath) throw new Exception("Image is required for new category.");

        Database::iud("INSERT INTO `category` (`title`, `description`, `img_path`,`category_status_id`)
            VALUES ('" . $title . "', '" . $description . "', '" . $imgPath . "','" . $status . "')");

        $response["status"] = true;
        $response["message"] = "Category added successfully!";
    }
} catch (Exception $e) {
    $response["message"] = $e->getMessage();
}

echo json_encode($response);
exit;
