<?php
/**
 * Populate pm_templates + pm_template_items from service_templates_catalog.
 *
 * Bridges the two libraries so /PmTemplates (existing designer UI, empty by default)
 * shows the same 8 templates seeded from sitetracker16 patterns. Idempotent per code:
 * re-running deletes the previous (code, version=1) rows and re-inserts.
 *
 * Field-type mapping (my catalog uses a wider set):
 *   CHECK       → CHECK
 *   NUMBER      → NUMBER
 *   PHOTO       → PHOTO
 *   TEXT        → TEXT
 *   LONG_TEXT   → TEXT
 *   DATE        → TEXT     (with unit "date")
 *   DROPDOWN    → TEXT     (with unit "dropdown")
 *   GPS         → TEXT     (with unit "gps")
 *   SCAN        → TEXT     (with unit "scan")
 */
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__DIR__));
require_once ROOT . DS . 'config' . DS . 'config.php';
require_once ROOT . DS . 'core' . DS . 'Application.php';
require_once ROOT . DS . 'core' . DS . 'Model.php';
require_once ROOT . DS . 'core' . DS . 'DB.php';

$db = new DB();

/* Cadence mapping: my catalog's cadence_note → pm_templates.cadence_type/value */
$cadenceFrom = function (string $catCategory, string $cadenceNote, string $scope): array {
    // (type, value)
    if (stripos($cadenceNote, 'run-hour') !== false) {
        if (preg_match('/(\d+)/', $cadenceNote, $m)) return ['HOURS_RUN', (int)$m[1]];
    }
    if (preg_match('/(\d+)\s*day/i', $cadenceNote, $m))    return ['DAYS',   (int)$m[1]];
    if (preg_match('/(\d+)\s*month/i', $cadenceNote, $m))  return ['MONTHS', (int)$m[1]];
    // Fallback per category
    switch ($catCategory) {
        case 'PM_MONTHLY':     return ['DAYS', 30];
        case 'PM_QUARTERLY':   return ['DAYS', 90];
        case 'PM_SEMI_ANNUAL': return ['DAYS', 180];
        case 'PM_ANNUAL':      return ['DAYS', 365];
        case 'PM_FUELTEST':    return ['DAYS', 90];
        case 'CALLOUT':
        case 'CALLOUT_RESOLUTION': return ['NONE', null];
        default:               return ['MONTHS', 1];
    }
};

/* Asset-type lookup */
$assetTypeIds = [];
$atRs = $db->mySelect("SELECT c0d, code FROM asset_types", []) ?: [];
foreach ($atRs as $r) $assetTypeIds[(string)$r['code']] = (int)$r['c0d'];

/* Type mapping: my field_type → pm_template_items.input_type + unit annotation */
$mapType = function (string $t): array {
    // Returns [pm_input_type, unit_hint (or null)]
    switch ($t) {
        case 'CHECK':     return ['CHECK', null];
        case 'NUMBER':    return ['NUMBER', null];
        case 'PHOTO':     return ['PHOTO', null];
        case 'TEXT':      return ['TEXT', null];
        case 'LONG_TEXT': return ['TEXT', null];
        case 'DATE':      return ['TEXT', 'date'];
        case 'DROPDOWN':  return ['TEXT', 'dropdown'];
        case 'GPS':       return ['TEXT', 'gps'];
        case 'SCAN':      return ['TEXT', 'scan'];
        default:          return ['TEXT', null];
    }
};

/* ── Pull the catalog templates ───────────────────────────────────── */
$templates = $db->mySelect(
    "SELECT * FROM service_templates_catalog WHERE is_active = 1 ORDER BY sort_order",
    []
) ?: [];

$totalTpl = 0; $totalItems = 0;
foreach ($templates as $tpl) {
    $code    = (string)$tpl['slug'];
    $name    = (string)$tpl['label'];
    $scope   = ((string)$tpl['scope'] === 'SITE') ? 'SITE' : 'ASSET';
    $atId    = $assetTypeIds[$tpl['scope']] ?? null;  // GEN/AC/BATTERY/SHELTER match asset_types.code
    [$cadType, $cadVal] = $cadenceFrom((string)$tpl['category'], (string)($tpl['cadence_note'] ?? ''), $scope);

    // Wipe prior seed of this code (any version) so re-run is clean
    $priorRs = $db->mySelect("SELECT c0d FROM pm_templates WHERE code = :c", [':c' => $code]) ?: [];
    foreach ($priorRs as $pr) {
        $db->insertUpdate("DELETE FROM pm_template_items WHERE template_id = :t", [':t' => (int)$pr['c0d']]);
    }
    $db->insertUpdate("DELETE FROM pm_templates WHERE code = :c", [':c' => $code]);

    // Insert header
    $r = $db->insertUpdate(
        "INSERT INTO pm_templates
            (asset_type_id, scope, cadence_type, cadence_value, code, name, version, is_active,
             reviewer_role, requires_manager_reconciliation, description)
         VALUES (:at, :sc, :ct, :cv, :cd, :nm, 1, 1, :rv, :rr, :ds)",
        [
            ':at' => $atId,
            ':sc' => $scope,
            ':ct' => $cadType,
            ':cv' => $cadVal,
            ':cd' => $code,
            ':nm' => $name,
            ':rv' => $code === 'GEN-FUELTEST-QTR' ? 'FUEL_DESK' : null,
            ':rr' => $code === 'GEN-FUELTEST-QTR' ? 1 : 0,
            ':ds' => (string)($tpl['description'] ?? ''),
        ]
    );
    $tplId = (int)($r['last_id'] ?? 0);
    if ($tplId <= 0) { echo "  ✗ header insert failed for {$code}\n"; continue; }

    // Insert items — two passes so we can resolve depends_on_slug → depends_on_item_id
    $items = $db->mySelect(
        "SELECT * FROM service_template_items WHERE template_id = :t ORDER BY sort_order, c0d",
        [':t' => (int)$tpl['c0d']]
    ) ?: [];

    $slugToItemId = [];
    // Pass 1 — insert everything without dep FK
    foreach ($items as $it) {
        [$inType, $unitHint] = $mapType((string)$it['field_type']);
        $unit = (string)($it['unit_or_note'] ?? '') ?: $unitHint;
        $ins = $db->insertUpdate(
            "INSERT INTO pm_template_items
                (template_id, sort_order, section, task, input_type, unit, is_required, tracks_qty,
                 depends_on_item_id, depends_on_value)
             VALUES (:t, :so, :sec, :tk, :it, :u, :req, 0, NULL, :dv)",
            [
                ':t'   => $tplId,
                ':so'  => (int)$it['sort_order'],
                ':sec' => (string)$it['section'],
                ':tk'  => (string)$it['field_label'],
                ':it'  => $inType,
                ':u'   => $unit ?: null,
                ':req' => (int)$it['is_required'],
                ':dv'  => (string)($it['depends_on_value'] ?? '') ?: null,
            ]
        );
        $slugToItemId[(string)$it['field_slug']] = (int)($ins['last_id'] ?? 0);
    }
    // Pass 2 — set depends_on_item_id from depends_on_slug
    foreach ($items as $it) {
        $depSlug = (string)($it['depends_on_slug'] ?? '');
        if ($depSlug === '' || empty($slugToItemId[$depSlug])) continue;
        $selfId = $slugToItemId[(string)$it['field_slug']] ?? 0;
        if ($selfId <= 0) continue;
        $db->insertUpdate(
            "UPDATE pm_template_items SET depends_on_item_id = :d WHERE c0d = :id",
            [':d' => $slugToItemId[$depSlug], ':id' => $selfId]
        );
    }

    $totalTpl++;
    $totalItems += count($items);
    echo "  ✓ {$code} → header + " . count($items) . " items (asset_type=" . ($tpl['scope']) . ", cadence={$cadType}/{$cadVal})\n";
}

echo "\n=== DONE · {$totalTpl} templates + {$totalItems} items seeded into pm_templates ===\n";
