-- ============================================================
-- TumbuhSehat v2 - Extended schema (scheduling, admin, progress)
-- Run this AFTER the base schema.sql
-- ============================================================

USE `tumbuhsehat`;

-- ---------- extend users: add admin role + specialty ----------
ALTER TABLE `users` MODIFY COLUMN `role` ENUM('parent','therapist','doctor','admin') NOT NULL;
ALTER TABLE `users`
  ADD COLUMN `specialty` VARCHAR(100) DEFAULT NULL COMMENT 'Therapy type for therapists; field for doctors' AFTER `phone`,
  ADD COLUMN `is_active` TINYINT(1) NOT NULL DEFAULT 1 COMMENT 'Active/inactive staff' AFTER `specialty`,
  ADD COLUMN `notes` TEXT DEFAULT NULL AFTER `is_active`;

-- ---------- therapist specialties reference ----------
CREATE TABLE IF NOT EXISTS `therapist_specialties` (
  `id`   INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(80) NOT NULL,
  `slug` VARCHAR(60) NOT NULL UNIQUE,
  `description` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

INSERT INTO `therapist_specialties` (`name`, `slug`, `description`) VALUES
('Terapi Wicara (Speech Therapy)', 'speech', 'Pengelolaan gangguan bicara, bahasa & komunikasi'),
('Terapi Okupasi', 'occupational', 'Peningkatan keterampilan aktivitas sehari-hari'),
('Terapi Sensori Integrasi', 'sensory-integration', 'Regulasi sensori untuk anak hipersensitif / hiposensitif'),
('Terapi Perilaku (ABA)', 'behavior-aba', 'Modifikasi perilaku berbasis Applied Behavior Analysis'),
('Fisioterapi Anak', 'pediatric-physio', 'Penguatan motorik kasar, keseimbangan, koordinasi'),
('Terapi Perilaku Kognitif', 'cbt', 'Cognitive Behavioral Therapy untuk anak');

-- ---------- scheduling: therapy programs (created by doctor) ----------
CREATE TABLE IF NOT EXISTS `therapy_programs` (
  `id`                INT(11) NOT NULL AUTO_INCREMENT,
  `child_id`          INT(11) NOT NULL,
  `doctor_id`         INT(11) NOT NULL,
  `title`             VARCHAR(200) NOT NULL,
  `diagnosis`         VARCHAR(255) DEFAULT NULL,
  `specialty`         VARCHAR(100) DEFAULT NULL COMMENT 'Therapy specialty needed (drives therapist assignment)',
  `notes`             TEXT DEFAULT NULL,
  `total_sessions`    INT(4) NOT NULL DEFAULT 8 COMMENT 'Total planned sessions',
  `frequency_per_week` TINYINT(1) NOT NULL DEFAULT 2 COMMENT 'Sessions per week',
  `evaluation_after`  INT(4) NOT NULL DEFAULT 6 COMMENT 'Auto-schedule evaluation after this many sessions',
  `status`            ENUM('draft','scheduled','active','paused','completed','cancelled') NOT NULL DEFAULT 'draft',
  `start_date`        DATE DEFAULT NULL,
  `end_date`          DATE 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_prog_child` (`child_id`),
  KEY `idx_prog_doctor` (`doctor_id`),
  KEY `idx_prog_status` (`status`),
  CONSTRAINT `fk_prog_child` FOREIGN KEY (`child_id`) REFERENCES `children`(`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_prog_doctor` FOREIGN KEY (`doctor_id`) REFERENCES `users`(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ---------- scheduled sessions (admin assigns therapist + time slot) ----------
CREATE TABLE IF NOT EXISTS `scheduled_sessions` (
  `id`              INT(11) NOT NULL AUTO_INCREMENT,
  `program_id`      INT(11) DEFAULT NULL COMMENT 'NULL = ad-hoc session',
  `child_id`        INT(11) NOT NULL,
  `therapist_id`    INT(11) NOT NULL,
  `session_date`    DATE NOT NULL,
  `session_time`    TIME NOT NULL DEFAULT '09:00:00',
  `duration_min`    SMALLINT(3) NOT NULL DEFAULT 60,
  `room`            VARCHAR(40) DEFAULT NULL,
  `session_type`    ENUM('regular','evaluation','makeup','trial') NOT NULL DEFAULT 'regular',
  `status`          ENUM('scheduled','confirmed','in_progress','completed','no_show','rescheduled','cancelled') NOT NULL DEFAULT 'scheduled',
  `notes`           TEXT DEFAULT NULL,
  `reschedule_from` INT(11) DEFAULT NULL COMMENT 'Original session ID if rescheduled',
  `reschedule_reason` VARCHAR(255) DEFAULT NULL,
  `requested_by`    INT(11) DEFAULT NULL COMMENT 'User who requested reschedule',
  `new_date`        DATE DEFAULT NULL,
  `new_time`        TIME 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_sched_therapist_date` (`therapist_id`, `session_date`),
  KEY `idx_sched_child_date` (`child_id`, `session_date`),
  KEY `idx_sched_program` (`program_id`),
  CONSTRAINT `fk_sched_child` FOREIGN KEY (`child_id`) REFERENCES `children`(`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_sched_therapist` FOREIGN KEY (`therapist_id`) REFERENCES `users`(`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_sched_program` FOREIGN KEY (`program_id`) REFERENCES `therapy_programs`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ---------- link scheduled_sessions to actual session data ----------
ALTER TABLE `sessions`
  ADD COLUMN `scheduled_session_id` INT(11) DEFAULT NULL AFTER `home_video_id`,
  ADD COLUMN `therapist_id` INT(11) DEFAULT NULL AFTER `scheduled_session_id`,
  ADD KEY `idx_session_scheduled` (`scheduled_session_id`),
  ADD CONSTRAINT `fk_session_scheduled` FOREIGN KEY (`scheduled_session_id`) REFERENCES `scheduled_sessions`(`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `fk_session_therapist_user` FOREIGN KEY (`therapist_id`) REFERENCES `users`(`id`) ON DELETE SET NULL;

-- ---------- availability / time-off for therapists ----------
CREATE TABLE IF NOT EXISTS `therapist_availability` (
  `id`          INT(11) NOT NULL AUTO_INCREMENT,
  `therapist_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,
  `is_available` TINYINT(1) NOT NULL DEFAULT 1,
  `notes`       VARCHAR(128) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_avail_therapist` (`therapist_id`),
  CONSTRAINT `fk_avail_therapist` FOREIGN KEY (`therapist_id`) REFERENCES `users`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE IF NOT EXISTS `therapist_timeoff` (
  `id`          INT(11) NOT NULL AUTO_INCREMENT,
  `therapist_id` INT(11) NOT NULL,
  `start_date`  DATE NOT NULL,
  `end_date`    DATE NOT NULL,
  `reason`      VARCHAR(255) DEFAULT NULL,
  `approved_by` INT(11) DEFAULT NULL,
  `approved_at` DATETIME DEFAULT NULL,
  `status`      ENUM('pending','approved','rejected','cancelled') NOT NULL DEFAULT 'pending',
  `created_at`  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_to_therapist` (`therapist_id`),
  CONSTRAINT `fk_to_therapist` FOREIGN KEY (`therapist_id`) REFERENCES `users`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ---------- progress history (aggregated per program) ----------
CREATE TABLE IF NOT EXISTS `progress_history` (
  `id`               INT(11) NOT NULL AUTO_INCREMENT,
  `child_id`         INT(11) NOT NULL,
  `program_id`       INT(11) DEFAULT NULL,
  `session_number`   INT(4) NOT NULL COMMENT 'Nth session in the program',
  `session_date`     DATE NOT NULL,
  `focus_rating_avg` DECIMAL(3,1) DEFAULT NULL,
  `cooperation_avg`  DECIMAL(3,1) DEFAULT NULL,
  `targets_passed`   INT(4) NOT NULL DEFAULT 0,
  `targets_total`    INT(4) NOT NULL DEFAULT 0,
  `mood_summary`     VARCHAR(32) DEFAULT NULL,
  `therapist_notes`  TEXT DEFAULT NULL,
  `milestone`        VARCHAR(255) DEFAULT NULL,
  `created_at`       DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_ph_child` (`child_id`),
  KEY `idx_ph_program` (`program_id`),
  CONSTRAINT `fk_ph_child` FOREIGN KEY (`child_id`) REFERENCES `children`(`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_ph_program` FOREIGN KEY (`program_id`) REFERENCES `therapy_programs`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ---------- reschedule requests (from parent/therapist) ----------
CREATE TABLE IF NOT EXISTS `reschedule_requests` (
  `id`              INT(11) NOT NULL AUTO_INCREMENT,
  `scheduled_session_id` INT(11) NOT NULL,
  `requested_by`    INT(11) NOT NULL,
  `reason`          VARCHAR(255) DEFAULT NULL,
  `proposed_dates`  JSON DEFAULT NULL COMMENT 'Array of proposed date+time strings',
  `status`          ENUM('pending','approved','rejected','withdrawn') NOT NULL DEFAULT 'pending',
  `reviewed_by`     INT(11) DEFAULT NULL,
  `reviewed_at`     DATETIME DEFAULT NULL,
  `review_notes`    VARCHAR(255) DEFAULT NULL,
  `created_at`      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_rr_session` (`scheduled_session_id`),
  KEY `idx_rr_requester` (`requested_by`),
  CONSTRAINT `fk_rr_session` FOREIGN KEY (`scheduled_session_id`) REFERENCES `scheduled_sessions`(`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_rr_requester` FOREIGN KEY (`requested_by`) REFERENCES `users`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
