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

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

$id = (int) post('id', 0);
$name = trim(post('name', ''));
$description = trim(post('description', ''));
$isActive = post('is_active', 1) ? 1 : 0;
$sortOrder = (int) post('sort_order', 0);
$defaultPlanningItems = post('default_planning_items', null);   // JSON string or array
$defaultChecklistItems = post('default_checklist_items', null);  // JSON string or array

if (!$name)
    apiError('Type name is required.', 422);

// Normalise JSON fields — accept array or JSON string
function normaliseJson($val): ?string
{
    if ($val === null || $val === '')
        return null;
    if (is_array($val))
        return json_encode(array_values($val));
    if (is_string($val)) {
        $decoded = json_decode($val, true);
        return json_last_error() === JSON_ERROR_NONE ? json_encode(array_values($decoded)) : null;
    }
    return null;
}

$planJson = normaliseJson($defaultPlanningItems);
$checkJson = normaliseJson($defaultChecklistItems);

// Generate slug from name
$slug = strtolower(trim(preg_replace('/[^a-zA-Z0-9_]/', '_', str_replace(' ', '_', $name)), '_'));
$slug = preg_replace('/_+/', '_', $slug);

// Check column exists (migration guard)
$hasCols = false;
try {
    $chk = $db->query("SHOW COLUMNS FROM job_card_types LIKE 'default_planning_items'");
    $hasCols = $chk && $chk->rowCount() > 0;
} catch (Exception $e) {
}

try {
    // Ensure job_type column is wide enough to hold slugs
    try {
        $db->exec("ALTER TABLE job_cards MODIFY COLUMN job_type VARCHAR(120) NOT NULL DEFAULT 'general'");
    } catch (Exception $ignored) {
    }

    if ($id) {
        // Fetch current slug before overwriting so we can cascade-update job_cards
        $oldRow = $db->prepare("SELECT slug FROM job_card_types WHERE id = ?");
        $oldRow->execute([$id]);
        $oldSlug = $oldRow->fetchColumn();

        $ex = $db->prepare("SELECT id FROM job_card_types WHERE slug = ? AND id != ?");
        $ex->execute([$slug, $id]);
        if ($ex->fetch())
            $slug = $slug . '_' . $id;

        if ($hasCols) {
            $db->prepare("
                UPDATE job_card_types SET
                    name                   = ?,
                    slug                   = ?,
                    description            = ?,
                    is_active              = ?,
                    sort_order             = ?,
                    default_planning_items  = ?,
                    default_checklist_items = ?,
                    updated_at             = NOW()
                WHERE id = ?
            ")->execute([$name, $slug, $description ?: null, $isActive, $sortOrder, $planJson, $checkJson, $id]);
        } else {
            $db->prepare("
                UPDATE job_card_types SET
                    name        = ?,
                    slug        = ?,
                    description = ?,
                    is_active   = ?,
                    sort_order  = ?,
                    updated_at  = NOW()
                WHERE id = ?
            ")->execute([$name, $slug, $description ?: null, $isActive, $sortOrder, $id]);
        }

        // Cascade slug rename to all job cards that reference the old slug
        if ($oldSlug && $oldSlug !== $slug) {
            $db->prepare("UPDATE job_cards SET job_type = ? WHERE job_type = ?")
                ->execute([$slug, $oldSlug]);
        }
    } else {
        $ex = $db->prepare("SELECT id FROM job_card_types WHERE slug = ?");
        $ex->execute([$slug]);
        if ($ex->fetch())
            $slug = $slug . '_' . uniqid();

        if ($hasCols) {
            $db->prepare("
                INSERT INTO job_card_types
                    (name, slug, description, is_active, sort_order, default_planning_items, default_checklist_items, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ")->execute([$name, $slug, $description ?: null, $isActive, $sortOrder, $planJson, $checkJson, $user['id']]);
        } else {
            $db->prepare("
                INSERT INTO job_card_types (name, slug, description, is_active, sort_order, created_by)
                VALUES (?, ?, ?, ?, ?, ?)
            ")->execute([$name, $slug, $description ?: null, $isActive, $sortOrder, $user['id']]);
        }
        $id = (int) $db->lastInsertId();
    }

    apiSuccess(['id' => $id, 'slug' => $slug], 'Job card type saved.');
} catch (Exception $e) {
    apiError('Failed to save type: ' . $e->getMessage(), 500);
}