<?php
/**
 * Admin API — Delete Category
 * Safety: Prevents deletion if products are linked.
 */
session_start();
header('Content-Type: application/json');

if (empty($_SESSION['admin_logged_in'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

require_once '../../includes/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;

    if (!$id) {
        echo json_encode(['status' => 'error', 'message' => 'Category ID is required.']);
        exit;
    }

    try {
        // Get slug first
        $stmtSlug = $pdo->prepare("SELECT slug FROM categories WHERE id = ?");
        $stmtSlug->execute([$id]);
        $category = $stmtSlug->fetch();

        if (!$category) {
            echo json_encode(['status' => 'error', 'message' => 'Category not found.']);
            exit;
        }

        $slug = $category['slug'];

        // Check if products use this category slug
        $check = $pdo->prepare("SELECT COUNT(*) FROM products WHERE category = ?");
        $check->execute([$slug]);
        if ($check->fetchColumn() > 0) {
            echo json_encode(['status' => 'error', 'message' => 'Cannot delete. This category has products assigned to it.']);
            exit;
        }

        // Delete if safe
        $delete = $pdo->prepare("DELETE FROM categories WHERE id = ?");
        $delete->execute([$id]);
        
        echo json_encode(['status' => 'success', 'message' => 'Category deleted successfully.']);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
}
?>
