-- ============================================================
-- TumbuhSehat v4 - Paket Terapi, Pendaftaran, Jadwal Dokter
-- Run this AFTER schema.sql, schema_v2.sql and schema_v3.sql
--
-- Business flow (alur proses):
--   1. Anak datang ke dokter -> konsultasi/pemeriksaan
--      -> doctor_appointments (visit_type=consultation/examination)
--   2. Dokter membuat therapy_programs (jumlah sesi + goal/tujuan)
--   3. Admin mendaftarkan anak ke paket terapi -> enrollments
--      (konfirmasi ke orang tua -> catat pembayaran)
--   4. Admin menjadwalkan sesi terapi dari paket -> scheduled_sessions
--      (terapis diambil dari package_therapists)
--   5. Sesi fisioterapi dijalankan -> sesi selesai
--   6. Kontrol/konsultasi lanjutan ke dokter bila diperlukan
--      -> doctor_appointments (visit_type=follow_up)
-- ============================================================

USE `tumbuhsehat`;

SET FOREIGN_KEY_CHECKS = 0;

-- ---------- therapy_packages (paket terapi) ----------
CREATE TABLE IF NOT EXISTS `therapy_packages` (
  `id`                 INT(11) NOT NULL AUTO_INCREMENT,
  `clinic_id`          INT(11) DEFAULT NULL COMMENT 'Owning clinic; NULL = template global',
  `name`               VARCHAR(160) NOT NULL COMMENT 'Nama paket, cth: Paket GOLD - 12 Sesi',
  `therapy_type`       VARCHAR(100) NOT NULL COMMENT 'Jenis terapi, cth: Fisioterapi Anak',
  `specialty`         VARCHAR(100) DEFAULT NULL COMMENT 'Spesialitas_bucket untuk therapist',
  `session_count`      INT(4) NOT NULL DEFAULT 8 COMMENT 'Jumlah/lama terapi (jumlah sesi)',
  `frequency_per_week` TINYINT(1) NOT NULL DEFAULT 2 COMMENT 'Sesi per minggu',
  `duration_weeks`     INT(4) DEFAULT NULL COMMENT 'Lama terapi dalam minggu',
  `goal`               TEXT DEFAULT NULL COMMENT 'Tujuan/goal terapi',
  `price`              DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT 'Nilai terapi (Rp)',
  `description`        TEXT DEFAULT NULL,
  `status`             ENUM('draft','active','archived') NOT NULL DEFAULT 'active',
  `created_by`         INT(11) DEFAULT NULL,
  `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_pkg_clinic` (`clinic_id`),
  KEY `idx_pkg_status` (`status`),
  CONSTRAINT `fk_pkg_clinic` FOREIGN KEY (`clinic_id`) REFERENCES `clinics`(`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_pkg_creator` FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ---------- package_therapists (assignment terapis ke paket) ----------
CREATE TABLE IF NOT EXISTS `package_therapists` (
  `id`           INT(11) NOT NULL AUTO_INCREMENT,
  `package_id`   INT(11) NOT NULL,
  `therapist_id` INT(11) NOT NULL,
  `is_primary`   TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Terapis utama paket',
  `created_at`   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_pkg_ther` (`package_id`, `therapist_id`),
  KEY `idx_pt_therapist` (`therapist_id`),
  CONSTRAINT `fk_pt_package` FOREIGN KEY (`package_id`) REFERENCES `therapy_packages`(`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_pt_therapist` FOREIGN KEY (`therapist_id`) REFERENCES `users`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ---------- enrollments (pendaftaran anak ke paket terapi) ----------
CREATE TABLE IF NOT EXISTS `enrollments` (
  `id`                 INT(11) NOT NULL AUTO_INCREMENT,
  `clinic_id`          INT(11) DEFAULT NULL,
  `child_id`           INT(11) NOT NULL,
  `package_id`         INT(11) DEFAULT NULL,
  `program_id`         INT(11) DEFAULT NULL COMMENT 'therapy_programs dari dokter',
  `doctor_id`          INT(11) DEFAULT NULL,
  `therapist_id`       INT(11) DEFAULT NULL,
  `parent_id`          INT(11) DEFAULT NULL,
  `total_sessions`     INT(4) NOT NULL DEFAULT 8,
  `sessions_done`      INT(4) NOT NULL DEFAULT 0,
  `price`              DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT 'Nilai terapi dari paket',
  `payment_status`     ENUM('unpaid','partial','paid','refunded') NOT NULL DEFAULT 'unpaid',
  `payment_method`     VARCHAR(32) DEFAULT NULL COMMENT 'cash/transfer/qr/debit',
  `paid_amount`        DECIMAL(12,2) NOT NULL DEFAULT 0,
  `payment_date`       DATE DEFAULT NULL,
  `parent_confirmed_at` DATETIME DEFAULT NULL COMMENT 'Waktu konfirmasi ke orang tua',
  `status`             ENUM('pending','active','completed','cancelled') NOT NULL DEFAULT 'pending',
  `start_date`         DATE DEFAULT NULL,
  `end_date`           DATE DEFAULT NULL,
  `notes`              TEXT DEFAULT NULL,
  `created_by`         INT(11) DEFAULT NULL,
  `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_enr_child` (`child_id`),
  KEY `idx_enr_package` (`package_id`),
  KEY `idx_enr_clinic` (`clinic_id`),
  KEY `idx_enr_status` (`status`),
  KEY `idx_enr_parent` (`parent_id`),
  KEY `idx_enr_therapist` (`therapist_id`),
  CONSTRAINT `fk_enr_child` FOREIGN KEY (`child_id`) REFERENCES `children`(`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_enr_package` FOREIGN KEY (`package_id`) REFERENCES `therapy_packages`(`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_enr_program` FOREIGN KEY (`program_id`) REFERENCES `therapy_programs`(`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_enr_doctor` FOREIGN KEY (`doctor_id`) REFERENCES `users`(`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_enr_therapist` FOREIGN KEY (`therapist_id`) REFERENCES `users`(`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_enr_parent` FOREIGN KEY (`parent_id`) REFERENCES `users`(`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_enr_clinic` FOREIGN KEY (`clinic_id`) REFERENCES `clinics`(`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_enr_creator` FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ---------- enrollment_goals (monitoring progress per tujuan) ----------
CREATE TABLE IF NOT EXISTS `enrollment_goals` (
  `id`            INT(11) NOT NULL AUTO_INCREMENT,
  `enrollment_id` INT(11) NOT NULL,
  `goal_text`     VARCHAR(255) NOT NULL,
  `description`   TEXT DEFAULT NULL,
  `target_value`  VARCHAR(64) DEFAULT NULL COMMENT 'Target, cth: 10 detik',
  `current_value` VARCHAR(64) DEFAULT NULL COMMENT 'Capaian saat ini',
  `unit`          VARCHAR(32) DEFAULT NULL,
  `status`        ENUM('not_started','in_progress','achieved','not_achieved') NOT NULL DEFAULT 'not_started',
  `progress_pct`  TINYINT(3) NOT NULL DEFAULT 0 COMMENT '0..100',
  `achieved_at`   DATETIME DEFAULT NULL,
  `sort_order`    INT(4) NOT NULL DEFAULT 0,
  `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_eg_enrollment` (`enrollment_id`),
  CONSTRAINT `fk_eg_enrollment` FOREIGN KEY (`enrollment_id`) REFERENCES `enrollments`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ---------- doctor_schedules (jadwal kerja dokter) ----------
CREATE TABLE IF NOT EXISTS `doctor_schedules` (
  `id`           INT(11) NOT NULL AUTO_INCREMENT,
  `clinic_id`    INT(11) DEFAULT NULL,
  `doctor_id`    INT(11) NOT NULL,
  `day_of_week`  TINYINT(1) NOT NULL COMMENT '0=Sun..6=Sat',
  `start_time`   TIME NOT NULL,
  `end_time`     TIME NOT NULL,
  `slot_minutes` SMALLINT(3) NOT NULL DEFAULT 30 COMMENT 'Durasi slot konsultasi',
  `max_patients` SMALLINT(3) NOT NULL DEFAULT 20,
  `is_active`    TINYINT(1) NOT NULL DEFAULT 1,
  `notes`        VARCHAR(255) DEFAULT NULL,
  `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_ds_doctor` (`doctor_id`),
  KEY `idx_ds_clinic` (`clinic_id`),
  CONSTRAINT `fk_ds_doctor` FOREIGN KEY (`doctor_id`) REFERENCES `users`(`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_ds_clinic` FOREIGN KEY (`clinic_id`) REFERENCES `clinics`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ---------- doctor_appointments (konsultasi / pemeriksaan anak) ----------
CREATE TABLE IF NOT EXISTS `doctor_appointments` (
  `id`               INT(11) NOT NULL AUTO_INCREMENT,
  `clinic_id`        INT(11) DEFAULT NULL,
  `doctor_id`        INT(11) NOT NULL,
  `child_id`         INT(11) NOT NULL,
  `parent_id`        INT(11) DEFAULT NULL,
  `appointment_date` DATE NOT NULL,
  `appointment_time` TIME NOT NULL DEFAULT '09:00:00',
  `duration_min`     SMALLINT(3) NOT NULL DEFAULT 30,
  `visit_type`       ENUM('consultation','examination','follow_up') NOT NULL DEFAULT 'consultation',
  `status`           ENUM('scheduled','completed','cancelled','no_show') NOT NULL DEFAULT 'scheduled',
  `diagnosis`        VARCHAR(255) DEFAULT NULL,
  `recommendation`   TEXT DEFAULT NULL COMMENT 'Rekomendasi dokter (dipakai admin saat pendaftaran)',
  `program_id`       INT(11) DEFAULT NULL COMMENT 'therapy_programs yang dibuat dokter',
  `notes`            TEXT DEFAULT NULL,
  `created_by`       INT(11) DEFAULT NULL,
  `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_da_doctor_date` (`doctor_id`, `appointment_date`),
  KEY `idx_da_child` (`child_id`),
  KEY `idx_da_clinic` (`clinic_id`),
  KEY `idx_da_status` (`status`),
  CONSTRAINT `fk_da_doctor` FOREIGN KEY (`doctor_id`) REFERENCES `users`(`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_da_child` FOREIGN KEY (`child_id`) REFERENCES `children`(`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_da_parent` FOREIGN KEY (`parent_id`) REFERENCES `users`(`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_da_clinic` FOREIGN KEY (`clinic_id`) REFERENCES `clinics`(`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_da_program` FOREIGN KEY (`program_id`) REFERENCES `therapy_programs`(`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_da_creator` FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ---------- link scheduled_sessions -> enrollment ----------
ALTER TABLE `scheduled_sessions`
  ADD COLUMN `enrollment_id` INT(11) DEFAULT NULL AFTER `program_id`,
  ADD KEY `idx_sched_enrollment` (`enrollment_id`),
  ADD CONSTRAINT `fk_sched_enrollment` FOREIGN KEY (`enrollment_id`) REFERENCES `enrollments`(`id`) ON DELETE SET NULL;

-- ---------- link therapy_programs -> package ----------
ALTER TABLE `therapy_programs`
  ADD COLUMN `package_id` INT(11) DEFAULT NULL AFTER `child_id`,
  ADD KEY `idx_prog_package` (`package_id`),
  ADD CONSTRAINT `fk_prog_package` FOREIGN KEY (`package_id`) REFERENCES `therapy_packages`(`id`) ON DELETE SET NULL;

SET FOREIGN_KEY_CHECKS = 1;
