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

$user = requireAuth();
$db = getDB();

// Check if new columns exist
$hasCols = false;
try {
    $chk = $db->query("SHOW COLUMNS FROM job_card_types LIKE 'default_planning_items'");
    $hasCols = $chk && $chk->rowCount() > 0;
} catch (Exception $e) {
}

$extraCols = $hasCols
    ? ", jct.default_planning_items, jct.default_checklist_items"
    : ", NULL AS default_planning_items, NULL AS default_checklist_items";

$stmt = $db->prepare("
    SELECT jct.*, ct.name AS default_checklist_name
    $extraCols
    FROM job_card_types jct
    LEFT JOIN checklist_templates ct ON ct.id = jct.default_checklist_id
    ORDER BY jct.sort_order ASC, jct.name ASC
");
$stmt->execute();
$types = $stmt->fetchAll();

// Parse JSON fields
foreach ($types as &$t) {
    $t['default_planning_items'] = $t['default_planning_items']
        ? json_decode($t['default_planning_items'], true) : [];
    $t['default_checklist_items'] = $t['default_checklist_items']
        ? json_decode($t['default_checklist_items'], true) : [];
}

apiSuccess(['types' => $types]);