-- =====================================================================
-- 0031 — TUGAS RUTIN STAFF (generator tugas rutin non-maintenance)
--
-- Mekanisme UNIVERSAL lintas jobdesk SDM/Sales: analog `pm_schedules`+
-- PmGenerator di modul FIX (jadwal PM -> work order harian), tetapi target
-- generasinya = `hr_tasks` (papan task terpadu), BUKAN work_orders.
--
--   template (hr_task_templates)  --RecurringTaskGenerator-->  hr_tasks(kind='instant')
--
-- Contoh pemakaian owner: "resepsionis cek stok amenity tiap pagi",
-- "housekeeping supervisor cek linen tiap shift".
--
-- Konsistensi arsitektur (ditiru PERSIS dari pm_schedules/PmGenerator):
--   * frequency_type ENUM('daily','weekly','monthly') — SUBSET nilai
--     pm_schedules.frequency_type (0001_init) supaya konsisten.
--   * frequency_detail memakai konvensi yang SAMA dgn pm_schedules:
--       - weekly  -> CSV hari ISO-8601 1..7 (Senin=1 .. Minggu=7),
--                    sama seperti pm_schedules.weekly_days.
--       - monthly -> tanggal 1..31 (clamp ke akhir bulan), sama seperti
--                    pm_schedules.monthly_day.
--       - daily   -> NULL.
--   * Idempotensi generator meniru PmSchedule::woExistsForDue(): satu task
--     per (template, due_date). Kunci di sisi hr_tasks = (source_ref =
--     'hr_task_template:{id}', due_date) — TIDAK perlu kolom baru di hr_tasks
--     (source_ref = "referensi bebas ke record asal", 0008).
--
-- CATATAN "jobdesk_id": di codebase ini TIDAK ada tabel `hr_jobdesks`.
-- Entitas "Jobdesk" = `hr_positions` (menu "Jobdesk" -> jobdesks.php ->
-- HrJobdeskPage yang mendaftar hr_positions; ObjectRegistry tipe 'position').
-- Maka jobdesk_id FK ke hr_positions(id), NULLABLE (NULL = tugas lintas
-- jobdesk, tidak terikat satu posisi).
--
-- Kaitan KPI: kpi_definition_id NULLABLE. Bila NULL, saat generasi
-- TaskBoardService::createTask() me-resolve OTOMATIS ke indikator
-- hr_kpi_definitions source='task' departemen task (mekanisme 0019 —
-- TIDAK ada logika KPI baru di sini).
--
-- Jalankan setelah 0008 (hr_tasks, hr_positions, hr_kpi_definitions) & 0022
-- (hr_departments). Nomor 0031 dipilih agar tidak bentrok dgn agent paralel
-- (0028..0030 dicadangkan). Idempoten via schema_migrations (bin/migrate.php).
-- =====================================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 1;
SET default_storage_engine = InnoDB;

-- ---------------------------------------------------------------------
-- 1. hr_task_templates — definisi tugas rutin (template), 1 baris = 1
--    tugas berulang untuk sebuah departemen/jobdesk/karyawan.
-- ---------------------------------------------------------------------
CREATE TABLE hr_task_templates (
    id                INT UNSIGNED NOT NULL AUTO_INCREMENT,
    property_id       INT UNSIGNED NOT NULL,
    department        VARCHAR(60)  NOT NULL
        COMMENT 'kode departemen (match hr_departments.code / hr_tasks.department / hr_kpi_definitions.department) — dipakai kaitan KPI otomatis',
    jobdesk_id        INT UNSIGNED NULL
        COMMENT 'FK hr_positions(id). "jobdesk" = posisi (tak ada tabel hr_jobdesks). NULL = tugas lintas jobdesk',
    title             VARCHAR(200) NOT NULL,
    description       TEXT NULL,
    frequency_type    ENUM('daily','weekly','monthly') NOT NULL DEFAULT 'daily'
        COMMENT 'subset nilai pm_schedules.frequency_type (konsistensi)',
    frequency_detail  VARCHAR(20) NULL
        COMMENT 'daily=NULL; weekly=CSV hari ISO 1-7 (Sen=1, sama pm_schedules.weekly_days); monthly=tanggal 1-31 (clamp akhir bulan, sama pm_schedules.monthly_day)',
    assignee_type     ENUM('employee','department') NOT NULL DEFAULT 'department'
        COMMENT 'employee=tugas ke 1 karyawan; department=tugas milik departemen (tampil di kolom papan per-dept, assignee kosong)',
    assignee_ref      VARCHAR(60)  NOT NULL
        COMMENT 'assignee_type=employee -> hr_employees.id (di-resolve ke users.id saat generasi); assignee_type=department -> kode departemen',
    kpi_definition_id INT UNSIGNED NULL
        COMMENT 'FK hr_kpi_definitions. NULL = auto-resolve per departemen di TaskBoardService::createTask (0019)',
    priority          ENUM('low','normal','high','urgent') NOT NULL DEFAULT 'normal',
    active            TINYINT(1)   NOT NULL DEFAULT 1,
    created_at        DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at        DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_htt_property_active (property_id, active),
    KEY idx_htt_property_dept (property_id, department),
    KEY idx_htt_jobdesk (jobdesk_id),
    KEY idx_htt_kpi (kpi_definition_id),
    CONSTRAINT fk_htt_property FOREIGN KEY (property_id) REFERENCES properties(id)
        ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT fk_htt_jobdesk FOREIGN KEY (jobdesk_id) REFERENCES hr_positions(id)
        ON DELETE SET NULL ON UPDATE CASCADE,
    CONSTRAINT fk_htt_kpi FOREIGN KEY (kpi_definition_id) REFERENCES hr_kpi_definitions(id)
        ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- =====================================================================
-- 2. SEED CONTOH (DUMMY demo — pola "(DUMMY demo)" migrasi 0016/0017/0019)
--    Template aktif; task NYATA baru muncul saat generator dijalankan
--    (bin/generate-recurring-tasks.php atau tombol "Generate hari ini").
--    property_id=1 = satu-satunya properti live.
-- =====================================================================
INSERT INTO hr_task_templates
    (property_id, department, jobdesk_id, title, description, frequency_type,
     frequency_detail, assignee_type, assignee_ref, kpi_definition_id, priority, active)
VALUES
    -- Contoh owner #1: housekeeping supervisor cek linen tiap shift (harian).
    -- assignee_type=department -> tugas milik departemen housekeeping; KPI
    -- di-auto-resolve ke indikator source='task' housekeeping saat generasi.
    (1, 'housekeeping', NULL,
     'Cek kelengkapan & kebersihan stok linen tiap shift (DUMMY demo)',
     'Supervisor housekeeping memeriksa stok linen (sheet, towel, pillowcase) awal shift; catat kekurangan (DUMMY demo — tugas rutin harian).',
     'daily', NULL, 'department', 'housekeeping', NULL, 'normal', 1),

    -- Contoh owner #2: resepsionis cek stok amenity tiap pagi (harian).
    (1, 'front_office', NULL,
     'Cek stok amenity & perlengkapan front desk tiap pagi (DUMMY demo)',
     'Resepsionis memeriksa stok amenity welcome drink, form, kartu kunci setiap pagi; ajukan permintaan bila menipis (DUMMY demo — tugas rutin harian).',
     'daily', NULL, 'department', 'front_office', NULL, 'low', 1);
