<?php
// delete_category.php
require_once 'db_connect.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    if (isset($_POST['id'])) {
        $id = $_POST['id']; // Matches @Field("id")

        // Optional: Delete the image file from server first
        // $getImgSql = "SELECT image FROM categories WHERE id = ?";
        // ... (Image deletion logic if you want it) ...

        // Delete from DB
        $sql = "DELETE FROM categories WHERE id = ?";
        
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("i", $id);
            
            if ($stmt->execute()) {
                if ($stmt->affected_rows > 0) {
                    echo json_encode(array("status" => "success", "message" => "Category deleted"));
                } else {
                    echo json_encode(array("status" => "error", "message" => "Category ID not found"));
                }
            } else {
                // Check if the error is due to Foreign Key Constraint (e.g., products still exist in this category)
                if ($conn->errno == 1451) {
                    echo json_encode(array("status" => "error", "message" => "Cannot delete: Products exist in this category."));
                } else {
                    echo json_encode(array("status" => "error", "message" => "SQL Error: " . $stmt->error));
                }
            }
            $stmt->close();
        } else {
            echo json_encode(array("status" => "error", "message" => "Prepare Error"));
        }
    } else {
        echo json_encode(array("status" => "error", "message" => "Missing ID"));
    }
}
$conn->close();
?>