<?php
ob_start();

include_once '../includes/constants.php';
include_once '../includes/functions.php';

$partners = new partners();
$partners->connection($host, $user, $pass, $db);

// Retrieve and sanitize input
$categorycompo = trim($_POST['categorycompo'] ?? '');

if ($categorycompo === "Choose a Category" || $categorycompo === "") {
    $msg = "Select a category to delete!";
    header("Location: index.php?Act=category&msg=" . urlencode($msg));
    exit;
}

// Check if category is in use by affiliates
$stmt1 = $partners->conn->prepare("SELECT 1 FROM partners_affiliate WHERE affiliate_category = ?");
$stmt1->bind_param("s", $categorycompo);
$stmt1->execute();
$res1 = $stmt1->get_result();
$aff_exists = $res1->num_rows > 0;
$stmt1->close();

// Check if category is in use by merchants
$stmt2 = $partners->conn->prepare("SELECT 1 FROM partners_merchant WHERE merchant_category = ?");
$stmt2->bind_param("s", $categorycompo);
$stmt2->execute();
$res2 = $stmt2->get_result();
$merch_exists = $res2->num_rows > 0;
$stmt2->close();

if (!$aff_exists && !$merch_exists) {
    // Safe to delete category
    $stmt3 = $partners->conn->prepare("DELETE FROM partners_category WHERE cat_name = ?");
    $stmt3->bind_param("s", $categorycompo);
    if ($stmt3->execute()) {
        $msg = "Category " . htmlspecialchars($categorycompo) . " deleted!";
    } else {
        $msg = "Error deleting category.";
    }
    $stmt3->close();
    header("Location: index.php?Act=category&msg1=" . urlencode($msg));
    exit;
} else {
    $msg = "Can't remove... Members exist in category " . htmlspecialchars($categorycompo);
    header("Location: index.php?Act=category&msg1=" . urlencode($msg));
    exit;
}
?>
