<?php
session_start();
include('includes/config.php');

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

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $catId     = isset($_POST['catId']) ? intval($_POST['catId']) : 0;
        $catCode   = trim($_POST['catCode']);
        $catName   = trim($_POST['catName']);
        // $catStatus = isset($_POST['catStatus']) ? intval($_POST['catStatus']) : 1;

        if (empty($catCode) || empty($catName)) {
            echo json_encode(['status' => 'error', 'message' => 'Category code and name are required']);
            exit;
        }

        if ($catId > 0) {
            // ✅ Update existing category
            $sql = "UPDATE tblcategory 
                    SET CategoryCode = :catCode, CategoryName = :catName 
                    WHERE id = :catId";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':catCode', $catCode);
            $stmt->bindParam(':catName', $catName);
            // $stmt->bindParam(':catStatus', $catStatus);
            $stmt->bindParam(':catId', $catId);
            $stmt->execute();

            echo json_encode(['status' => 'success', 'message' => 'Category updated successfully']);
            exit;
        } else {
            // ✅ Insert new category
            $sql = "INSERT INTO tblcategory (CategoryCode, CategoryName) 
                    VALUES (:catCode, :catName)";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':catCode', $catCode);
            $stmt->bindParam(':catName', $catName);
            $stmt->execute();

            echo json_encode(['status' => 'success', 'message' => 'Category added successfully']);
            exit;
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
