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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // Receive ID from Android @Field("id")
    $id = isset($_POST['id']) ? $_POST['id'] : 0;

    if (!empty($id)) {
        $sql = "DELETE FROM brands 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" => "Brand deleted successfully"));
                } else {
                    echo json_encode(array("status" => "error", "message" => "Brand ID not found in database"));
                }
            } else {
                // Handle foreign key constraint error (if products are using this brand)
                if ($conn->errno == 1451) {
                    echo json_encode(array("status" => "error", "message" => "Cannot delete: Products are still assigned to this brand."));
                } else {
                    echo json_encode(array("status" => "error", "message" => "SQL Error: " . $stmt->error));
                }
            }
            $stmt->close();
        } else {
            echo json_encode(array("status" => "error", "message" => "Failed to prepare statement"));
        }
    } else {
        echo json_encode(array("status" => "error", "message" => "Brand ID is missing"));
    }
} else {
    echo json_encode(array("status" => "error", "message" => "Invalid request method"));
}
$conn->close();
?>