<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireRole([1, 2]);
$db   = getDB();

$id = (int)post('id', 0);
if (!$id) apiError('Job type ID required.', 422);

$stmt = $db->prepare("SELECT * FROM job_card_types WHERE id = ?");
$stmt->execute([$id]);
$type = $stmt->fetch();
if (!$type) apiError('Job type not found.', 404);

// Check if in use — count job cards using this slug
$inUse = $db->prepare("SELECT COUNT(*) FROM job_cards WHERE job_type = ?");
$inUse->execute([$type['slug']]);
$count = (int)$inUse->fetchColumn();

if ($count > 0) {
    // Soft deactivate — can't delete if in use
    $db->prepare("UPDATE job_card_types SET is_active = 0 WHERE id = ?")->execute([$id]);
    apiSuccess([], "Job type deactivated ($count job card(s) use this type).");
}

$db->prepare("DELETE FROM job_card_types WHERE id = ?")->execute([$id]);
apiSuccess([], 'Job type deleted.');
