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

$response = ["status" => "error", "message" => "Unknown error"];

$tableId   = $_POST['tableid'] ?? $_GET['tableid'] ?? '';
$categoryId   = $_POST['id'] ?? $_GET['id'] ?? '';
$categoryName = $_POST['name'] ?? '';
$categoryStatus = $_POST['status'] ?? '';

// Insert values
$newCode = $_POST['newcode'] ?? '';
$newName = $_POST['newname'] ?? '';

try {
    if ($tableId !== '' && $categoryStatus !== '' && $categoryName !== '') {
        // 🔹 Update Category
        $sql = "UPDATE tblcategory 
                SET Status = :categoryStatus, CategoryName = :name 
                WHERE id = :id";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':categoryStatus', $categoryStatus);
        $stmt->bindParam(':name', $categoryName);
        $stmt->bindParam(':id', $tableId);

        if ($stmt->execute()) {
            $response = ["status" => "success", "message" => "Category updated successfully"];
        } else {
            $response = ["status" => "error", "message" => "Failed to update category"];
        }
    } elseif ($newCode && $newName) {
        // 🔹 Insert Category
        $sql = "INSERT INTO tblcategory (CategoryCode, CategoryName) 
                VALUES (:code, :name)";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':code', $newCode);
        $stmt->bindParam(':name', $newName);

        if ($stmt->execute()) {
            $response = ["status" => "success", "message" => "Category inserted successfully"];
        } else {
            $response = ["status" => "error", "message" => "Failed to insert category"];
        }
    } else if ($categoryId) {
        // 🔹 Delete Category
        $sql = "DELETE from tblcategory 
                WHERE id = :id";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':id', $categoryId);

        if ($stmt->execute()) {
            $response = ["status" => "success", "message" => "Category Deleted successfully"];
        } else {
            $response = ["status" => "error", "message" => "Failed to update category"];
        }
    } else {
        // 🔹 Fetch all Categories
        $sql = "SELECT id, CategoryCode, CategoryName, Status, CreationDate, UpdationDate 
                FROM tblcategory 
                ORDER BY CategoryName ASC";
        $stmt = $dbh->prepare($sql);
        $stmt->execute();

        $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($categories) {
            $response = ["status" => "success", "data" => $categories];
        } else {
            $response = ["status" => "error", "message" => "No categories found"];
        }
    }
} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
}

echo json_encode($response);
exit;
